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::CommitmentTxConfirmed);
1195 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1197 // Check we only broadcast 1 timeout tx
1198 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1199 assert_eq!(claim_txn.len(), 8);
1200 assert_eq!(claim_txn[1], claim_txn[4]);
1201 assert_eq!(claim_txn[2], claim_txn[5]);
1202 check_spends!(claim_txn[1], chan_1.3);
1203 check_spends!(claim_txn[2], claim_txn[1]);
1204 check_spends!(claim_txn[7], claim_txn[1]);
1206 assert_eq!(claim_txn[0].input.len(), 1);
1207 assert_eq!(claim_txn[3].input.len(), 1);
1208 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1210 assert_eq!(claim_txn[0].input.len(), 1);
1211 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1212 check_spends!(claim_txn[0], remote_txn[0]);
1213 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1214 assert_eq!(claim_txn[6].input.len(), 1);
1215 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1216 check_spends!(claim_txn[6], remote_txn[0]);
1217 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1219 let events = nodes[0].node.get_and_clear_pending_msg_events();
1220 assert_eq!(events.len(), 3);
1223 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1224 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1225 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1226 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1228 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1229 assert!(update_add_htlcs.is_empty());
1230 assert!(update_fail_htlcs.is_empty());
1231 assert_eq!(update_fulfill_htlcs.len(), 1);
1232 assert!(update_fail_malformed_htlcs.is_empty());
1233 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1235 _ => panic!("Unexpected event"),
1241 fn test_basic_channel_reserve() {
1242 let chanmon_cfgs = create_chanmon_cfgs(2);
1243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1245 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1246 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1247 let logger = test_utils::TestLogger::new();
1249 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1250 let channel_reserve = chan_stat.channel_reserve_msat;
1252 // The 2* and +1 are for the fee spike reserve.
1253 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
1254 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1255 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1256 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1257 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1258 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1260 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1262 &APIError::ChannelUnavailable{ref err} =>
1263 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1264 _ => panic!("Unexpected error variant"),
1267 _ => panic!("Unexpected error variant"),
1269 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1270 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1272 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1276 fn test_fee_spike_violation_fails_htlc() {
1277 let chanmon_cfgs = create_chanmon_cfgs(2);
1278 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1279 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1280 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1281 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1283 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1284 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1285 let secp_ctx = Secp256k1::new();
1286 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1288 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1290 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1291 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1292 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1293 let msg = msgs::UpdateAddHTLC {
1296 amount_msat: htlc_msat,
1297 payment_hash: payment_hash,
1298 cltv_expiry: htlc_cltv,
1299 onion_routing_packet: onion_packet,
1302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1304 // Now manually create the commitment_signed message corresponding to the update_add
1305 // nodes[0] just sent. In the code for construction of this message, "local" refers
1306 // to the sender of the message, and "remote" refers to the receiver.
1308 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1310 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1312 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1313 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1314 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1315 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1316 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1317 let chan_signer = local_chan.get_signer();
1318 // Make the signer believe we validated another commitment, so we can release the secret
1319 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1321 let pubkeys = chan_signer.pubkeys();
1322 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1323 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1324 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1325 chan_signer.pubkeys().funding_pubkey)
1327 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1328 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1329 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1330 let chan_signer = remote_chan.get_signer();
1331 let pubkeys = chan_signer.pubkeys();
1332 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1333 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1334 chan_signer.pubkeys().funding_pubkey)
1337 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1338 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1339 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1341 // Build the remote commitment transaction so we can sign it, and then later use the
1342 // signature for the commitment_signed message.
1343 let local_chan_balance = 1313;
1345 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1347 amount_msat: 3460001,
1348 cltv_expiry: htlc_cltv,
1350 transaction_output_index: Some(1),
1353 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1356 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1357 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1358 let local_chan_signer = local_chan.get_signer();
1359 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1363 false, local_funding, remote_funding,
1364 commit_tx_keys.clone(),
1366 &mut vec![(accepted_htlc_info, ())],
1367 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1369 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1372 let commit_signed_msg = msgs::CommitmentSigned {
1375 htlc_signatures: res.1
1378 // Send the commitment_signed message to the nodes[1].
1379 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1380 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1382 // Send the RAA to nodes[1].
1383 let raa_msg = msgs::RevokeAndACK {
1385 per_commitment_secret: local_secret,
1386 next_per_commitment_point: next_local_point
1388 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1390 let events = nodes[1].node.get_and_clear_pending_msg_events();
1391 assert_eq!(events.len(), 1);
1392 // Make sure the HTLC failed in the way we expect.
1394 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1395 assert_eq!(update_fail_htlcs.len(), 1);
1396 update_fail_htlcs[0].clone()
1398 _ => panic!("Unexpected event"),
1400 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1401 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1403 check_added_monitors!(nodes[1], 2);
1407 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1408 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1409 // Set the fee rate for the channel very high, to the point where the fundee
1410 // sending any above-dust amount would result in a channel reserve violation.
1411 // In this test we check that we would be prevented from sending an HTLC in
1413 let feerate_per_kw = 253;
1414 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1415 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1418 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1420 let mut push_amt = 100_000_000;
1421 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1422 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1424 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1426 // Sending exactly enough to hit the reserve amount should be accepted
1427 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1429 // However one more HTLC should be significantly over the reserve amount and fail.
1430 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1431 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1432 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1433 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1434 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1438 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1439 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1440 // Set the fee rate for the channel very high, to the point where the funder
1441 // receiving 1 update_add_htlc would result in them closing the channel due
1442 // to channel reserve violation. This close could also happen if the fee went
1443 // up a more realistic amount, but many HTLCs were outstanding at the time of
1444 // the update_add_htlc.
1445 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1446 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1447 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1448 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1449 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1450 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1452 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1453 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1454 let secp_ctx = Secp256k1::new();
1455 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1456 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1457 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1458 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1459 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1460 let msg = msgs::UpdateAddHTLC {
1463 amount_msat: htlc_msat + 1,
1464 payment_hash: payment_hash,
1465 cltv_expiry: htlc_cltv,
1466 onion_routing_packet: onion_packet,
1469 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1470 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1471 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1472 assert_eq!(nodes[0].node.list_channels().len(), 0);
1473 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1474 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1475 check_added_monitors!(nodes[0], 1);
1476 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() });
1480 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1481 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1482 // calculating our commitment transaction fee (this was previously broken).
1483 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1484 let feerate_per_kw = 253;
1485 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1486 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1488 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1489 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1490 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1492 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1493 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1494 // transaction fee with 0 HTLCs (183 sats)).
1495 let mut push_amt = 100_000_000;
1496 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1497 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1498 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1500 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1501 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1502 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1503 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1504 // commitment transaction fee.
1505 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1507 // One more than the dust amt should fail, however.
1508 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1509 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1510 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1514 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1515 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1516 // calculating our counterparty's commitment transaction fee (this was previously broken).
1517 let chanmon_cfgs = create_chanmon_cfgs(2);
1518 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1519 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1520 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1521 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1523 let payment_amt = 46000; // Dust amount
1524 // In the previous code, these first four payments would succeed.
1525 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1526 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1527 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1528 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1530 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1531 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1532 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1533 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1534 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1535 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1537 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1538 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1539 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1540 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1544 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1545 let chanmon_cfgs = create_chanmon_cfgs(3);
1546 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1547 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1548 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1549 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1550 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1553 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1554 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1555 let feerate = get_feerate!(nodes[0], chan.2);
1557 // Add a 2* and +1 for the fee spike reserve.
1558 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1559 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1560 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1562 // Add a pending HTLC.
1563 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1564 let payment_event_1 = {
1565 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1566 check_added_monitors!(nodes[0], 1);
1568 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1569 assert_eq!(events.len(), 1);
1570 SendEvent::from_event(events.remove(0))
1572 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1574 // Attempt to trigger a channel reserve violation --> payment failure.
1575 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1576 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1577 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1578 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1580 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1581 let secp_ctx = Secp256k1::new();
1582 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1583 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1584 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1585 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1586 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1587 let msg = msgs::UpdateAddHTLC {
1590 amount_msat: htlc_msat + 1,
1591 payment_hash: our_payment_hash_1,
1592 cltv_expiry: htlc_cltv,
1593 onion_routing_packet: onion_packet,
1596 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1597 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1598 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1599 assert_eq!(nodes[1].node.list_channels().len(), 1);
1600 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1601 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1602 check_added_monitors!(nodes[1], 1);
1603 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1607 fn test_inbound_outbound_capacity_is_not_zero() {
1608 let chanmon_cfgs = create_chanmon_cfgs(2);
1609 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1610 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1611 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1612 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1613 let channels0 = node_chanmgrs[0].list_channels();
1614 let channels1 = node_chanmgrs[1].list_channels();
1615 assert_eq!(channels0.len(), 1);
1616 assert_eq!(channels1.len(), 1);
1618 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1619 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1620 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1622 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1623 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1626 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1627 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1631 fn test_channel_reserve_holding_cell_htlcs() {
1632 let chanmon_cfgs = create_chanmon_cfgs(3);
1633 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1634 // When this test was written, the default base fee floated based on the HTLC count.
1635 // It is now fixed, so we simply set the fee to the expected value here.
1636 let mut config = test_default_channel_config();
1637 config.channel_options.forwarding_fee_base_msat = 239;
1638 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1639 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1640 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1641 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1643 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1644 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1646 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1647 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1649 macro_rules! expect_forward {
1651 let mut events = $node.node.get_and_clear_pending_msg_events();
1652 assert_eq!(events.len(), 1);
1653 check_added_monitors!($node, 1);
1654 let payment_event = SendEvent::from_event(events.remove(0));
1659 let feemsat = 239; // set above
1660 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1661 let feerate = get_feerate!(nodes[0], chan_1.2);
1663 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1665 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1667 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1668 route.paths[0].last_mut().unwrap().fee_msat += 1;
1669 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1670 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1671 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1672 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1673 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1676 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1677 // nodes[0]'s wealth
1679 let amt_msat = recv_value_0 + total_fee_msat;
1680 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1681 // Also, ensure that each payment has enough to be over the dust limit to
1682 // ensure it'll be included in each commit tx fee calculation.
1683 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1684 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1685 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1688 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1690 let (stat01_, stat11_, stat12_, stat22_) = (
1691 get_channel_value_stat!(nodes[0], chan_1.2),
1692 get_channel_value_stat!(nodes[1], chan_1.2),
1693 get_channel_value_stat!(nodes[1], chan_2.2),
1694 get_channel_value_stat!(nodes[2], chan_2.2),
1697 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1698 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1699 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1700 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1701 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1704 // adding pending output.
1705 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1706 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1707 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1708 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1709 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1710 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1711 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1712 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1713 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1715 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1716 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1717 let amt_msat_1 = recv_value_1 + total_fee_msat;
1719 let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1720 let payment_event_1 = {
1721 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1722 check_added_monitors!(nodes[0], 1);
1724 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1725 assert_eq!(events.len(), 1);
1726 SendEvent::from_event(events.remove(0))
1728 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1730 // channel reserve test with htlc pending output > 0
1731 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1733 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1734 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1735 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1736 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1739 // split the rest to test holding cell
1740 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1741 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1742 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1743 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1745 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1746 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1749 // now see if they go through on both sides
1750 let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1751 // but this will stuck in the holding cell
1752 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1753 check_added_monitors!(nodes[0], 0);
1754 let events = nodes[0].node.get_and_clear_pending_events();
1755 assert_eq!(events.len(), 0);
1757 // test with outbound holding cell amount > 0
1759 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1760 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1761 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1762 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1763 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
1766 let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1767 // this will also stuck in the holding cell
1768 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1769 check_added_monitors!(nodes[0], 0);
1770 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1771 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1773 // flush the pending htlc
1774 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1775 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1776 check_added_monitors!(nodes[1], 1);
1778 // the pending htlc should be promoted to committed
1779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1780 check_added_monitors!(nodes[0], 1);
1781 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1783 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1784 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1785 // No commitment_signed so get_event_msg's assert(len == 1) passes
1786 check_added_monitors!(nodes[0], 1);
1788 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1789 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1790 check_added_monitors!(nodes[1], 1);
1792 expect_pending_htlcs_forwardable!(nodes[1]);
1794 let ref payment_event_11 = expect_forward!(nodes[1]);
1795 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1796 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1798 expect_pending_htlcs_forwardable!(nodes[2]);
1799 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1801 // flush the htlcs in the holding cell
1802 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1803 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1804 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1805 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1806 expect_pending_htlcs_forwardable!(nodes[1]);
1808 let ref payment_event_3 = expect_forward!(nodes[1]);
1809 assert_eq!(payment_event_3.msgs.len(), 2);
1810 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1811 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1813 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1814 expect_pending_htlcs_forwardable!(nodes[2]);
1816 let events = nodes[2].node.get_and_clear_pending_events();
1817 assert_eq!(events.len(), 2);
1819 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1820 assert_eq!(our_payment_hash_21, *payment_hash);
1821 assert_eq!(recv_value_21, amt);
1823 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1824 assert!(payment_preimage.is_none());
1825 assert_eq!(our_payment_secret_21, *payment_secret);
1827 _ => panic!("expected PaymentPurpose::InvoicePayment")
1830 _ => panic!("Unexpected event"),
1833 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1834 assert_eq!(our_payment_hash_22, *payment_hash);
1835 assert_eq!(recv_value_22, amt);
1837 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1838 assert!(payment_preimage.is_none());
1839 assert_eq!(our_payment_secret_22, *payment_secret);
1841 _ => panic!("expected PaymentPurpose::InvoicePayment")
1844 _ => panic!("Unexpected event"),
1847 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1848 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1849 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1851 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1852 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1853 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1855 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1856 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
1857 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1858 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1859 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1861 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1862 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1866 fn channel_reserve_in_flight_removes() {
1867 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1868 // can send to its counterparty, but due to update ordering, the other side may not yet have
1869 // considered those HTLCs fully removed.
1870 // This tests that we don't count HTLCs which will not be included in the next remote
1871 // commitment transaction towards the reserve value (as it implies no commitment transaction
1872 // will be generated which violates the remote reserve value).
1873 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1875 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1876 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1877 // you only consider the value of the first HTLC, it may not),
1878 // * start routing a third HTLC from A to B,
1879 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1880 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1881 // * deliver the first fulfill from B
1882 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1884 // * deliver A's response CS and RAA.
1885 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1886 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1887 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1888 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1889 let chanmon_cfgs = create_chanmon_cfgs(2);
1890 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1891 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1892 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1893 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1894 let logger = test_utils::TestLogger::new();
1896 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1897 // Route the first two HTLCs.
1898 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1899 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1901 // Start routing the third HTLC (this is just used to get everyone in the right state).
1902 let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
1904 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1905 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
1906 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1907 check_added_monitors!(nodes[0], 1);
1908 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1909 assert_eq!(events.len(), 1);
1910 SendEvent::from_event(events.remove(0))
1913 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1914 // initial fulfill/CS.
1915 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1916 check_added_monitors!(nodes[1], 1);
1917 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1919 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1920 // remove the second HTLC when we send the HTLC back from B to A.
1921 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1922 check_added_monitors!(nodes[1], 1);
1923 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1925 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1926 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1927 check_added_monitors!(nodes[0], 1);
1928 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1929 expect_payment_sent!(nodes[0], payment_preimage_1);
1931 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1932 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1933 check_added_monitors!(nodes[1], 1);
1934 // B is already AwaitingRAA, so cant generate a CS here
1935 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1937 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1938 check_added_monitors!(nodes[1], 1);
1939 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1941 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1942 check_added_monitors!(nodes[0], 1);
1943 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1945 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1946 check_added_monitors!(nodes[1], 1);
1947 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1949 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1950 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1951 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1952 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1953 // on-chain as necessary).
1954 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1956 check_added_monitors!(nodes[0], 1);
1957 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1958 expect_payment_sent!(nodes[0], payment_preimage_2);
1960 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1961 check_added_monitors!(nodes[1], 1);
1962 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1964 expect_pending_htlcs_forwardable!(nodes[1]);
1965 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1967 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1968 // resolve the second HTLC from A's point of view.
1969 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1970 check_added_monitors!(nodes[0], 1);
1971 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1973 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1974 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1975 let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
1977 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1978 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
1979 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1980 check_added_monitors!(nodes[1], 1);
1981 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1982 assert_eq!(events.len(), 1);
1983 SendEvent::from_event(events.remove(0))
1986 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1987 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1988 check_added_monitors!(nodes[0], 1);
1989 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1991 // Now just resolve all the outstanding messages/HTLCs for completeness...
1993 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1994 check_added_monitors!(nodes[1], 1);
1995 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1997 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1998 check_added_monitors!(nodes[1], 1);
2000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2001 check_added_monitors!(nodes[0], 1);
2002 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2004 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2005 check_added_monitors!(nodes[1], 1);
2006 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2008 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2009 check_added_monitors!(nodes[0], 1);
2011 expect_pending_htlcs_forwardable!(nodes[0]);
2012 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2014 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2015 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2019 fn channel_monitor_network_test() {
2020 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2021 // tests that ChannelMonitor is able to recover from various states.
2022 let chanmon_cfgs = create_chanmon_cfgs(5);
2023 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2024 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2025 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2027 // Create some initial channels
2028 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2029 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2030 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2031 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2033 // Make sure all nodes are at the same starting height
2034 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2035 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2036 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2037 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2038 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2040 // Rebalance the network a bit by relaying one payment through all the channels...
2041 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2042 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2043 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2044 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2046 // Simple case with no pending HTLCs:
2047 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2048 check_added_monitors!(nodes[1], 1);
2049 check_closed_broadcast!(nodes[1], false);
2051 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2052 assert_eq!(node_txn.len(), 1);
2053 mine_transaction(&nodes[0], &node_txn[0]);
2054 check_added_monitors!(nodes[0], 1);
2055 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2057 check_closed_broadcast!(nodes[0], true);
2058 assert_eq!(nodes[0].node.list_channels().len(), 0);
2059 assert_eq!(nodes[1].node.list_channels().len(), 1);
2060 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2061 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2063 // One pending HTLC is discarded by the force-close:
2064 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2066 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2067 // broadcasted until we reach the timelock time).
2068 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2069 check_closed_broadcast!(nodes[1], false);
2070 check_added_monitors!(nodes[1], 1);
2072 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2073 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2074 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2075 mine_transaction(&nodes[2], &node_txn[0]);
2076 check_added_monitors!(nodes[2], 1);
2077 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2079 check_closed_broadcast!(nodes[2], true);
2080 assert_eq!(nodes[1].node.list_channels().len(), 0);
2081 assert_eq!(nodes[2].node.list_channels().len(), 1);
2082 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2083 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2085 macro_rules! claim_funds {
2086 ($node: expr, $prev_node: expr, $preimage: expr) => {
2088 assert!($node.node.claim_funds($preimage));
2089 check_added_monitors!($node, 1);
2091 let events = $node.node.get_and_clear_pending_msg_events();
2092 assert_eq!(events.len(), 1);
2094 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2095 assert!(update_add_htlcs.is_empty());
2096 assert!(update_fail_htlcs.is_empty());
2097 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2099 _ => panic!("Unexpected event"),
2105 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2106 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2107 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2108 check_added_monitors!(nodes[2], 1);
2109 check_closed_broadcast!(nodes[2], false);
2110 let node2_commitment_txid;
2112 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2113 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2114 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2115 node2_commitment_txid = node_txn[0].txid();
2117 // Claim the payment on nodes[3], giving it knowledge of the preimage
2118 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2119 mine_transaction(&nodes[3], &node_txn[0]);
2120 check_added_monitors!(nodes[3], 1);
2121 check_preimage_claim(&nodes[3], &node_txn);
2123 check_closed_broadcast!(nodes[3], true);
2124 assert_eq!(nodes[2].node.list_channels().len(), 0);
2125 assert_eq!(nodes[3].node.list_channels().len(), 1);
2126 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2127 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2129 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2130 // confusing us in the following tests.
2131 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2133 // One pending HTLC to time out:
2134 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2135 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2138 let (close_chan_update_1, close_chan_update_2) = {
2139 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2140 let events = nodes[3].node.get_and_clear_pending_msg_events();
2141 assert_eq!(events.len(), 2);
2142 let close_chan_update_1 = match events[0] {
2143 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2146 _ => panic!("Unexpected event"),
2149 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2150 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2152 _ => panic!("Unexpected event"),
2154 check_added_monitors!(nodes[3], 1);
2156 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2158 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2159 node_txn.retain(|tx| {
2160 if tx.input[0].previous_output.txid == node2_commitment_txid {
2166 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2168 // Claim the payment on nodes[4], giving it knowledge of the preimage
2169 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2171 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2172 let events = nodes[4].node.get_and_clear_pending_msg_events();
2173 assert_eq!(events.len(), 2);
2174 let close_chan_update_2 = match events[0] {
2175 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2178 _ => panic!("Unexpected event"),
2181 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2182 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2184 _ => panic!("Unexpected event"),
2186 check_added_monitors!(nodes[4], 1);
2187 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2189 mine_transaction(&nodes[4], &node_txn[0]);
2190 check_preimage_claim(&nodes[4], &node_txn);
2191 (close_chan_update_1, close_chan_update_2)
2193 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2194 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2195 assert_eq!(nodes[3].node.list_channels().len(), 0);
2196 assert_eq!(nodes[4].node.list_channels().len(), 0);
2198 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2199 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2200 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2204 fn test_justice_tx() {
2205 // Test justice txn built on revoked HTLC-Success tx, against both sides
2206 let mut alice_config = UserConfig::default();
2207 alice_config.channel_options.announced_channel = true;
2208 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2209 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2210 let mut bob_config = UserConfig::default();
2211 bob_config.channel_options.announced_channel = true;
2212 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2213 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2214 let user_cfgs = [Some(alice_config), Some(bob_config)];
2215 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2216 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2217 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2218 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2219 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2220 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2221 // Create some new channels:
2222 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2224 // A pending HTLC which will be revoked:
2225 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2226 // Get the will-be-revoked local txn from nodes[0]
2227 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2228 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2229 assert_eq!(revoked_local_txn[0].input.len(), 1);
2230 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2231 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2232 assert_eq!(revoked_local_txn[1].input.len(), 1);
2233 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2234 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2235 // Revoke the old state
2236 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2239 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2241 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2242 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2243 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2245 check_spends!(node_txn[0], revoked_local_txn[0]);
2246 node_txn.swap_remove(0);
2247 node_txn.truncate(1);
2249 check_added_monitors!(nodes[1], 1);
2250 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2251 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2253 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2254 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2255 // Verify broadcast of revoked HTLC-timeout
2256 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2257 check_added_monitors!(nodes[0], 1);
2258 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2259 // Broadcast revoked HTLC-timeout on node 1
2260 mine_transaction(&nodes[1], &node_txn[1]);
2261 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2263 get_announce_close_broadcast_events(&nodes, 0, 1);
2265 assert_eq!(nodes[0].node.list_channels().len(), 0);
2266 assert_eq!(nodes[1].node.list_channels().len(), 0);
2268 // We test justice_tx build by A on B's revoked HTLC-Success tx
2269 // Create some new channels:
2270 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2272 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2276 // A pending HTLC which will be revoked:
2277 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2278 // Get the will-be-revoked local txn from B
2279 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2280 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2281 assert_eq!(revoked_local_txn[0].input.len(), 1);
2282 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2283 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2284 // Revoke the old state
2285 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2287 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2289 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2290 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2291 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2293 check_spends!(node_txn[0], revoked_local_txn[0]);
2294 node_txn.swap_remove(0);
2296 check_added_monitors!(nodes[0], 1);
2297 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2299 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2300 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2301 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2302 check_added_monitors!(nodes[1], 1);
2303 mine_transaction(&nodes[0], &node_txn[1]);
2304 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2305 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2307 get_announce_close_broadcast_events(&nodes, 0, 1);
2308 assert_eq!(nodes[0].node.list_channels().len(), 0);
2309 assert_eq!(nodes[1].node.list_channels().len(), 0);
2313 fn revoked_output_claim() {
2314 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2315 // transaction is broadcast by its counterparty
2316 let chanmon_cfgs = create_chanmon_cfgs(2);
2317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2319 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2320 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2321 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2322 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2323 assert_eq!(revoked_local_txn.len(), 1);
2324 // Only output is the full channel value back to nodes[0]:
2325 assert_eq!(revoked_local_txn[0].output.len(), 1);
2326 // Send a payment through, updating everyone's latest commitment txn
2327 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2329 // Inform nodes[1] that nodes[0] broadcast a stale tx
2330 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2331 check_added_monitors!(nodes[1], 1);
2332 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2333 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2334 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2336 check_spends!(node_txn[0], revoked_local_txn[0]);
2337 check_spends!(node_txn[1], chan_1.3);
2339 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2340 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2341 get_announce_close_broadcast_events(&nodes, 0, 1);
2342 check_added_monitors!(nodes[0], 1);
2343 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2347 fn claim_htlc_outputs_shared_tx() {
2348 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2349 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2350 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2351 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2352 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2353 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2355 // Create some new channel:
2356 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2358 // Rebalance the network to generate htlc in the two directions
2359 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2360 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2361 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2362 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2364 // Get the will-be-revoked local txn from node[0]
2365 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2366 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2367 assert_eq!(revoked_local_txn[0].input.len(), 1);
2368 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2369 assert_eq!(revoked_local_txn[1].input.len(), 1);
2370 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2371 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2372 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2374 //Revoke the old state
2375 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2378 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2379 check_added_monitors!(nodes[0], 1);
2380 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2381 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2382 check_added_monitors!(nodes[1], 1);
2383 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2384 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2385 expect_payment_failed!(nodes[1], payment_hash_2, true);
2387 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2388 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2390 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2391 check_spends!(node_txn[0], revoked_local_txn[0]);
2393 let mut witness_lens = BTreeSet::new();
2394 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2395 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2396 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2397 assert_eq!(witness_lens.len(), 3);
2398 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2399 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2400 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2402 // Next nodes[1] broadcasts its current local tx state:
2403 assert_eq!(node_txn[1].input.len(), 1);
2404 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2406 get_announce_close_broadcast_events(&nodes, 0, 1);
2407 assert_eq!(nodes[0].node.list_channels().len(), 0);
2408 assert_eq!(nodes[1].node.list_channels().len(), 0);
2412 fn claim_htlc_outputs_single_tx() {
2413 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2414 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2415 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2420 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2422 // Rebalance the network to generate htlc in the two directions
2423 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2424 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2425 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2426 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2427 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2429 // Get the will-be-revoked local txn from node[0]
2430 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2432 //Revoke the old state
2433 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2436 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2437 check_added_monitors!(nodes[0], 1);
2438 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2439 check_added_monitors!(nodes[1], 1);
2440 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2441 let mut events = nodes[0].node.get_and_clear_pending_events();
2442 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2444 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2445 _ => panic!("Unexpected event"),
2448 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2449 expect_payment_failed!(nodes[1], payment_hash_2, true);
2451 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2452 assert_eq!(node_txn.len(), 9);
2453 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2454 // ChannelManager: local commmitment + local HTLC-timeout (2)
2455 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2456 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2458 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2459 assert_eq!(node_txn[0].input.len(), 1);
2460 check_spends!(node_txn[0], chan_1.3);
2461 assert_eq!(node_txn[1].input.len(), 1);
2462 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2463 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2464 check_spends!(node_txn[1], node_txn[0]);
2466 // Justice transactions are indices 1-2-4
2467 assert_eq!(node_txn[2].input.len(), 1);
2468 assert_eq!(node_txn[3].input.len(), 1);
2469 assert_eq!(node_txn[4].input.len(), 1);
2471 check_spends!(node_txn[2], revoked_local_txn[0]);
2472 check_spends!(node_txn[3], revoked_local_txn[0]);
2473 check_spends!(node_txn[4], revoked_local_txn[0]);
2475 let mut witness_lens = BTreeSet::new();
2476 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2477 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2478 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2479 assert_eq!(witness_lens.len(), 3);
2480 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2481 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2482 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2484 get_announce_close_broadcast_events(&nodes, 0, 1);
2485 assert_eq!(nodes[0].node.list_channels().len(), 0);
2486 assert_eq!(nodes[1].node.list_channels().len(), 0);
2490 fn test_htlc_on_chain_success() {
2491 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2492 // the preimage backward accordingly. So here we test that ChannelManager is
2493 // broadcasting the right event to other nodes in payment path.
2494 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2495 // A --------------------> B ----------------------> C (preimage)
2496 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2497 // commitment transaction was broadcast.
2498 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2500 // B should be able to claim via preimage if A then broadcasts its local tx.
2501 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2502 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2503 // PaymentSent event).
2505 let chanmon_cfgs = create_chanmon_cfgs(3);
2506 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2507 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2508 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2510 // Create some initial channels
2511 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2512 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2514 // Ensure all nodes are at the same height
2515 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2516 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2517 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2518 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2520 // Rebalance the network a bit by relaying one payment through all the channels...
2521 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2522 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2524 let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2525 let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2527 // Broadcast legit commitment tx from C on B's chain
2528 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2529 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2530 assert_eq!(commitment_tx.len(), 1);
2531 check_spends!(commitment_tx[0], chan_2.3);
2532 nodes[2].node.claim_funds(our_payment_preimage);
2533 nodes[2].node.claim_funds(our_payment_preimage_2);
2534 check_added_monitors!(nodes[2], 2);
2535 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2536 assert!(updates.update_add_htlcs.is_empty());
2537 assert!(updates.update_fail_htlcs.is_empty());
2538 assert!(updates.update_fail_malformed_htlcs.is_empty());
2539 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2541 mine_transaction(&nodes[2], &commitment_tx[0]);
2542 check_closed_broadcast!(nodes[2], true);
2543 check_added_monitors!(nodes[2], 1);
2544 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2545 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2546 assert_eq!(node_txn.len(), 5);
2547 assert_eq!(node_txn[0], node_txn[3]);
2548 assert_eq!(node_txn[1], node_txn[4]);
2549 assert_eq!(node_txn[2], commitment_tx[0]);
2550 check_spends!(node_txn[0], commitment_tx[0]);
2551 check_spends!(node_txn[1], commitment_tx[0]);
2552 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2553 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2554 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2555 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2556 assert_eq!(node_txn[0].lock_time, 0);
2557 assert_eq!(node_txn[1].lock_time, 0);
2559 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2560 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2561 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2562 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2564 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2565 assert_eq!(added_monitors.len(), 1);
2566 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2567 added_monitors.clear();
2569 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2570 assert_eq!(forwarded_events.len(), 3);
2571 match forwarded_events[0] {
2572 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2573 _ => panic!("Unexpected event"),
2575 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2576 } else { panic!(); }
2577 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2578 } else { panic!(); }
2579 let events = nodes[1].node.get_and_clear_pending_msg_events();
2581 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2582 assert_eq!(added_monitors.len(), 2);
2583 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2584 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2585 added_monitors.clear();
2587 assert_eq!(events.len(), 3);
2589 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2590 _ => panic!("Unexpected event"),
2593 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2594 _ => panic!("Unexpected event"),
2598 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2599 assert!(update_add_htlcs.is_empty());
2600 assert!(update_fail_htlcs.is_empty());
2601 assert_eq!(update_fulfill_htlcs.len(), 1);
2602 assert!(update_fail_malformed_htlcs.is_empty());
2603 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2605 _ => panic!("Unexpected event"),
2607 macro_rules! check_tx_local_broadcast {
2608 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2609 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2610 assert_eq!(node_txn.len(), 3);
2611 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2612 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2613 check_spends!(node_txn[1], $commitment_tx);
2614 check_spends!(node_txn[2], $commitment_tx);
2615 assert_ne!(node_txn[1].lock_time, 0);
2616 assert_ne!(node_txn[2].lock_time, 0);
2618 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2619 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2620 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2621 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2623 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2624 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2625 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2626 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2628 check_spends!(node_txn[0], $chan_tx);
2629 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2633 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2634 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2635 // timeout-claim of the output that nodes[2] just claimed via success.
2636 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2638 // Broadcast legit commitment tx from A on B's chain
2639 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2640 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2641 check_spends!(node_a_commitment_tx[0], chan_1.3);
2642 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2643 check_closed_broadcast!(nodes[1], true);
2644 check_added_monitors!(nodes[1], 1);
2645 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2646 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2647 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2648 let commitment_spend =
2649 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2650 check_spends!(node_txn[1], commitment_tx[0]);
2651 check_spends!(node_txn[2], commitment_tx[0]);
2652 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2655 check_spends!(node_txn[0], commitment_tx[0]);
2656 check_spends!(node_txn[1], commitment_tx[0]);
2657 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2661 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2662 assert_eq!(commitment_spend.input.len(), 2);
2663 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2664 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2665 assert_eq!(commitment_spend.lock_time, 0);
2666 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2667 check_spends!(node_txn[3], chan_1.3);
2668 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2669 check_spends!(node_txn[4], node_txn[3]);
2670 check_spends!(node_txn[5], node_txn[3]);
2671 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2672 // we already checked the same situation with A.
2674 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2675 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2676 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2677 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2678 check_closed_broadcast!(nodes[0], true);
2679 check_added_monitors!(nodes[0], 1);
2680 let events = nodes[0].node.get_and_clear_pending_events();
2681 assert_eq!(events.len(), 3);
2682 let mut first_claimed = false;
2683 for event in events {
2685 Event::PaymentSent { payment_preimage } => {
2686 if payment_preimage == our_payment_preimage {
2687 assert!(!first_claimed);
2688 first_claimed = true;
2690 assert_eq!(payment_preimage, our_payment_preimage_2);
2693 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2694 _ => panic!("Unexpected event"),
2697 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2700 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2701 // Test that in case of a unilateral close onchain, we detect the state of output and
2702 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2703 // broadcasting the right event to other nodes in payment path.
2704 // A ------------------> B ----------------------> C (timeout)
2705 // B's commitment tx C's commitment tx
2707 // B's HTLC timeout tx B's timeout tx
2709 let chanmon_cfgs = create_chanmon_cfgs(3);
2710 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2711 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2712 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2713 *nodes[0].connect_style.borrow_mut() = connect_style;
2714 *nodes[1].connect_style.borrow_mut() = connect_style;
2715 *nodes[2].connect_style.borrow_mut() = connect_style;
2717 // Create some intial channels
2718 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2719 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2721 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2722 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2723 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2725 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2727 // Broadcast legit commitment tx from C on B's chain
2728 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2729 check_spends!(commitment_tx[0], chan_2.3);
2730 nodes[2].node.fail_htlc_backwards(&payment_hash);
2731 check_added_monitors!(nodes[2], 0);
2732 expect_pending_htlcs_forwardable!(nodes[2]);
2733 check_added_monitors!(nodes[2], 1);
2735 let events = nodes[2].node.get_and_clear_pending_msg_events();
2736 assert_eq!(events.len(), 1);
2738 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2739 assert!(update_add_htlcs.is_empty());
2740 assert!(!update_fail_htlcs.is_empty());
2741 assert!(update_fulfill_htlcs.is_empty());
2742 assert!(update_fail_malformed_htlcs.is_empty());
2743 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2745 _ => panic!("Unexpected event"),
2747 mine_transaction(&nodes[2], &commitment_tx[0]);
2748 check_closed_broadcast!(nodes[2], true);
2749 check_added_monitors!(nodes[2], 1);
2750 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2751 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2752 assert_eq!(node_txn.len(), 1);
2753 check_spends!(node_txn[0], chan_2.3);
2754 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2756 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2757 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2758 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2759 mine_transaction(&nodes[1], &commitment_tx[0]);
2760 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2763 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2764 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2765 assert_eq!(node_txn[0], node_txn[3]);
2766 assert_eq!(node_txn[1], node_txn[4]);
2768 check_spends!(node_txn[2], commitment_tx[0]);
2769 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2771 check_spends!(node_txn[0], chan_2.3);
2772 check_spends!(node_txn[1], node_txn[0]);
2773 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2774 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2776 timeout_tx = node_txn[2].clone();
2780 mine_transaction(&nodes[1], &timeout_tx);
2781 check_added_monitors!(nodes[1], 1);
2782 check_closed_broadcast!(nodes[1], true);
2784 // B will rebroadcast a fee-bumped timeout transaction here.
2785 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2786 assert_eq!(node_txn.len(), 1);
2787 check_spends!(node_txn[0], commitment_tx[0]);
2790 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2792 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2793 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2794 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2795 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2796 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2797 if node_txn.len() == 1 {
2798 check_spends!(node_txn[0], chan_2.3);
2800 assert_eq!(node_txn.len(), 0);
2804 expect_pending_htlcs_forwardable!(nodes[1]);
2805 check_added_monitors!(nodes[1], 1);
2806 let events = nodes[1].node.get_and_clear_pending_msg_events();
2807 assert_eq!(events.len(), 1);
2809 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2810 assert!(update_add_htlcs.is_empty());
2811 assert!(!update_fail_htlcs.is_empty());
2812 assert!(update_fulfill_htlcs.is_empty());
2813 assert!(update_fail_malformed_htlcs.is_empty());
2814 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2816 _ => panic!("Unexpected event"),
2819 // Broadcast legit commitment tx from B on A's chain
2820 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2821 check_spends!(commitment_tx[0], chan_1.3);
2823 mine_transaction(&nodes[0], &commitment_tx[0]);
2824 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2826 check_closed_broadcast!(nodes[0], true);
2827 check_added_monitors!(nodes[0], 1);
2828 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2829 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2830 assert_eq!(node_txn.len(), 2);
2831 check_spends!(node_txn[0], chan_1.3);
2832 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2833 check_spends!(node_txn[1], commitment_tx[0]);
2834 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2838 fn test_htlc_on_chain_timeout() {
2839 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2840 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2841 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2845 fn test_simple_commitment_revoked_fail_backward() {
2846 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2847 // and fail backward accordingly.
2849 let chanmon_cfgs = create_chanmon_cfgs(3);
2850 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2851 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2852 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2854 // Create some initial channels
2855 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2856 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2858 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2859 // Get the will-be-revoked local txn from nodes[2]
2860 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2861 // Revoke the old state
2862 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2864 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2866 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2867 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2868 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2869 check_added_monitors!(nodes[1], 1);
2870 check_closed_broadcast!(nodes[1], true);
2872 expect_pending_htlcs_forwardable!(nodes[1]);
2873 check_added_monitors!(nodes[1], 1);
2874 let events = nodes[1].node.get_and_clear_pending_msg_events();
2875 assert_eq!(events.len(), 1);
2877 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
2878 assert!(update_add_htlcs.is_empty());
2879 assert_eq!(update_fail_htlcs.len(), 1);
2880 assert!(update_fulfill_htlcs.is_empty());
2881 assert!(update_fail_malformed_htlcs.is_empty());
2882 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2884 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2885 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2886 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2888 _ => panic!("Unexpected event"),
2892 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2893 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2894 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2895 // commitment transaction anymore.
2896 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2897 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2898 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2899 // technically disallowed and we should probably handle it reasonably.
2900 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2901 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2903 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2904 // commitment_signed (implying it will be in the latest remote commitment transaction).
2905 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2906 // and once they revoke the previous commitment transaction (allowing us to send a new
2907 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2908 let chanmon_cfgs = create_chanmon_cfgs(3);
2909 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2910 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2911 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2913 // Create some initial channels
2914 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2915 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2917 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2918 // Get the will-be-revoked local txn from nodes[2]
2919 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2920 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2921 // Revoke the old state
2922 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2924 let value = if use_dust {
2925 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2926 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2927 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2930 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2931 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2932 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2934 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2935 expect_pending_htlcs_forwardable!(nodes[2]);
2936 check_added_monitors!(nodes[2], 1);
2937 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2938 assert!(updates.update_add_htlcs.is_empty());
2939 assert!(updates.update_fulfill_htlcs.is_empty());
2940 assert!(updates.update_fail_malformed_htlcs.is_empty());
2941 assert_eq!(updates.update_fail_htlcs.len(), 1);
2942 assert!(updates.update_fee.is_none());
2943 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2944 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2945 // Drop the last RAA from 3 -> 2
2947 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2948 expect_pending_htlcs_forwardable!(nodes[2]);
2949 check_added_monitors!(nodes[2], 1);
2950 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2951 assert!(updates.update_add_htlcs.is_empty());
2952 assert!(updates.update_fulfill_htlcs.is_empty());
2953 assert!(updates.update_fail_malformed_htlcs.is_empty());
2954 assert_eq!(updates.update_fail_htlcs.len(), 1);
2955 assert!(updates.update_fee.is_none());
2956 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2957 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2958 check_added_monitors!(nodes[1], 1);
2959 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2960 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2961 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2962 check_added_monitors!(nodes[2], 1);
2964 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2965 expect_pending_htlcs_forwardable!(nodes[2]);
2966 check_added_monitors!(nodes[2], 1);
2967 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2968 assert!(updates.update_add_htlcs.is_empty());
2969 assert!(updates.update_fulfill_htlcs.is_empty());
2970 assert!(updates.update_fail_malformed_htlcs.is_empty());
2971 assert_eq!(updates.update_fail_htlcs.len(), 1);
2972 assert!(updates.update_fee.is_none());
2973 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2974 // At this point first_payment_hash has dropped out of the latest two commitment
2975 // transactions that nodes[1] is tracking...
2976 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2977 check_added_monitors!(nodes[1], 1);
2978 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2979 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2980 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2981 check_added_monitors!(nodes[2], 1);
2983 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2984 // on nodes[2]'s RAA.
2985 let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
2986 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2987 let logger = test_utils::TestLogger::new();
2988 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
2989 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2990 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2991 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2992 check_added_monitors!(nodes[1], 0);
2995 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2996 // One monitor for the new revocation preimage, no second on as we won't generate a new
2997 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2998 check_added_monitors!(nodes[1], 1);
2999 let events = nodes[1].node.get_and_clear_pending_events();
3000 assert_eq!(events.len(), 1);
3002 Event::PendingHTLCsForwardable { .. } => { },
3003 _ => panic!("Unexpected event"),
3005 // Deliberately don't process the pending fail-back so they all fail back at once after
3006 // block connection just like the !deliver_bs_raa case
3009 let mut failed_htlcs = HashSet::new();
3010 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3012 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3013 check_added_monitors!(nodes[1], 1);
3014 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3016 let events = nodes[1].node.get_and_clear_pending_events();
3017 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3019 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3020 _ => panic!("Unexepected event"),
3023 Event::PaymentPathFailed { ref payment_hash, .. } => {
3024 assert_eq!(*payment_hash, fourth_payment_hash);
3026 _ => panic!("Unexpected event"),
3028 if !deliver_bs_raa {
3030 Event::PendingHTLCsForwardable { .. } => { },
3031 _ => panic!("Unexpected event"),
3034 nodes[1].node.process_pending_htlc_forwards();
3035 check_added_monitors!(nodes[1], 1);
3037 let events = nodes[1].node.get_and_clear_pending_msg_events();
3038 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3039 match events[if deliver_bs_raa { 1 } else { 0 }] {
3040 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3041 _ => panic!("Unexpected event"),
3043 match events[if deliver_bs_raa { 2 } else { 1 }] {
3044 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3045 assert_eq!(channel_id, chan_2.2);
3046 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3048 _ => panic!("Unexpected event"),
3052 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3053 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3054 assert_eq!(update_add_htlcs.len(), 1);
3055 assert!(update_fulfill_htlcs.is_empty());
3056 assert!(update_fail_htlcs.is_empty());
3057 assert!(update_fail_malformed_htlcs.is_empty());
3059 _ => panic!("Unexpected event"),
3062 match events[if deliver_bs_raa { 3 } else { 2 }] {
3063 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3064 assert!(update_add_htlcs.is_empty());
3065 assert_eq!(update_fail_htlcs.len(), 3);
3066 assert!(update_fulfill_htlcs.is_empty());
3067 assert!(update_fail_malformed_htlcs.is_empty());
3068 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3070 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3071 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3072 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3074 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3076 let events = nodes[0].node.get_and_clear_pending_events();
3077 assert_eq!(events.len(), 3);
3079 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3080 assert!(failed_htlcs.insert(payment_hash.0));
3081 // If we delivered B's RAA we got an unknown preimage error, not something
3082 // that we should update our routing table for.
3083 if !deliver_bs_raa {
3084 assert!(network_update.is_some());
3087 _ => panic!("Unexpected event"),
3090 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3091 assert!(failed_htlcs.insert(payment_hash.0));
3092 assert!(network_update.is_some());
3094 _ => panic!("Unexpected event"),
3097 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3098 assert!(failed_htlcs.insert(payment_hash.0));
3099 assert!(network_update.is_some());
3101 _ => panic!("Unexpected event"),
3104 _ => panic!("Unexpected event"),
3107 assert!(failed_htlcs.contains(&first_payment_hash.0));
3108 assert!(failed_htlcs.contains(&second_payment_hash.0));
3109 assert!(failed_htlcs.contains(&third_payment_hash.0));
3113 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3114 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3115 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3116 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3117 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3121 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3122 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3123 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3124 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3125 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3129 fn fail_backward_pending_htlc_upon_channel_failure() {
3130 let chanmon_cfgs = create_chanmon_cfgs(2);
3131 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3132 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3133 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3134 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3135 let logger = test_utils::TestLogger::new();
3137 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3139 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3140 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3141 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3142 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3143 check_added_monitors!(nodes[0], 1);
3145 let payment_event = {
3146 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3147 assert_eq!(events.len(), 1);
3148 SendEvent::from_event(events.remove(0))
3150 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3151 assert_eq!(payment_event.msgs.len(), 1);
3154 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3155 let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3157 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3158 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3159 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3160 check_added_monitors!(nodes[0], 0);
3162 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3165 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3167 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3169 let secp_ctx = Secp256k1::new();
3170 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3171 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3172 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3173 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3174 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3175 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3176 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3178 // Send a 0-msat update_add_htlc to fail the channel.
3179 let update_add_htlc = msgs::UpdateAddHTLC {
3185 onion_routing_packet,
3187 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3189 let events = nodes[0].node.get_and_clear_pending_events();
3190 assert_eq!(events.len(), 2);
3191 // Check that Alice fails backward the pending HTLC from the second payment.
3193 Event::PaymentPathFailed { payment_hash, .. } => {
3194 assert_eq!(payment_hash, failed_payment_hash);
3196 _ => panic!("Unexpected event"),
3199 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3200 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3202 _ => panic!("Unexpected event {:?}", events[1]),
3204 check_closed_broadcast!(nodes[0], true);
3205 check_added_monitors!(nodes[0], 1);
3209 fn test_htlc_ignore_latest_remote_commitment() {
3210 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3211 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3212 let chanmon_cfgs = create_chanmon_cfgs(2);
3213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3215 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3216 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3218 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3219 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3220 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3221 check_closed_broadcast!(nodes[0], true);
3222 check_added_monitors!(nodes[0], 1);
3223 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3225 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3226 assert_eq!(node_txn.len(), 3);
3227 assert_eq!(node_txn[0], node_txn[1]);
3229 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3230 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3231 check_closed_broadcast!(nodes[1], true);
3232 check_added_monitors!(nodes[1], 1);
3233 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3235 // Duplicate the connect_block call since this may happen due to other listeners
3236 // registering new transactions
3237 header.prev_blockhash = header.block_hash();
3238 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3242 fn test_force_close_fail_back() {
3243 // Check which HTLCs are failed-backwards on channel force-closure
3244 let chanmon_cfgs = create_chanmon_cfgs(3);
3245 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3246 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3247 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3248 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3249 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3250 let logger = test_utils::TestLogger::new();
3252 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3254 let mut payment_event = {
3255 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3256 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3257 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3258 check_added_monitors!(nodes[0], 1);
3260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3261 assert_eq!(events.len(), 1);
3262 SendEvent::from_event(events.remove(0))
3265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3266 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3268 expect_pending_htlcs_forwardable!(nodes[1]);
3270 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3271 assert_eq!(events_2.len(), 1);
3272 payment_event = SendEvent::from_event(events_2.remove(0));
3273 assert_eq!(payment_event.msgs.len(), 1);
3275 check_added_monitors!(nodes[1], 1);
3276 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3277 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3278 check_added_monitors!(nodes[2], 1);
3279 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3281 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3282 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3283 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3285 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3286 check_closed_broadcast!(nodes[2], true);
3287 check_added_monitors!(nodes[2], 1);
3288 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3290 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3291 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3292 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3293 // back to nodes[1] upon timeout otherwise.
3294 assert_eq!(node_txn.len(), 1);
3298 mine_transaction(&nodes[1], &tx);
3300 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3301 check_closed_broadcast!(nodes[1], true);
3302 check_added_monitors!(nodes[1], 1);
3303 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3305 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3307 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3308 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3309 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3311 mine_transaction(&nodes[2], &tx);
3312 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3313 assert_eq!(node_txn.len(), 1);
3314 assert_eq!(node_txn[0].input.len(), 1);
3315 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3316 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3317 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3319 check_spends!(node_txn[0], tx);
3323 fn test_dup_events_on_peer_disconnect() {
3324 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3325 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3326 // as we used to generate the event immediately upon receipt of the payment preimage in the
3327 // update_fulfill_htlc message.
3329 let chanmon_cfgs = create_chanmon_cfgs(2);
3330 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3331 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3332 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3333 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3335 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3337 assert!(nodes[1].node.claim_funds(payment_preimage));
3338 check_added_monitors!(nodes[1], 1);
3339 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3340 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3341 expect_payment_sent!(nodes[0], payment_preimage);
3343 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3344 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3346 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3347 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3351 fn test_simple_peer_disconnect() {
3352 // Test that we can reconnect when there are no lost messages
3353 let chanmon_cfgs = create_chanmon_cfgs(3);
3354 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3355 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3356 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3357 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3358 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3360 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3361 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3362 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3364 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3365 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3366 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3367 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3369 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3370 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3371 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3373 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3374 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3375 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3376 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3378 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3379 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3381 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3382 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3384 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3386 let events = nodes[0].node.get_and_clear_pending_events();
3387 assert_eq!(events.len(), 2);
3389 Event::PaymentSent { payment_preimage } => {
3390 assert_eq!(payment_preimage, payment_preimage_3);
3392 _ => panic!("Unexpected event"),
3395 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3396 assert_eq!(payment_hash, payment_hash_5);
3397 assert!(rejected_by_dest);
3399 _ => panic!("Unexpected event"),
3403 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3404 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3407 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3408 // Test that we can reconnect when in-flight HTLC updates get dropped
3409 let chanmon_cfgs = create_chanmon_cfgs(2);
3410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3412 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3414 let mut as_funding_locked = None;
3415 if messages_delivered == 0 {
3416 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3417 as_funding_locked = Some(funding_locked);
3418 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3419 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3420 // it before the channel_reestablish message.
3422 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3425 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3427 let logger = test_utils::TestLogger::new();
3428 let payment_event = {
3429 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3430 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3431 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3432 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3433 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3434 check_added_monitors!(nodes[0], 1);
3436 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3437 assert_eq!(events.len(), 1);
3438 SendEvent::from_event(events.remove(0))
3440 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3442 if messages_delivered < 2 {
3443 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3445 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3446 if messages_delivered >= 3 {
3447 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3448 check_added_monitors!(nodes[1], 1);
3449 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3451 if messages_delivered >= 4 {
3452 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3453 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3454 check_added_monitors!(nodes[0], 1);
3456 if messages_delivered >= 5 {
3457 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3458 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3459 // No commitment_signed so get_event_msg's assert(len == 1) passes
3460 check_added_monitors!(nodes[0], 1);
3462 if messages_delivered >= 6 {
3463 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3464 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3465 check_added_monitors!(nodes[1], 1);
3472 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3473 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3474 if messages_delivered < 3 {
3475 if simulate_broken_lnd {
3476 // lnd has a long-standing bug where they send a funding_locked prior to a
3477 // channel_reestablish if you reconnect prior to funding_locked time.
3479 // Here we simulate that behavior, delivering a funding_locked immediately on
3480 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3481 // in `reconnect_nodes` but we currently don't fail based on that.
3483 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3484 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3486 // Even if the funding_locked messages get exchanged, as long as nothing further was
3487 // received on either side, both sides will need to resend them.
3488 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3489 } else if messages_delivered == 3 {
3490 // nodes[0] still wants its RAA + commitment_signed
3491 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3492 } else if messages_delivered == 4 {
3493 // nodes[0] still wants its commitment_signed
3494 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3495 } else if messages_delivered == 5 {
3496 // nodes[1] still wants its final RAA
3497 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3498 } else if messages_delivered == 6 {
3499 // Everything was delivered...
3500 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3503 let events_1 = nodes[1].node.get_and_clear_pending_events();
3504 assert_eq!(events_1.len(), 1);
3506 Event::PendingHTLCsForwardable { .. } => { },
3507 _ => panic!("Unexpected event"),
3510 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3511 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3512 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3514 nodes[1].node.process_pending_htlc_forwards();
3516 let events_2 = nodes[1].node.get_and_clear_pending_events();
3517 assert_eq!(events_2.len(), 1);
3519 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3520 assert_eq!(payment_hash_1, *payment_hash);
3521 assert_eq!(amt, 1000000);
3523 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3524 assert!(payment_preimage.is_none());
3525 assert_eq!(payment_secret_1, *payment_secret);
3527 _ => panic!("expected PaymentPurpose::InvoicePayment")
3530 _ => panic!("Unexpected event"),
3533 nodes[1].node.claim_funds(payment_preimage_1);
3534 check_added_monitors!(nodes[1], 1);
3536 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3537 assert_eq!(events_3.len(), 1);
3538 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3539 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3540 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3541 assert!(updates.update_add_htlcs.is_empty());
3542 assert!(updates.update_fail_htlcs.is_empty());
3543 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3544 assert!(updates.update_fail_malformed_htlcs.is_empty());
3545 assert!(updates.update_fee.is_none());
3546 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3548 _ => panic!("Unexpected event"),
3551 if messages_delivered >= 1 {
3552 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3554 let events_4 = nodes[0].node.get_and_clear_pending_events();
3555 assert_eq!(events_4.len(), 1);
3557 Event::PaymentSent { ref payment_preimage } => {
3558 assert_eq!(payment_preimage_1, *payment_preimage);
3560 _ => panic!("Unexpected event"),
3563 if messages_delivered >= 2 {
3564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3565 check_added_monitors!(nodes[0], 1);
3566 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3568 if messages_delivered >= 3 {
3569 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3570 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3571 check_added_monitors!(nodes[1], 1);
3573 if messages_delivered >= 4 {
3574 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3575 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3576 // No commitment_signed so get_event_msg's assert(len == 1) passes
3577 check_added_monitors!(nodes[1], 1);
3579 if messages_delivered >= 5 {
3580 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3581 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3582 check_added_monitors!(nodes[0], 1);
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591 if messages_delivered < 2 {
3592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593 if messages_delivered < 1 {
3594 let events_4 = nodes[0].node.get_and_clear_pending_events();
3595 assert_eq!(events_4.len(), 1);
3597 Event::PaymentSent { ref payment_preimage } => {
3598 assert_eq!(payment_preimage_1, *payment_preimage);
3600 _ => panic!("Unexpected event"),
3603 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3605 } else if messages_delivered == 2 {
3606 // nodes[0] still wants its RAA + commitment_signed
3607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3608 } else if messages_delivered == 3 {
3609 // nodes[0] still wants its commitment_signed
3610 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3611 } else if messages_delivered == 4 {
3612 // nodes[1] still wants its final RAA
3613 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3614 } else if messages_delivered == 5 {
3615 // Everything was delivered...
3616 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3619 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3620 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3621 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3623 // Channel should still work fine...
3624 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3625 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph,
3626 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3627 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3628 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3629 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3633 fn test_drop_messages_peer_disconnect_a() {
3634 do_test_drop_messages_peer_disconnect(0, true);
3635 do_test_drop_messages_peer_disconnect(0, false);
3636 do_test_drop_messages_peer_disconnect(1, false);
3637 do_test_drop_messages_peer_disconnect(2, false);
3641 fn test_drop_messages_peer_disconnect_b() {
3642 do_test_drop_messages_peer_disconnect(3, false);
3643 do_test_drop_messages_peer_disconnect(4, false);
3644 do_test_drop_messages_peer_disconnect(5, false);
3645 do_test_drop_messages_peer_disconnect(6, false);
3649 fn test_funding_peer_disconnect() {
3650 // Test that we can lock in our funding tx while disconnected
3651 let chanmon_cfgs = create_chanmon_cfgs(2);
3652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3654 let persister: test_utils::TestPersister;
3655 let new_chain_monitor: test_utils::TestChainMonitor;
3656 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3657 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3658 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3660 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3661 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3663 confirm_transaction(&nodes[0], &tx);
3664 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3665 assert_eq!(events_1.len(), 1);
3667 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3668 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3670 _ => panic!("Unexpected event"),
3673 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3675 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3676 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3678 confirm_transaction(&nodes[1], &tx);
3679 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3680 assert_eq!(events_2.len(), 2);
3681 let funding_locked = match events_2[0] {
3682 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3683 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3686 _ => panic!("Unexpected event"),
3688 let bs_announcement_sigs = match events_2[1] {
3689 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3690 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3693 _ => panic!("Unexpected event"),
3696 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3698 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3699 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3700 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3701 assert_eq!(events_3.len(), 2);
3702 let as_announcement_sigs = match events_3[0] {
3703 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3704 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3707 _ => panic!("Unexpected event"),
3709 let (as_announcement, as_update) = match events_3[1] {
3710 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3711 (msg.clone(), update_msg.clone())
3713 _ => panic!("Unexpected event"),
3716 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3717 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3718 assert_eq!(events_4.len(), 1);
3719 let (_, bs_update) = match events_4[0] {
3720 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3721 (msg.clone(), update_msg.clone())
3723 _ => panic!("Unexpected event"),
3726 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3727 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3728 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3730 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3731 let logger = test_utils::TestLogger::new();
3732 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3733 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3734 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3736 // Check that after deserialization and reconnection we can still generate an identical
3737 // channel_announcement from the cached signatures.
3738 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3740 let nodes_0_serialized = nodes[0].node.encode();
3741 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3742 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3744 persister = test_utils::TestPersister::new();
3745 let keys_manager = &chanmon_cfgs[0].keys_manager;
3746 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
3747 nodes[0].chain_monitor = &new_chain_monitor;
3748 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3749 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3750 &mut chan_0_monitor_read, keys_manager).unwrap();
3751 assert!(chan_0_monitor_read.is_empty());
3753 let mut nodes_0_read = &nodes_0_serialized[..];
3754 let (_, nodes_0_deserialized_tmp) = {
3755 let mut channel_monitors = HashMap::new();
3756 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3757 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3758 default_config: UserConfig::default(),
3760 fee_estimator: node_cfgs[0].fee_estimator,
3761 chain_monitor: nodes[0].chain_monitor,
3762 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3763 logger: nodes[0].logger,
3767 nodes_0_deserialized = nodes_0_deserialized_tmp;
3768 assert!(nodes_0_read.is_empty());
3770 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3771 nodes[0].node = &nodes_0_deserialized;
3772 check_added_monitors!(nodes[0], 1);
3774 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3776 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3777 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3778 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3779 let mut found_announcement = false;
3780 for event in msgs.iter() {
3782 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3783 if *msg == as_announcement { found_announcement = true; }
3785 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3786 _ => panic!("Unexpected event"),
3789 assert!(found_announcement);
3793 fn test_drop_messages_peer_disconnect_dual_htlc() {
3794 // Test that we can handle reconnecting when both sides of a channel have pending
3795 // commitment_updates when we disconnect.
3796 let chanmon_cfgs = create_chanmon_cfgs(2);
3797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3800 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3801 let logger = test_utils::TestLogger::new();
3803 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3805 // Now try to send a second payment which will fail to send
3806 let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
3807 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3808 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3809 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3810 check_added_monitors!(nodes[0], 1);
3812 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3813 assert_eq!(events_1.len(), 1);
3815 MessageSendEvent::UpdateHTLCs { .. } => {},
3816 _ => panic!("Unexpected event"),
3819 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3820 check_added_monitors!(nodes[1], 1);
3822 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3823 assert_eq!(events_2.len(), 1);
3825 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
3826 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3827 assert!(update_add_htlcs.is_empty());
3828 assert_eq!(update_fulfill_htlcs.len(), 1);
3829 assert!(update_fail_htlcs.is_empty());
3830 assert!(update_fail_malformed_htlcs.is_empty());
3831 assert!(update_fee.is_none());
3833 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3834 let events_3 = nodes[0].node.get_and_clear_pending_events();
3835 assert_eq!(events_3.len(), 1);
3837 Event::PaymentSent { ref payment_preimage } => {
3838 assert_eq!(*payment_preimage, payment_preimage_1);
3840 _ => panic!("Unexpected event"),
3843 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3844 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3845 // No commitment_signed so get_event_msg's assert(len == 1) passes
3846 check_added_monitors!(nodes[0], 1);
3848 _ => panic!("Unexpected event"),
3851 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3852 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3854 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3855 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3856 assert_eq!(reestablish_1.len(), 1);
3857 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3858 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3859 assert_eq!(reestablish_2.len(), 1);
3861 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3862 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3863 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3864 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3866 assert!(as_resp.0.is_none());
3867 assert!(bs_resp.0.is_none());
3869 assert!(bs_resp.1.is_none());
3870 assert!(bs_resp.2.is_none());
3872 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3874 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3875 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3876 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3877 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3878 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3879 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3880 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3881 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3882 // No commitment_signed so get_event_msg's assert(len == 1) passes
3883 check_added_monitors!(nodes[1], 1);
3885 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3886 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3887 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3888 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3889 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3890 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3891 assert!(bs_second_commitment_signed.update_fee.is_none());
3892 check_added_monitors!(nodes[1], 1);
3894 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3895 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3896 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3897 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3898 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3899 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3900 assert!(as_commitment_signed.update_fee.is_none());
3901 check_added_monitors!(nodes[0], 1);
3903 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3904 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3905 // No commitment_signed so get_event_msg's assert(len == 1) passes
3906 check_added_monitors!(nodes[0], 1);
3908 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3909 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3910 // No commitment_signed so get_event_msg's assert(len == 1) passes
3911 check_added_monitors!(nodes[1], 1);
3913 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3914 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3915 check_added_monitors!(nodes[1], 1);
3917 expect_pending_htlcs_forwardable!(nodes[1]);
3919 let events_5 = nodes[1].node.get_and_clear_pending_events();
3920 assert_eq!(events_5.len(), 1);
3922 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3923 assert_eq!(payment_hash_2, *payment_hash);
3925 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3926 assert!(payment_preimage.is_none());
3927 assert_eq!(payment_secret_2, *payment_secret);
3929 _ => panic!("expected PaymentPurpose::InvoicePayment")
3932 _ => panic!("Unexpected event"),
3935 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3936 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3937 check_added_monitors!(nodes[0], 1);
3939 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3942 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3943 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3944 // to avoid our counterparty failing the channel.
3945 let chanmon_cfgs = create_chanmon_cfgs(2);
3946 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3947 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3948 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3950 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3951 let logger = test_utils::TestLogger::new();
3953 let our_payment_hash = if send_partial_mpp {
3954 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3955 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3956 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
3957 // Use the utility function send_payment_along_path to send the payment with MPP data which
3958 // indicates there are more HTLCs coming.
3959 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
3960 let mpp_id = MppId([42; 32]);
3961 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, mpp_id, &None).unwrap();
3962 check_added_monitors!(nodes[0], 1);
3963 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3964 assert_eq!(events.len(), 1);
3965 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3966 // hop should *not* yet generate any PaymentReceived event(s).
3967 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3970 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3973 let mut block = Block {
3974 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3977 connect_block(&nodes[0], &block);
3978 connect_block(&nodes[1], &block);
3979 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3980 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3981 block.header.prev_blockhash = block.block_hash();
3982 connect_block(&nodes[0], &block);
3983 connect_block(&nodes[1], &block);
3986 expect_pending_htlcs_forwardable!(nodes[1]);
3988 check_added_monitors!(nodes[1], 1);
3989 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3990 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3991 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3992 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3993 assert!(htlc_timeout_updates.update_fee.is_none());
3995 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3996 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3997 // 100_000 msat as u64, followed by the height at which we failed back above
3998 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3999 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4000 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4004 fn test_htlc_timeout() {
4005 do_test_htlc_timeout(true);
4006 do_test_htlc_timeout(false);
4009 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4010 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4011 let chanmon_cfgs = create_chanmon_cfgs(3);
4012 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4013 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4014 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4015 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4016 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4018 // Make sure all nodes are at the same starting height
4019 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4020 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4021 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4023 let logger = test_utils::TestLogger::new();
4025 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4026 let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4028 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4029 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4030 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4032 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4033 check_added_monitors!(nodes[1], 1);
4035 // Now attempt to route a second payment, which should be placed in the holding cell
4036 let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4038 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4039 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4040 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
4041 check_added_monitors!(nodes[0], 1);
4042 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4044 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4045 expect_pending_htlcs_forwardable!(nodes[1]);
4046 check_added_monitors!(nodes[1], 0);
4048 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4049 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4050 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4051 check_added_monitors!(nodes[1], 0);
4054 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4055 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4056 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4057 connect_blocks(&nodes[1], 1);
4060 expect_pending_htlcs_forwardable!(nodes[1]);
4061 check_added_monitors!(nodes[1], 1);
4062 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4063 assert_eq!(fail_commit.len(), 1);
4064 match fail_commit[0] {
4065 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4066 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4067 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4069 _ => unreachable!(),
4071 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4073 expect_payment_failed!(nodes[1], second_payment_hash, true);
4078 fn test_holding_cell_htlc_add_timeouts() {
4079 do_test_holding_cell_htlc_add_timeouts(false);
4080 do_test_holding_cell_htlc_add_timeouts(true);
4084 fn test_no_txn_manager_serialize_deserialize() {
4085 let chanmon_cfgs = create_chanmon_cfgs(2);
4086 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4087 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4088 let logger: test_utils::TestLogger;
4089 let fee_estimator: test_utils::TestFeeEstimator;
4090 let persister: test_utils::TestPersister;
4091 let new_chain_monitor: test_utils::TestChainMonitor;
4092 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4093 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4095 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4097 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4099 let nodes_0_serialized = nodes[0].node.encode();
4100 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4101 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4103 logger = test_utils::TestLogger::new();
4104 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4105 persister = test_utils::TestPersister::new();
4106 let keys_manager = &chanmon_cfgs[0].keys_manager;
4107 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4108 nodes[0].chain_monitor = &new_chain_monitor;
4109 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4110 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4111 &mut chan_0_monitor_read, keys_manager).unwrap();
4112 assert!(chan_0_monitor_read.is_empty());
4114 let mut nodes_0_read = &nodes_0_serialized[..];
4115 let config = UserConfig::default();
4116 let (_, nodes_0_deserialized_tmp) = {
4117 let mut channel_monitors = HashMap::new();
4118 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4119 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4120 default_config: config,
4122 fee_estimator: &fee_estimator,
4123 chain_monitor: nodes[0].chain_monitor,
4124 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4129 nodes_0_deserialized = nodes_0_deserialized_tmp;
4130 assert!(nodes_0_read.is_empty());
4132 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4133 nodes[0].node = &nodes_0_deserialized;
4134 assert_eq!(nodes[0].node.list_channels().len(), 1);
4135 check_added_monitors!(nodes[0], 1);
4137 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4138 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4139 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4140 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4142 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4143 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4144 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4145 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4147 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4148 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4149 for node in nodes.iter() {
4150 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4151 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4152 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4155 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4160 let chanmon_cfgs = create_chanmon_cfgs(4);
4161 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4162 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4163 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4165 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4166 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4167 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4168 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
4169 let logger = test_utils::TestLogger::new();
4171 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
4172 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4173 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
4174 let path = route.paths[0].clone();
4175 route.paths.push(path);
4176 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
4177 route.paths[0][0].short_channel_id = chan_1_id;
4178 route.paths[0][1].short_channel_id = chan_3_id;
4179 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
4180 route.paths[1][0].short_channel_id = chan_2_id;
4181 route.paths[1][1].short_channel_id = chan_4_id;
4182 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
4183 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
4187 fn test_dup_htlc_onchain_fails_on_reload() {
4188 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4189 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4190 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4191 // the ChannelMonitor tells it to.
4193 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4194 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4195 // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4196 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4197 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4198 // and de-duplicates ChannelMonitor events.
4200 // This tests that explicit tracking behavior.
4201 let chanmon_cfgs = create_chanmon_cfgs(2);
4202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4204 let persister: test_utils::TestPersister;
4205 let new_chain_monitor: test_utils::TestChainMonitor;
4206 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4207 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4209 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4211 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4213 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4214 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4215 check_closed_broadcast!(nodes[0], true);
4216 check_added_monitors!(nodes[0], 1);
4217 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4219 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4220 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4222 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4223 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4224 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4225 assert_eq!(node_txn.len(), 3);
4226 assert_eq!(node_txn[0], node_txn[1]);
4228 assert!(nodes[1].node.claim_funds(payment_preimage));
4229 check_added_monitors!(nodes[1], 1);
4231 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4232 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4233 check_closed_broadcast!(nodes[1], true);
4234 check_added_monitors!(nodes[1], 1);
4235 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4236 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4238 header.prev_blockhash = nodes[0].best_block_hash();
4239 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4241 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4242 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4243 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4244 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4245 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4247 header.prev_blockhash = nodes[0].best_block_hash();
4248 let claim_block = Block { header, txdata: claim_txn};
4249 connect_block(&nodes[0], &claim_block);
4250 expect_payment_sent!(nodes[0], payment_preimage);
4252 // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4253 // connected a highly-relevant block, it likely gets serialized out now.
4254 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4255 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4257 // Now reload nodes[0]...
4258 persister = test_utils::TestPersister::new();
4259 let keys_manager = &chanmon_cfgs[0].keys_manager;
4260 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), nodes[0].logger, node_cfgs[0].fee_estimator, &persister, keys_manager);
4261 nodes[0].chain_monitor = &new_chain_monitor;
4262 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4263 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4264 &mut chan_0_monitor_read, keys_manager).unwrap();
4265 assert!(chan_0_monitor_read.is_empty());
4267 let (_, nodes_0_deserialized_tmp) = {
4268 let mut channel_monitors = HashMap::new();
4269 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4270 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4271 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4272 default_config: Default::default(),
4274 fee_estimator: node_cfgs[0].fee_estimator,
4275 chain_monitor: nodes[0].chain_monitor,
4276 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4277 logger: nodes[0].logger,
4281 nodes_0_deserialized = nodes_0_deserialized_tmp;
4283 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4284 check_added_monitors!(nodes[0], 1);
4285 nodes[0].node = &nodes_0_deserialized;
4287 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4288 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4289 // payment events should kick in, leaving us with no pending events here.
4290 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4291 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4292 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4296 fn test_manager_serialize_deserialize_events() {
4297 // This test makes sure the events field in ChannelManager survives de/serialization
4298 let chanmon_cfgs = create_chanmon_cfgs(2);
4299 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4300 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4301 let fee_estimator: test_utils::TestFeeEstimator;
4302 let persister: test_utils::TestPersister;
4303 let logger: test_utils::TestLogger;
4304 let new_chain_monitor: test_utils::TestChainMonitor;
4305 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4306 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4308 // Start creating a channel, but stop right before broadcasting the funding transaction
4309 let channel_value = 100000;
4310 let push_msat = 10001;
4311 let a_flags = InitFeatures::known();
4312 let b_flags = InitFeatures::known();
4313 let node_a = nodes.remove(0);
4314 let node_b = nodes.remove(0);
4315 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4316 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
4317 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
4319 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4321 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4322 check_added_monitors!(node_a, 0);
4324 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
4326 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4327 assert_eq!(added_monitors.len(), 1);
4328 assert_eq!(added_monitors[0].0, funding_output);
4329 added_monitors.clear();
4332 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4334 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4335 assert_eq!(added_monitors.len(), 1);
4336 assert_eq!(added_monitors[0].0, funding_output);
4337 added_monitors.clear();
4339 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4344 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4345 let nodes_0_serialized = nodes[0].node.encode();
4346 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4347 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4349 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4350 logger = test_utils::TestLogger::new();
4351 persister = test_utils::TestPersister::new();
4352 let keys_manager = &chanmon_cfgs[0].keys_manager;
4353 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4354 nodes[0].chain_monitor = &new_chain_monitor;
4355 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4356 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4357 &mut chan_0_monitor_read, keys_manager).unwrap();
4358 assert!(chan_0_monitor_read.is_empty());
4360 let mut nodes_0_read = &nodes_0_serialized[..];
4361 let config = UserConfig::default();
4362 let (_, nodes_0_deserialized_tmp) = {
4363 let mut channel_monitors = HashMap::new();
4364 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4365 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4366 default_config: config,
4368 fee_estimator: &fee_estimator,
4369 chain_monitor: nodes[0].chain_monitor,
4370 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4375 nodes_0_deserialized = nodes_0_deserialized_tmp;
4376 assert!(nodes_0_read.is_empty());
4378 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4380 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4381 nodes[0].node = &nodes_0_deserialized;
4383 // After deserializing, make sure the funding_transaction is still held by the channel manager
4384 let events_4 = nodes[0].node.get_and_clear_pending_events();
4385 assert_eq!(events_4.len(), 0);
4386 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4387 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4389 // Make sure the channel is functioning as though the de/serialization never happened
4390 assert_eq!(nodes[0].node.list_channels().len(), 1);
4391 check_added_monitors!(nodes[0], 1);
4393 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4394 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4395 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4396 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4398 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4399 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4400 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4401 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4403 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4404 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4405 for node in nodes.iter() {
4406 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4407 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4408 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4411 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4415 fn test_simple_manager_serialize_deserialize() {
4416 let chanmon_cfgs = create_chanmon_cfgs(2);
4417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4419 let logger: test_utils::TestLogger;
4420 let fee_estimator: test_utils::TestFeeEstimator;
4421 let persister: test_utils::TestPersister;
4422 let new_chain_monitor: test_utils::TestChainMonitor;
4423 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4424 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4425 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4427 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4428 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4430 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4432 let nodes_0_serialized = nodes[0].node.encode();
4433 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4434 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4436 logger = test_utils::TestLogger::new();
4437 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4438 persister = test_utils::TestPersister::new();
4439 let keys_manager = &chanmon_cfgs[0].keys_manager;
4440 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4441 nodes[0].chain_monitor = &new_chain_monitor;
4442 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4443 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4444 &mut chan_0_monitor_read, keys_manager).unwrap();
4445 assert!(chan_0_monitor_read.is_empty());
4447 let mut nodes_0_read = &nodes_0_serialized[..];
4448 let (_, nodes_0_deserialized_tmp) = {
4449 let mut channel_monitors = HashMap::new();
4450 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4451 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4452 default_config: UserConfig::default(),
4454 fee_estimator: &fee_estimator,
4455 chain_monitor: nodes[0].chain_monitor,
4456 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4461 nodes_0_deserialized = nodes_0_deserialized_tmp;
4462 assert!(nodes_0_read.is_empty());
4464 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4465 nodes[0].node = &nodes_0_deserialized;
4466 check_added_monitors!(nodes[0], 1);
4468 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4470 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4471 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4475 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4476 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4477 let chanmon_cfgs = create_chanmon_cfgs(4);
4478 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4479 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4480 let logger: test_utils::TestLogger;
4481 let fee_estimator: test_utils::TestFeeEstimator;
4482 let persister: test_utils::TestPersister;
4483 let new_chain_monitor: test_utils::TestChainMonitor;
4484 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4485 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4486 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4487 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4488 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4490 let mut node_0_stale_monitors_serialized = Vec::new();
4491 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4492 let mut writer = test_utils::TestVecWriter(Vec::new());
4493 monitor.1.write(&mut writer).unwrap();
4494 node_0_stale_monitors_serialized.push(writer.0);
4497 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4499 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4500 let nodes_0_serialized = nodes[0].node.encode();
4502 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4503 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4504 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4505 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4507 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4509 let mut node_0_monitors_serialized = Vec::new();
4510 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4511 let mut writer = test_utils::TestVecWriter(Vec::new());
4512 monitor.1.write(&mut writer).unwrap();
4513 node_0_monitors_serialized.push(writer.0);
4516 logger = test_utils::TestLogger::new();
4517 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4518 persister = test_utils::TestPersister::new();
4519 let keys_manager = &chanmon_cfgs[0].keys_manager;
4520 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4521 nodes[0].chain_monitor = &new_chain_monitor;
4524 let mut node_0_stale_monitors = Vec::new();
4525 for serialized in node_0_stale_monitors_serialized.iter() {
4526 let mut read = &serialized[..];
4527 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4528 assert!(read.is_empty());
4529 node_0_stale_monitors.push(monitor);
4532 let mut node_0_monitors = Vec::new();
4533 for serialized in node_0_monitors_serialized.iter() {
4534 let mut read = &serialized[..];
4535 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4536 assert!(read.is_empty());
4537 node_0_monitors.push(monitor);
4540 let mut nodes_0_read = &nodes_0_serialized[..];
4541 if let Err(msgs::DecodeError::InvalidValue) =
4542 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4543 default_config: UserConfig::default(),
4545 fee_estimator: &fee_estimator,
4546 chain_monitor: nodes[0].chain_monitor,
4547 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4549 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4551 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4554 let mut nodes_0_read = &nodes_0_serialized[..];
4555 let (_, nodes_0_deserialized_tmp) =
4556 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4557 default_config: UserConfig::default(),
4559 fee_estimator: &fee_estimator,
4560 chain_monitor: nodes[0].chain_monitor,
4561 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4563 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4565 nodes_0_deserialized = nodes_0_deserialized_tmp;
4566 assert!(nodes_0_read.is_empty());
4568 { // Channel close should result in a commitment tx
4569 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4570 assert_eq!(txn.len(), 1);
4571 check_spends!(txn[0], funding_tx);
4572 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4575 for monitor in node_0_monitors.drain(..) {
4576 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4577 check_added_monitors!(nodes[0], 1);
4579 nodes[0].node = &nodes_0_deserialized;
4580 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4582 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4583 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4584 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4585 //... and we can even still claim the payment!
4586 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4588 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4589 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4590 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4591 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4592 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4593 assert_eq!(msg_events.len(), 1);
4594 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4596 &ErrorAction::SendErrorMessage { ref msg } => {
4597 assert_eq!(msg.channel_id, channel_id);
4599 _ => panic!("Unexpected event!"),
4604 macro_rules! check_spendable_outputs {
4605 ($node: expr, $keysinterface: expr) => {
4607 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4608 let mut txn = Vec::new();
4609 let mut all_outputs = Vec::new();
4610 let secp_ctx = Secp256k1::new();
4611 for event in events.drain(..) {
4613 Event::SpendableOutputs { mut outputs } => {
4614 for outp in outputs.drain(..) {
4615 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4616 all_outputs.push(outp);
4619 _ => panic!("Unexpected event"),
4622 if all_outputs.len() > 1 {
4623 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx) {
4633 fn test_claim_sizeable_push_msat() {
4634 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4635 let chanmon_cfgs = create_chanmon_cfgs(2);
4636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4638 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4640 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4641 nodes[1].node.force_close_channel(&chan.2).unwrap();
4642 check_closed_broadcast!(nodes[1], true);
4643 check_added_monitors!(nodes[1], 1);
4644 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4645 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4646 assert_eq!(node_txn.len(), 1);
4647 check_spends!(node_txn[0], chan.3);
4648 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4650 mine_transaction(&nodes[1], &node_txn[0]);
4651 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4653 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4654 assert_eq!(spend_txn.len(), 1);
4655 assert_eq!(spend_txn[0].input.len(), 1);
4656 check_spends!(spend_txn[0], node_txn[0]);
4657 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4661 fn test_claim_on_remote_sizeable_push_msat() {
4662 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4663 // to_remote output is encumbered by a P2WPKH
4664 let chanmon_cfgs = create_chanmon_cfgs(2);
4665 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4666 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4667 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4669 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4670 nodes[0].node.force_close_channel(&chan.2).unwrap();
4671 check_closed_broadcast!(nodes[0], true);
4672 check_added_monitors!(nodes[0], 1);
4673 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4675 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4676 assert_eq!(node_txn.len(), 1);
4677 check_spends!(node_txn[0], chan.3);
4678 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4680 mine_transaction(&nodes[1], &node_txn[0]);
4681 check_closed_broadcast!(nodes[1], true);
4682 check_added_monitors!(nodes[1], 1);
4683 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4684 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4686 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4687 assert_eq!(spend_txn.len(), 1);
4688 check_spends!(spend_txn[0], node_txn[0]);
4692 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4693 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4694 // to_remote output is encumbered by a P2WPKH
4696 let chanmon_cfgs = create_chanmon_cfgs(2);
4697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4699 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4701 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4702 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4703 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4704 assert_eq!(revoked_local_txn[0].input.len(), 1);
4705 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4707 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4708 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4709 check_closed_broadcast!(nodes[1], true);
4710 check_added_monitors!(nodes[1], 1);
4711 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4713 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4714 mine_transaction(&nodes[1], &node_txn[0]);
4715 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4717 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4718 assert_eq!(spend_txn.len(), 3);
4719 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4720 check_spends!(spend_txn[1], node_txn[0]);
4721 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4725 fn test_static_spendable_outputs_preimage_tx() {
4726 let chanmon_cfgs = create_chanmon_cfgs(2);
4727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4731 // Create some initial channels
4732 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4734 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4736 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4737 assert_eq!(commitment_tx[0].input.len(), 1);
4738 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4740 // Settle A's commitment tx on B's chain
4741 assert!(nodes[1].node.claim_funds(payment_preimage));
4742 check_added_monitors!(nodes[1], 1);
4743 mine_transaction(&nodes[1], &commitment_tx[0]);
4744 check_added_monitors!(nodes[1], 1);
4745 let events = nodes[1].node.get_and_clear_pending_msg_events();
4747 MessageSendEvent::UpdateHTLCs { .. } => {},
4748 _ => panic!("Unexpected event"),
4751 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4752 _ => panic!("Unexepected event"),
4755 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4756 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4757 assert_eq!(node_txn.len(), 3);
4758 check_spends!(node_txn[0], commitment_tx[0]);
4759 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4760 check_spends!(node_txn[1], chan_1.3);
4761 check_spends!(node_txn[2], node_txn[1]);
4763 mine_transaction(&nodes[1], &node_txn[0]);
4764 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4765 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4767 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4768 assert_eq!(spend_txn.len(), 1);
4769 check_spends!(spend_txn[0], node_txn[0]);
4773 fn test_static_spendable_outputs_timeout_tx() {
4774 let chanmon_cfgs = create_chanmon_cfgs(2);
4775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4777 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4779 // Create some initial channels
4780 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4782 // Rebalance the network a bit by relaying one payment through all the channels ...
4783 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4785 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4787 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4788 assert_eq!(commitment_tx[0].input.len(), 1);
4789 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4791 // Settle A's commitment tx on B' chain
4792 mine_transaction(&nodes[1], &commitment_tx[0]);
4793 check_added_monitors!(nodes[1], 1);
4794 let events = nodes[1].node.get_and_clear_pending_msg_events();
4796 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4797 _ => panic!("Unexpected event"),
4799 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4801 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4802 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4803 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4804 check_spends!(node_txn[0], chan_1.3.clone());
4805 check_spends!(node_txn[1], commitment_tx[0].clone());
4806 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4808 mine_transaction(&nodes[1], &node_txn[1]);
4809 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4810 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4811 expect_payment_failed!(nodes[1], our_payment_hash, true);
4813 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4814 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4815 check_spends!(spend_txn[0], commitment_tx[0]);
4816 check_spends!(spend_txn[1], node_txn[1]);
4817 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4821 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4822 let chanmon_cfgs = create_chanmon_cfgs(2);
4823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4825 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4827 // Create some initial channels
4828 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4830 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4831 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4832 assert_eq!(revoked_local_txn[0].input.len(), 1);
4833 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4835 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4837 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4838 check_closed_broadcast!(nodes[1], true);
4839 check_added_monitors!(nodes[1], 1);
4840 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4842 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4843 assert_eq!(node_txn.len(), 2);
4844 assert_eq!(node_txn[0].input.len(), 2);
4845 check_spends!(node_txn[0], revoked_local_txn[0]);
4847 mine_transaction(&nodes[1], &node_txn[0]);
4848 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4850 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4851 assert_eq!(spend_txn.len(), 1);
4852 check_spends!(spend_txn[0], node_txn[0]);
4856 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4857 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4858 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4863 // Create some initial channels
4864 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4866 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4867 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4868 assert_eq!(revoked_local_txn[0].input.len(), 1);
4869 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4871 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4873 // A will generate HTLC-Timeout from revoked commitment tx
4874 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4875 check_closed_broadcast!(nodes[0], true);
4876 check_added_monitors!(nodes[0], 1);
4877 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4878 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4880 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4881 assert_eq!(revoked_htlc_txn.len(), 2);
4882 check_spends!(revoked_htlc_txn[0], chan_1.3);
4883 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4884 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4885 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4886 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4888 // B will generate justice tx from A's revoked commitment/HTLC tx
4889 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4891 check_closed_broadcast!(nodes[1], true);
4892 check_added_monitors!(nodes[1], 1);
4893 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4895 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4896 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4897 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4898 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4899 // transactions next...
4900 assert_eq!(node_txn[0].input.len(), 3);
4901 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4903 assert_eq!(node_txn[1].input.len(), 2);
4904 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4905 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4906 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4908 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4909 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4912 assert_eq!(node_txn[2].input.len(), 1);
4913 check_spends!(node_txn[2], chan_1.3);
4915 mine_transaction(&nodes[1], &node_txn[1]);
4916 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4918 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4919 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4920 assert_eq!(spend_txn.len(), 1);
4921 assert_eq!(spend_txn[0].input.len(), 1);
4922 check_spends!(spend_txn[0], node_txn[1]);
4926 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4927 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4928 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4929 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4930 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4931 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4933 // Create some initial channels
4934 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4936 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4937 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4938 assert_eq!(revoked_local_txn[0].input.len(), 1);
4939 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4941 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4942 assert_eq!(revoked_local_txn[0].output.len(), 2);
4944 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4946 // B will generate HTLC-Success from revoked commitment tx
4947 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4948 check_closed_broadcast!(nodes[1], true);
4949 check_added_monitors!(nodes[1], 1);
4950 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4951 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4953 assert_eq!(revoked_htlc_txn.len(), 2);
4954 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4955 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4956 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4958 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4959 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4960 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4962 // A will generate justice tx from B's revoked commitment/HTLC tx
4963 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4964 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4965 check_closed_broadcast!(nodes[0], true);
4966 check_added_monitors!(nodes[0], 1);
4967 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4969 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4970 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4972 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4973 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4974 // transactions next...
4975 assert_eq!(node_txn[0].input.len(), 2);
4976 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4977 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4978 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4980 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4981 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4984 assert_eq!(node_txn[1].input.len(), 1);
4985 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4987 check_spends!(node_txn[2], chan_1.3);
4989 mine_transaction(&nodes[0], &node_txn[1]);
4990 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4992 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4993 // didn't try to generate any new transactions.
4995 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4996 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4997 assert_eq!(spend_txn.len(), 3);
4998 assert_eq!(spend_txn[0].input.len(), 1);
4999 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5000 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5001 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5002 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5006 fn test_onchain_to_onchain_claim() {
5007 // Test that in case of channel closure, we detect the state of output and claim HTLC
5008 // on downstream peer's remote commitment tx.
5009 // First, have C claim an HTLC against its own latest commitment transaction.
5010 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5012 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5015 let chanmon_cfgs = create_chanmon_cfgs(3);
5016 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5017 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5018 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5020 // Create some initial channels
5021 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5022 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5024 // Ensure all nodes are at the same height
5025 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5026 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5027 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5028 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5030 // Rebalance the network a bit by relaying one payment through all the channels ...
5031 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5032 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5034 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5035 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5036 check_spends!(commitment_tx[0], chan_2.3);
5037 nodes[2].node.claim_funds(payment_preimage);
5038 check_added_monitors!(nodes[2], 1);
5039 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5040 assert!(updates.update_add_htlcs.is_empty());
5041 assert!(updates.update_fail_htlcs.is_empty());
5042 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5043 assert!(updates.update_fail_malformed_htlcs.is_empty());
5045 mine_transaction(&nodes[2], &commitment_tx[0]);
5046 check_closed_broadcast!(nodes[2], true);
5047 check_added_monitors!(nodes[2], 1);
5048 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5050 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5051 assert_eq!(c_txn.len(), 3);
5052 assert_eq!(c_txn[0], c_txn[2]);
5053 assert_eq!(commitment_tx[0], c_txn[1]);
5054 check_spends!(c_txn[1], chan_2.3);
5055 check_spends!(c_txn[2], c_txn[1]);
5056 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5057 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5058 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5059 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5061 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
5062 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5063 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5064 check_added_monitors!(nodes[1], 1);
5065 let events = nodes[1].node.get_and_clear_pending_events();
5066 assert_eq!(events.len(), 2);
5068 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5069 _ => panic!("Unexpected event"),
5072 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
5073 assert_eq!(fee_earned_msat, Some(1000));
5074 assert_eq!(claim_from_onchain_tx, true);
5076 _ => panic!("Unexpected event"),
5079 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5080 // ChannelMonitor: claim tx
5081 assert_eq!(b_txn.len(), 1);
5082 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5085 check_added_monitors!(nodes[1], 1);
5086 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5087 assert_eq!(msg_events.len(), 3);
5088 match msg_events[0] {
5089 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5090 _ => panic!("Unexpected event"),
5092 match msg_events[1] {
5093 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5094 _ => panic!("Unexpected event"),
5096 match msg_events[2] {
5097 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
5098 assert!(update_add_htlcs.is_empty());
5099 assert!(update_fail_htlcs.is_empty());
5100 assert_eq!(update_fulfill_htlcs.len(), 1);
5101 assert!(update_fail_malformed_htlcs.is_empty());
5102 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5104 _ => panic!("Unexpected event"),
5106 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5107 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5108 mine_transaction(&nodes[1], &commitment_tx[0]);
5109 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5110 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5111 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5112 assert_eq!(b_txn.len(), 3);
5113 check_spends!(b_txn[1], chan_1.3);
5114 check_spends!(b_txn[2], b_txn[1]);
5115 check_spends!(b_txn[0], commitment_tx[0]);
5116 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5117 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5118 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5120 check_closed_broadcast!(nodes[1], true);
5121 check_added_monitors!(nodes[1], 1);
5125 fn test_duplicate_payment_hash_one_failure_one_success() {
5126 // Topology : A --> B --> C --> D
5127 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5128 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5129 // we forward one of the payments onwards to D.
5130 let chanmon_cfgs = create_chanmon_cfgs(4);
5131 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5132 // When this test was written, the default base fee floated based on the HTLC count.
5133 // It is now fixed, so we simply set the fee to the expected value here.
5134 let mut config = test_default_channel_config();
5135 config.channel_options.forwarding_fee_base_msat = 196;
5136 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5137 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5138 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5140 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5141 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5142 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5144 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5145 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5146 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5147 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5148 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5150 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5152 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5153 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5154 // script push size limit so that the below script length checks match
5155 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5156 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
5157 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5158 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5160 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5161 assert_eq!(commitment_txn[0].input.len(), 1);
5162 check_spends!(commitment_txn[0], chan_2.3);
5164 mine_transaction(&nodes[1], &commitment_txn[0]);
5165 check_closed_broadcast!(nodes[1], true);
5166 check_added_monitors!(nodes[1], 1);
5167 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5168 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5170 let htlc_timeout_tx;
5171 { // Extract one of the two HTLC-Timeout transaction
5172 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5173 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5174 assert_eq!(node_txn.len(), 4);
5175 check_spends!(node_txn[0], chan_2.3);
5177 check_spends!(node_txn[1], commitment_txn[0]);
5178 assert_eq!(node_txn[1].input.len(), 1);
5179 check_spends!(node_txn[2], commitment_txn[0]);
5180 assert_eq!(node_txn[2].input.len(), 1);
5181 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5182 check_spends!(node_txn[3], commitment_txn[0]);
5183 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5185 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5186 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5187 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5188 htlc_timeout_tx = node_txn[1].clone();
5191 nodes[2].node.claim_funds(our_payment_preimage);
5192 mine_transaction(&nodes[2], &commitment_txn[0]);
5193 check_added_monitors!(nodes[2], 2);
5194 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5195 let events = nodes[2].node.get_and_clear_pending_msg_events();
5197 MessageSendEvent::UpdateHTLCs { .. } => {},
5198 _ => panic!("Unexpected event"),
5201 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5202 _ => panic!("Unexepected event"),
5204 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5205 assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
5206 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5207 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5208 assert_eq!(htlc_success_txn[0].input.len(), 1);
5209 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5210 assert_eq!(htlc_success_txn[1].input.len(), 1);
5211 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5212 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5213 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5214 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5215 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5216 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5218 mine_transaction(&nodes[1], &htlc_timeout_tx);
5219 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5220 expect_pending_htlcs_forwardable!(nodes[1]);
5221 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5222 assert!(htlc_updates.update_add_htlcs.is_empty());
5223 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5224 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5225 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5226 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5227 check_added_monitors!(nodes[1], 1);
5229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5230 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5232 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5234 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5236 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5237 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5238 // and nodes[2] fee) is rounded down and then claimed in full.
5239 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5240 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5241 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5242 assert!(updates.update_add_htlcs.is_empty());
5243 assert!(updates.update_fail_htlcs.is_empty());
5244 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5245 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5246 assert!(updates.update_fail_malformed_htlcs.is_empty());
5247 check_added_monitors!(nodes[1], 1);
5249 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5250 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5252 let events = nodes[0].node.get_and_clear_pending_events();
5254 Event::PaymentSent { ref payment_preimage } => {
5255 assert_eq!(*payment_preimage, our_payment_preimage);
5257 _ => panic!("Unexpected event"),
5262 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5263 let chanmon_cfgs = create_chanmon_cfgs(2);
5264 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5265 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5266 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5268 // Create some initial channels
5269 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5271 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5272 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5273 assert_eq!(local_txn.len(), 1);
5274 assert_eq!(local_txn[0].input.len(), 1);
5275 check_spends!(local_txn[0], chan_1.3);
5277 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5278 nodes[1].node.claim_funds(payment_preimage);
5279 check_added_monitors!(nodes[1], 1);
5280 mine_transaction(&nodes[1], &local_txn[0]);
5281 check_added_monitors!(nodes[1], 1);
5282 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5283 let events = nodes[1].node.get_and_clear_pending_msg_events();
5285 MessageSendEvent::UpdateHTLCs { .. } => {},
5286 _ => panic!("Unexpected event"),
5289 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5290 _ => panic!("Unexepected event"),
5293 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5294 assert_eq!(node_txn.len(), 3);
5295 assert_eq!(node_txn[0], node_txn[2]);
5296 assert_eq!(node_txn[1], local_txn[0]);
5297 assert_eq!(node_txn[0].input.len(), 1);
5298 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5299 check_spends!(node_txn[0], local_txn[0]);
5303 mine_transaction(&nodes[1], &node_tx);
5304 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5306 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5307 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5308 assert_eq!(spend_txn.len(), 1);
5309 assert_eq!(spend_txn[0].input.len(), 1);
5310 check_spends!(spend_txn[0], node_tx);
5311 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5314 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5315 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5316 // unrevoked commitment transaction.
5317 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5318 // a remote RAA before they could be failed backwards (and combinations thereof).
5319 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5320 // use the same payment hashes.
5321 // Thus, we use a six-node network:
5326 // And test where C fails back to A/B when D announces its latest commitment transaction
5327 let chanmon_cfgs = create_chanmon_cfgs(6);
5328 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5329 // When this test was written, the default base fee floated based on the HTLC count.
5330 // It is now fixed, so we simply set the fee to the expected value here.
5331 let mut config = test_default_channel_config();
5332 config.channel_options.forwarding_fee_base_msat = 196;
5333 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5334 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5335 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5336 let logger = test_utils::TestLogger::new();
5338 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5339 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5340 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5341 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5342 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5344 // Rebalance and check output sanity...
5345 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5346 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5347 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5349 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5351 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5353 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5354 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5355 let our_node_id = &nodes[1].node.get_our_node_id();
5356 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5358 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5360 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5362 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5364 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5365 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5367 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, 0).unwrap());
5369 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, 0).unwrap());
5372 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5374 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5375 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5378 let (_, payment_hash_6, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5380 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph, &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5381 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, 0).unwrap());
5383 // Double-check that six of the new HTLC were added
5384 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5385 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5386 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5387 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5389 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5390 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5391 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5392 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5393 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5394 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5395 check_added_monitors!(nodes[4], 0);
5396 expect_pending_htlcs_forwardable!(nodes[4]);
5397 check_added_monitors!(nodes[4], 1);
5399 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5400 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5401 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5402 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5403 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5404 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5406 // Fail 3rd below-dust and 7th above-dust HTLCs
5407 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5408 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5409 check_added_monitors!(nodes[5], 0);
5410 expect_pending_htlcs_forwardable!(nodes[5]);
5411 check_added_monitors!(nodes[5], 1);
5413 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5414 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5415 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5416 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5418 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5420 expect_pending_htlcs_forwardable!(nodes[3]);
5421 check_added_monitors!(nodes[3], 1);
5422 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5423 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5424 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5425 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5426 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5427 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5428 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5429 if deliver_last_raa {
5430 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5432 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5435 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5436 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5437 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5438 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5440 // We now broadcast the latest commitment transaction, which *should* result in failures for
5441 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5442 // the non-broadcast above-dust HTLCs.
5444 // Alternatively, we may broadcast the previous commitment transaction, which should only
5445 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5446 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5448 if announce_latest {
5449 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5451 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5453 let events = nodes[2].node.get_and_clear_pending_events();
5454 let close_event = if deliver_last_raa {
5455 assert_eq!(events.len(), 2);
5458 assert_eq!(events.len(), 1);
5462 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5463 _ => panic!("Unexpected event"),
5466 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5467 check_closed_broadcast!(nodes[2], true);
5468 if deliver_last_raa {
5469 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5471 expect_pending_htlcs_forwardable!(nodes[2]);
5473 check_added_monitors!(nodes[2], 3);
5475 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5476 assert_eq!(cs_msgs.len(), 2);
5477 let mut a_done = false;
5478 for msg in cs_msgs {
5480 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5481 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5482 // should be failed-backwards here.
5483 let target = if *node_id == nodes[0].node.get_our_node_id() {
5484 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5485 for htlc in &updates.update_fail_htlcs {
5486 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5488 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5493 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5494 for htlc in &updates.update_fail_htlcs {
5495 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5497 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5498 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5501 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5502 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5503 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5504 if announce_latest {
5505 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5506 if *node_id == nodes[0].node.get_our_node_id() {
5507 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5510 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5512 _ => panic!("Unexpected event"),
5516 let as_events = nodes[0].node.get_and_clear_pending_events();
5517 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5518 let mut as_failds = HashSet::new();
5519 let mut as_updates = 0;
5520 for event in as_events.iter() {
5521 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5522 assert!(as_failds.insert(*payment_hash));
5523 if *payment_hash != payment_hash_2 {
5524 assert_eq!(*rejected_by_dest, deliver_last_raa);
5526 assert!(!rejected_by_dest);
5528 if network_update.is_some() {
5531 } else { panic!("Unexpected event"); }
5533 assert!(as_failds.contains(&payment_hash_1));
5534 assert!(as_failds.contains(&payment_hash_2));
5535 if announce_latest {
5536 assert!(as_failds.contains(&payment_hash_3));
5537 assert!(as_failds.contains(&payment_hash_5));
5539 assert!(as_failds.contains(&payment_hash_6));
5541 let bs_events = nodes[1].node.get_and_clear_pending_events();
5542 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5543 let mut bs_failds = HashSet::new();
5544 let mut bs_updates = 0;
5545 for event in bs_events.iter() {
5546 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5547 assert!(bs_failds.insert(*payment_hash));
5548 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5549 assert_eq!(*rejected_by_dest, deliver_last_raa);
5551 assert!(!rejected_by_dest);
5553 if network_update.is_some() {
5556 } else { panic!("Unexpected event"); }
5558 assert!(bs_failds.contains(&payment_hash_1));
5559 assert!(bs_failds.contains(&payment_hash_2));
5560 if announce_latest {
5561 assert!(bs_failds.contains(&payment_hash_4));
5563 assert!(bs_failds.contains(&payment_hash_5));
5565 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5566 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5567 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5568 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5569 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5570 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5574 fn test_fail_backwards_latest_remote_announce_a() {
5575 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5579 fn test_fail_backwards_latest_remote_announce_b() {
5580 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5584 fn test_fail_backwards_previous_remote_announce() {
5585 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5586 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5587 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5591 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5592 let chanmon_cfgs = create_chanmon_cfgs(2);
5593 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5594 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5595 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5597 // Create some initial channels
5598 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5600 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5601 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5602 assert_eq!(local_txn[0].input.len(), 1);
5603 check_spends!(local_txn[0], chan_1.3);
5605 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5606 mine_transaction(&nodes[0], &local_txn[0]);
5607 check_closed_broadcast!(nodes[0], true);
5608 check_added_monitors!(nodes[0], 1);
5609 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5610 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5612 let htlc_timeout = {
5613 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5614 assert_eq!(node_txn.len(), 2);
5615 check_spends!(node_txn[0], chan_1.3);
5616 assert_eq!(node_txn[1].input.len(), 1);
5617 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5618 check_spends!(node_txn[1], local_txn[0]);
5622 mine_transaction(&nodes[0], &htlc_timeout);
5623 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5624 expect_payment_failed!(nodes[0], our_payment_hash, true);
5626 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5627 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5628 assert_eq!(spend_txn.len(), 3);
5629 check_spends!(spend_txn[0], local_txn[0]);
5630 assert_eq!(spend_txn[1].input.len(), 1);
5631 check_spends!(spend_txn[1], htlc_timeout);
5632 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5633 assert_eq!(spend_txn[2].input.len(), 2);
5634 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5635 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5636 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5640 fn test_key_derivation_params() {
5641 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5642 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5643 // let us re-derive the channel key set to then derive a delayed_payment_key.
5645 let chanmon_cfgs = create_chanmon_cfgs(3);
5647 // We manually create the node configuration to backup the seed.
5648 let seed = [42; 32];
5649 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5650 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5651 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, node_seed: seed, features: InitFeatures::known() };
5652 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5653 node_cfgs.remove(0);
5654 node_cfgs.insert(0, node);
5656 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5657 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5659 // Create some initial channels
5660 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5662 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5663 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5664 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5666 // Ensure all nodes are at the same height
5667 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5668 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5669 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5670 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5672 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5673 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5674 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5675 assert_eq!(local_txn_1[0].input.len(), 1);
5676 check_spends!(local_txn_1[0], chan_1.3);
5678 // We check funding pubkey are unique
5679 let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness[3][36..69]));
5680 let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness[3][36..69]));
5681 if from_0_funding_key_0 == from_1_funding_key_0
5682 || from_0_funding_key_0 == from_1_funding_key_1
5683 || from_0_funding_key_1 == from_1_funding_key_0
5684 || from_0_funding_key_1 == from_1_funding_key_1 {
5685 panic!("Funding pubkeys aren't unique");
5688 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5689 mine_transaction(&nodes[0], &local_txn_1[0]);
5690 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5691 check_closed_broadcast!(nodes[0], true);
5692 check_added_monitors!(nodes[0], 1);
5693 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5695 let htlc_timeout = {
5696 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5697 assert_eq!(node_txn[1].input.len(), 1);
5698 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5699 check_spends!(node_txn[1], local_txn_1[0]);
5703 mine_transaction(&nodes[0], &htlc_timeout);
5704 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5705 expect_payment_failed!(nodes[0], our_payment_hash, true);
5707 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5708 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5709 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5710 assert_eq!(spend_txn.len(), 3);
5711 check_spends!(spend_txn[0], local_txn_1[0]);
5712 assert_eq!(spend_txn[1].input.len(), 1);
5713 check_spends!(spend_txn[1], htlc_timeout);
5714 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5715 assert_eq!(spend_txn[2].input.len(), 2);
5716 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5717 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5718 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5722 fn test_static_output_closing_tx() {
5723 let chanmon_cfgs = create_chanmon_cfgs(2);
5724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5726 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5728 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5730 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5731 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5733 mine_transaction(&nodes[0], &closing_tx);
5734 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5735 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5737 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5738 assert_eq!(spend_txn.len(), 1);
5739 check_spends!(spend_txn[0], closing_tx);
5741 mine_transaction(&nodes[1], &closing_tx);
5742 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5743 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5745 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5746 assert_eq!(spend_txn.len(), 1);
5747 check_spends!(spend_txn[0], closing_tx);
5750 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5751 let chanmon_cfgs = create_chanmon_cfgs(2);
5752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5757 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5759 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5760 // present in B's local commitment transaction, but none of A's commitment transactions.
5761 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5762 check_added_monitors!(nodes[1], 1);
5764 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5765 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5766 let events = nodes[0].node.get_and_clear_pending_events();
5767 assert_eq!(events.len(), 1);
5769 Event::PaymentSent { payment_preimage } => {
5770 assert_eq!(payment_preimage, our_payment_preimage);
5772 _ => panic!("Unexpected event"),
5775 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5776 check_added_monitors!(nodes[0], 1);
5777 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5778 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5779 check_added_monitors!(nodes[1], 1);
5781 let starting_block = nodes[1].best_block_info();
5782 let mut block = Block {
5783 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5786 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5787 connect_block(&nodes[1], &block);
5788 block.header.prev_blockhash = block.block_hash();
5790 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5791 check_closed_broadcast!(nodes[1], true);
5792 check_added_monitors!(nodes[1], 1);
5793 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5796 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5797 let chanmon_cfgs = create_chanmon_cfgs(2);
5798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5800 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5801 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802 let logger = test_utils::TestLogger::new();
5804 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
5805 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5806 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5807 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5808 check_added_monitors!(nodes[0], 1);
5810 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5812 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5813 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5814 // to "time out" the HTLC.
5816 let starting_block = nodes[1].best_block_info();
5817 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5819 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5820 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5821 header.prev_blockhash = header.block_hash();
5823 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5824 check_closed_broadcast!(nodes[0], true);
5825 check_added_monitors!(nodes[0], 1);
5826 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5829 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5830 let chanmon_cfgs = create_chanmon_cfgs(3);
5831 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5832 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5833 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5834 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5836 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5837 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5838 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5839 // actually revoked.
5840 let htlc_value = if use_dust { 50000 } else { 3000000 };
5841 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5842 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5843 expect_pending_htlcs_forwardable!(nodes[1]);
5844 check_added_monitors!(nodes[1], 1);
5846 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5847 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5848 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5849 check_added_monitors!(nodes[0], 1);
5850 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5851 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5852 check_added_monitors!(nodes[1], 1);
5853 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5854 check_added_monitors!(nodes[1], 1);
5855 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5857 if check_revoke_no_close {
5858 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5859 check_added_monitors!(nodes[0], 1);
5862 let starting_block = nodes[1].best_block_info();
5863 let mut block = Block {
5864 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5867 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5868 connect_block(&nodes[0], &block);
5869 block.header.prev_blockhash = block.block_hash();
5871 if !check_revoke_no_close {
5872 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5873 check_closed_broadcast!(nodes[0], true);
5874 check_added_monitors!(nodes[0], 1);
5875 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5877 expect_payment_failed!(nodes[0], our_payment_hash, true);
5881 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5882 // There are only a few cases to test here:
5883 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5884 // broadcastable commitment transactions result in channel closure,
5885 // * its included in an unrevoked-but-previous remote commitment transaction,
5886 // * its included in the latest remote or local commitment transactions.
5887 // We test each of the three possible commitment transactions individually and use both dust and
5889 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5890 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5891 // tested for at least one of the cases in other tests.
5893 fn htlc_claim_single_commitment_only_a() {
5894 do_htlc_claim_local_commitment_only(true);
5895 do_htlc_claim_local_commitment_only(false);
5897 do_htlc_claim_current_remote_commitment_only(true);
5898 do_htlc_claim_current_remote_commitment_only(false);
5902 fn htlc_claim_single_commitment_only_b() {
5903 do_htlc_claim_previous_remote_commitment_only(true, false);
5904 do_htlc_claim_previous_remote_commitment_only(false, false);
5905 do_htlc_claim_previous_remote_commitment_only(true, true);
5906 do_htlc_claim_previous_remote_commitment_only(false, true);
5911 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5912 let chanmon_cfgs = create_chanmon_cfgs(2);
5913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5916 //Force duplicate channel ids
5917 for node in nodes.iter() {
5918 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5921 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5922 let channel_value_satoshis=10000;
5923 let push_msat=10001;
5924 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5925 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5926 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5928 //Create a second channel with a channel_id collision
5929 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5933 fn bolt2_open_channel_sending_node_checks_part2() {
5934 let chanmon_cfgs = create_chanmon_cfgs(2);
5935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5939 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5940 let channel_value_satoshis=2^24;
5941 let push_msat=10001;
5942 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5944 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5945 let channel_value_satoshis=10000;
5946 // Test when push_msat is equal to 1000 * funding_satoshis.
5947 let push_msat=1000*channel_value_satoshis+1;
5948 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5950 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5951 let channel_value_satoshis=10000;
5952 let push_msat=10001;
5953 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5954 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5955 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5957 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5958 // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5959 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5961 // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5962 assert!(BREAKDOWN_TIMEOUT>0);
5963 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5965 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5966 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5967 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5969 // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5970 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5971 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5972 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5973 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5974 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5978 fn bolt2_open_channel_sane_dust_limit() {
5979 let chanmon_cfgs = create_chanmon_cfgs(2);
5980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5984 let channel_value_satoshis=1000000;
5985 let push_msat=10001;
5986 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5987 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5988 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5989 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5991 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5992 let events = nodes[1].node.get_and_clear_pending_msg_events();
5993 let err_msg = match events[0] {
5994 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5997 _ => panic!("Unexpected event"),
5999 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
6002 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6003 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6004 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6005 // is no longer affordable once it's freed.
6007 fn test_fail_holding_cell_htlc_upon_free() {
6008 let chanmon_cfgs = create_chanmon_cfgs(2);
6009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6011 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6012 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6013 let logger = test_utils::TestLogger::new();
6015 // First nodes[0] generates an update_fee, setting the channel's
6016 // pending_update_fee.
6018 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6019 *feerate_lock += 20;
6021 nodes[0].node.timer_tick_occurred();
6022 check_added_monitors!(nodes[0], 1);
6024 let events = nodes[0].node.get_and_clear_pending_msg_events();
6025 assert_eq!(events.len(), 1);
6026 let (update_msg, commitment_signed) = match events[0] {
6027 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6028 (update_fee.as_ref(), commitment_signed)
6030 _ => panic!("Unexpected event"),
6033 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6035 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6036 let channel_reserve = chan_stat.channel_reserve_msat;
6037 let feerate = get_feerate!(nodes[0], chan.2);
6039 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6040 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6041 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6042 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6043 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6045 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6046 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6047 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6048 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6050 // Flush the pending fee update.
6051 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6052 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6053 check_added_monitors!(nodes[1], 1);
6054 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6055 check_added_monitors!(nodes[0], 1);
6057 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6058 // HTLC, but now that the fee has been raised the payment will now fail, causing
6059 // us to surface its failure to the user.
6060 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6061 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6062 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Freeing holding cell with 1 HTLC updates in channel {}", hex::encode(chan.2)), 1);
6063 let failure_log = format!("Failed to send HTLC with payment_hash {} due to Cannot send value that would put our balance under counterparty-announced channel reserve value ({}) in channel {}",
6064 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6065 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6067 // Check that the payment failed to be sent out.
6068 let events = nodes[0].node.get_and_clear_pending_events();
6069 assert_eq!(events.len(), 1);
6071 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6072 assert_eq!(our_payment_hash.clone(), *payment_hash);
6073 assert_eq!(*rejected_by_dest, false);
6074 assert_eq!(*all_paths_failed, true);
6075 assert_eq!(*network_update, None);
6076 assert_eq!(*short_channel_id, None);
6077 assert_eq!(*error_code, None);
6078 assert_eq!(*error_data, None);
6080 _ => panic!("Unexpected event"),
6084 // Test that if multiple HTLCs are released from the holding cell and one is
6085 // valid but the other is no longer valid upon release, the valid HTLC can be
6086 // successfully completed while the other one fails as expected.
6088 fn test_free_and_fail_holding_cell_htlcs() {
6089 let chanmon_cfgs = create_chanmon_cfgs(2);
6090 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6091 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6092 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6093 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6094 let logger = test_utils::TestLogger::new();
6096 // First nodes[0] generates an update_fee, setting the channel's
6097 // pending_update_fee.
6099 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6100 *feerate_lock += 200;
6102 nodes[0].node.timer_tick_occurred();
6103 check_added_monitors!(nodes[0], 1);
6105 let events = nodes[0].node.get_and_clear_pending_msg_events();
6106 assert_eq!(events.len(), 1);
6107 let (update_msg, commitment_signed) = match events[0] {
6108 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6109 (update_fee.as_ref(), commitment_signed)
6111 _ => panic!("Unexpected event"),
6114 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6116 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6117 let channel_reserve = chan_stat.channel_reserve_msat;
6118 let feerate = get_feerate!(nodes[0], chan.2);
6120 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6121 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6123 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6124 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6125 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6126 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();
6127 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();
6129 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6130 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6131 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6132 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6133 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6134 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6135 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6137 // Flush the pending fee update.
6138 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6139 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6140 check_added_monitors!(nodes[1], 1);
6141 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6142 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6143 check_added_monitors!(nodes[0], 2);
6145 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6146 // but now that the fee has been raised the second payment will now fail, causing us
6147 // to surface its failure to the user. The first payment should succeed.
6148 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6149 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6150 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);
6151 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 {}",
6152 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6153 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6155 // Check that the second payment failed to be sent out.
6156 let events = nodes[0].node.get_and_clear_pending_events();
6157 assert_eq!(events.len(), 1);
6159 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6160 assert_eq!(payment_hash_2.clone(), *payment_hash);
6161 assert_eq!(*rejected_by_dest, false);
6162 assert_eq!(*all_paths_failed, true);
6163 assert_eq!(*network_update, None);
6164 assert_eq!(*short_channel_id, None);
6165 assert_eq!(*error_code, None);
6166 assert_eq!(*error_data, None);
6168 _ => panic!("Unexpected event"),
6171 // Complete the first payment and the RAA from the fee update.
6172 let (payment_event, send_raa_event) = {
6173 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6174 assert_eq!(msgs.len(), 2);
6175 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6177 let raa = match send_raa_event {
6178 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6179 _ => panic!("Unexpected event"),
6181 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6182 check_added_monitors!(nodes[1], 1);
6183 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6184 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6185 let events = nodes[1].node.get_and_clear_pending_events();
6186 assert_eq!(events.len(), 1);
6188 Event::PendingHTLCsForwardable { .. } => {},
6189 _ => panic!("Unexpected event"),
6191 nodes[1].node.process_pending_htlc_forwards();
6192 let events = nodes[1].node.get_and_clear_pending_events();
6193 assert_eq!(events.len(), 1);
6195 Event::PaymentReceived { .. } => {},
6196 _ => panic!("Unexpected event"),
6198 nodes[1].node.claim_funds(payment_preimage_1);
6199 check_added_monitors!(nodes[1], 1);
6200 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6201 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6202 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6203 let events = nodes[0].node.get_and_clear_pending_events();
6204 assert_eq!(events.len(), 1);
6206 Event::PaymentSent { ref payment_preimage } => {
6207 assert_eq!(*payment_preimage, payment_preimage_1);
6209 _ => panic!("Unexpected event"),
6213 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6214 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6215 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6218 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6219 let chanmon_cfgs = create_chanmon_cfgs(3);
6220 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6221 // When this test was written, the default base fee floated based on the HTLC count.
6222 // It is now fixed, so we simply set the fee to the expected value here.
6223 let mut config = test_default_channel_config();
6224 config.channel_options.forwarding_fee_base_msat = 196;
6225 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6226 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6227 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6228 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6229 let logger = test_utils::TestLogger::new();
6231 // First nodes[1] generates an update_fee, setting the channel's
6232 // pending_update_fee.
6234 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6235 *feerate_lock += 20;
6237 nodes[1].node.timer_tick_occurred();
6238 check_added_monitors!(nodes[1], 1);
6240 let events = nodes[1].node.get_and_clear_pending_msg_events();
6241 assert_eq!(events.len(), 1);
6242 let (update_msg, commitment_signed) = match events[0] {
6243 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6244 (update_fee.as_ref(), commitment_signed)
6246 _ => panic!("Unexpected event"),
6249 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6251 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6252 let channel_reserve = chan_stat.channel_reserve_msat;
6253 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6255 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6257 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6258 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6259 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6260 let payment_event = {
6261 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6262 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();
6263 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6264 check_added_monitors!(nodes[0], 1);
6266 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6267 assert_eq!(events.len(), 1);
6269 SendEvent::from_event(events.remove(0))
6271 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6272 check_added_monitors!(nodes[1], 0);
6273 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6274 expect_pending_htlcs_forwardable!(nodes[1]);
6276 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6277 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6279 // Flush the pending fee update.
6280 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6281 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6282 check_added_monitors!(nodes[2], 1);
6283 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6284 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6285 check_added_monitors!(nodes[1], 2);
6287 // A final RAA message is generated to finalize the fee update.
6288 let events = nodes[1].node.get_and_clear_pending_msg_events();
6289 assert_eq!(events.len(), 1);
6291 let raa_msg = match &events[0] {
6292 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6295 _ => panic!("Unexpected event"),
6298 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6299 check_added_monitors!(nodes[2], 1);
6300 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6302 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6303 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6304 assert_eq!(process_htlc_forwards_event.len(), 1);
6305 match &process_htlc_forwards_event[0] {
6306 &Event::PendingHTLCsForwardable { .. } => {},
6307 _ => panic!("Unexpected event"),
6310 // In response, we call ChannelManager's process_pending_htlc_forwards
6311 nodes[1].node.process_pending_htlc_forwards();
6312 check_added_monitors!(nodes[1], 1);
6314 // This causes the HTLC to be failed backwards.
6315 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6316 assert_eq!(fail_event.len(), 1);
6317 let (fail_msg, commitment_signed) = match &fail_event[0] {
6318 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6319 assert_eq!(updates.update_add_htlcs.len(), 0);
6320 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6321 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6322 assert_eq!(updates.update_fail_htlcs.len(), 1);
6323 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6325 _ => panic!("Unexpected event"),
6328 // Pass the failure messages back to nodes[0].
6329 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6330 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6332 // Complete the HTLC failure+removal process.
6333 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6334 check_added_monitors!(nodes[0], 1);
6335 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6336 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6337 check_added_monitors!(nodes[1], 2);
6338 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6339 assert_eq!(final_raa_event.len(), 1);
6340 let raa = match &final_raa_event[0] {
6341 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6342 _ => panic!("Unexpected event"),
6344 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6345 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6346 check_added_monitors!(nodes[0], 1);
6349 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6350 // 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.
6351 //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.
6354 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6355 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6356 let chanmon_cfgs = create_chanmon_cfgs(2);
6357 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6358 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6359 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6360 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6362 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6363 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6364 let logger = test_utils::TestLogger::new();
6365 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();
6366 route.paths[0][0].fee_msat = 100;
6368 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6369 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6370 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6371 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6375 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6376 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
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());
6382 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 = 0;
6388 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6389 assert_eq!(err, "Cannot send 0-msat HTLC"));
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 0-msat HTLC".to_string(), 1);
6396 fn test_update_add_htlc_bolt2_receiver_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());
6404 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 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 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6409 check_added_monitors!(nodes[0], 1);
6410 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6411 updates.update_add_htlcs[0].amount_msat = 0;
6413 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6414 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6415 check_closed_broadcast!(nodes[1], true).unwrap();
6416 check_added_monitors!(nodes[1], 1);
6417 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6421 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6422 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6423 //It is enforced when constructing a route.
6424 let chanmon_cfgs = create_chanmon_cfgs(2);
6425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6427 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6428 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6429 let logger = test_utils::TestLogger::new();
6431 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6433 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6434 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();
6435 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6436 assert_eq!(err, &"Channel CLTV overflowed?"));
6440 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6441 //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.
6442 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6443 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6444 let chanmon_cfgs = create_chanmon_cfgs(2);
6445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6447 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6448 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6449 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6451 let logger = test_utils::TestLogger::new();
6452 for i in 0..max_accepted_htlcs {
6453 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6454 let payment_event = {
6455 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6456 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();
6457 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6458 check_added_monitors!(nodes[0], 1);
6460 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6461 assert_eq!(events.len(), 1);
6462 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6463 assert_eq!(htlcs[0].htlc_id, i);
6467 SendEvent::from_event(events.remove(0))
6469 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6470 check_added_monitors!(nodes[1], 0);
6471 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6473 expect_pending_htlcs_forwardable!(nodes[1]);
6474 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6476 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6477 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6478 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();
6479 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6480 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6482 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6483 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6487 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6488 //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.
6489 let chanmon_cfgs = create_chanmon_cfgs(2);
6490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6492 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6493 let channel_value = 100000;
6494 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6495 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6497 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6499 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6500 // Manually create a route over our max in flight (which our router normally automatically
6502 let route = Route { paths: vec![vec![RouteHop {
6503 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6504 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6505 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6507 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6508 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)));
6510 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6511 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);
6513 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6516 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6518 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6519 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6520 let chanmon_cfgs = create_chanmon_cfgs(2);
6521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6523 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6524 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6525 let htlc_minimum_msat: u64;
6527 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6528 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6529 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6532 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6533 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6534 let logger = test_utils::TestLogger::new();
6535 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();
6536 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6537 check_added_monitors!(nodes[0], 1);
6538 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6539 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6540 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6541 assert!(nodes[1].node.list_channels().is_empty());
6542 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6543 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()));
6544 check_added_monitors!(nodes[1], 1);
6545 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6549 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6550 //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
6551 let chanmon_cfgs = create_chanmon_cfgs(2);
6552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6554 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6555 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6556 let logger = test_utils::TestLogger::new();
6558 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6559 let channel_reserve = chan_stat.channel_reserve_msat;
6560 let feerate = get_feerate!(nodes[0], chan.2);
6561 // The 2* and +1 are for the fee spike reserve.
6562 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6564 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6565 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6566 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6567 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();
6568 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6569 check_added_monitors!(nodes[0], 1);
6570 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6572 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6573 // at this time channel-initiatee receivers are not required to enforce that senders
6574 // respect the fee_spike_reserve.
6575 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6576 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6578 assert!(nodes[1].node.list_channels().is_empty());
6579 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6580 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6581 check_added_monitors!(nodes[1], 1);
6582 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6586 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6587 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6588 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6589 let chanmon_cfgs = create_chanmon_cfgs(2);
6590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6592 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6593 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6594 let logger = test_utils::TestLogger::new();
6596 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6597 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6599 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6600 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();
6602 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6603 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6604 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6605 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6607 let mut msg = msgs::UpdateAddHTLC {
6611 payment_hash: our_payment_hash,
6612 cltv_expiry: htlc_cltv,
6613 onion_routing_packet: onion_packet.clone(),
6616 for i in 0..super::channel::OUR_MAX_HTLCS {
6617 msg.htlc_id = i as u64;
6618 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6620 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6621 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6623 assert!(nodes[1].node.list_channels().is_empty());
6624 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6625 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6626 check_added_monitors!(nodes[1], 1);
6627 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6631 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6632 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6633 let chanmon_cfgs = create_chanmon_cfgs(2);
6634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6636 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6637 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6638 let logger = test_utils::TestLogger::new();
6640 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6641 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6642 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();
6643 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6644 check_added_monitors!(nodes[0], 1);
6645 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6646 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6647 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6649 assert!(nodes[1].node.list_channels().is_empty());
6650 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6651 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6652 check_added_monitors!(nodes[1], 1);
6653 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6657 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6658 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6659 let chanmon_cfgs = create_chanmon_cfgs(2);
6660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6662 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6663 let logger = test_utils::TestLogger::new();
6665 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6666 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6667 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6668 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();
6669 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6670 check_added_monitors!(nodes[0], 1);
6671 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6672 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6673 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6675 assert!(nodes[1].node.list_channels().is_empty());
6676 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6677 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6678 check_added_monitors!(nodes[1], 1);
6679 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6683 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6684 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6685 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6686 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6687 let chanmon_cfgs = create_chanmon_cfgs(2);
6688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691 let logger = test_utils::TestLogger::new();
6693 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6694 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6695 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6696 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();
6697 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6698 check_added_monitors!(nodes[0], 1);
6699 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6700 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6702 //Disconnect and Reconnect
6703 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6704 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6705 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6706 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6707 assert_eq!(reestablish_1.len(), 1);
6708 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6709 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6710 assert_eq!(reestablish_2.len(), 1);
6711 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6712 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6713 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6714 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6717 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6718 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6719 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6720 check_added_monitors!(nodes[1], 1);
6721 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6723 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6725 assert!(nodes[1].node.list_channels().is_empty());
6726 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6727 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6728 check_added_monitors!(nodes[1], 1);
6729 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6733 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6734 //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.
6736 let chanmon_cfgs = create_chanmon_cfgs(2);
6737 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6738 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6739 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6740 let logger = test_utils::TestLogger::new();
6741 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6742 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6743 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6744 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();
6745 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6747 check_added_monitors!(nodes[0], 1);
6748 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6749 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6751 let update_msg = msgs::UpdateFulfillHTLC{
6754 payment_preimage: our_payment_preimage,
6757 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6759 assert!(nodes[0].node.list_channels().is_empty());
6760 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6761 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()));
6762 check_added_monitors!(nodes[0], 1);
6763 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6767 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6768 //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.
6770 let chanmon_cfgs = create_chanmon_cfgs(2);
6771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6773 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6774 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6775 let logger = test_utils::TestLogger::new();
6777 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6778 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6779 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();
6780 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6781 check_added_monitors!(nodes[0], 1);
6782 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6783 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785 let update_msg = msgs::UpdateFailHTLC{
6788 reason: msgs::OnionErrorPacket { data: Vec::new()},
6791 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6793 assert!(nodes[0].node.list_channels().is_empty());
6794 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6795 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()));
6796 check_added_monitors!(nodes[0], 1);
6797 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6801 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6802 //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.
6804 let chanmon_cfgs = create_chanmon_cfgs(2);
6805 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6806 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6807 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6808 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6809 let logger = test_utils::TestLogger::new();
6811 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6812 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6813 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();
6814 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6815 check_added_monitors!(nodes[0], 1);
6816 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6817 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6818 let update_msg = msgs::UpdateFailMalformedHTLC{
6821 sha256_of_onion: [1; 32],
6822 failure_code: 0x8000,
6825 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6827 assert!(nodes[0].node.list_channels().is_empty());
6828 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6829 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()));
6830 check_added_monitors!(nodes[0], 1);
6831 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6835 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6836 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6838 let chanmon_cfgs = create_chanmon_cfgs(2);
6839 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6840 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6841 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6842 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6844 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6846 nodes[1].node.claim_funds(our_payment_preimage);
6847 check_added_monitors!(nodes[1], 1);
6849 let events = nodes[1].node.get_and_clear_pending_msg_events();
6850 assert_eq!(events.len(), 1);
6851 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6853 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, .. } } => {
6854 assert!(update_add_htlcs.is_empty());
6855 assert_eq!(update_fulfill_htlcs.len(), 1);
6856 assert!(update_fail_htlcs.is_empty());
6857 assert!(update_fail_malformed_htlcs.is_empty());
6858 assert!(update_fee.is_none());
6859 update_fulfill_htlcs[0].clone()
6861 _ => panic!("Unexpected event"),
6865 update_fulfill_msg.htlc_id = 1;
6867 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6869 assert!(nodes[0].node.list_channels().is_empty());
6870 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6871 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6872 check_added_monitors!(nodes[0], 1);
6873 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6877 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6878 //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.
6880 let chanmon_cfgs = create_chanmon_cfgs(2);
6881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6884 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6886 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6888 nodes[1].node.claim_funds(our_payment_preimage);
6889 check_added_monitors!(nodes[1], 1);
6891 let events = nodes[1].node.get_and_clear_pending_msg_events();
6892 assert_eq!(events.len(), 1);
6893 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6895 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, .. } } => {
6896 assert!(update_add_htlcs.is_empty());
6897 assert_eq!(update_fulfill_htlcs.len(), 1);
6898 assert!(update_fail_htlcs.is_empty());
6899 assert!(update_fail_malformed_htlcs.is_empty());
6900 assert!(update_fee.is_none());
6901 update_fulfill_htlcs[0].clone()
6903 _ => panic!("Unexpected event"),
6907 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6909 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6911 assert!(nodes[0].node.list_channels().is_empty());
6912 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6913 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6914 check_added_monitors!(nodes[0], 1);
6915 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6919 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6920 //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.
6922 let chanmon_cfgs = create_chanmon_cfgs(2);
6923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6925 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6926 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6927 let logger = test_utils::TestLogger::new();
6929 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6930 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6931 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();
6932 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6933 check_added_monitors!(nodes[0], 1);
6935 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6936 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6938 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6939 check_added_monitors!(nodes[1], 0);
6940 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6942 let events = nodes[1].node.get_and_clear_pending_msg_events();
6944 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6946 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, .. } } => {
6947 assert!(update_add_htlcs.is_empty());
6948 assert!(update_fulfill_htlcs.is_empty());
6949 assert!(update_fail_htlcs.is_empty());
6950 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6951 assert!(update_fee.is_none());
6952 update_fail_malformed_htlcs[0].clone()
6954 _ => panic!("Unexpected event"),
6957 update_msg.failure_code &= !0x8000;
6958 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6960 assert!(nodes[0].node.list_channels().is_empty());
6961 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6962 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6963 check_added_monitors!(nodes[0], 1);
6964 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6968 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6969 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6970 // * 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.
6972 let chanmon_cfgs = create_chanmon_cfgs(3);
6973 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6974 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6975 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6976 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6977 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6978 let logger = test_utils::TestLogger::new();
6980 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6983 let mut payment_event = {
6984 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6985 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();
6986 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6987 check_added_monitors!(nodes[0], 1);
6988 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6989 assert_eq!(events.len(), 1);
6990 SendEvent::from_event(events.remove(0))
6992 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6993 check_added_monitors!(nodes[1], 0);
6994 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6995 expect_pending_htlcs_forwardable!(nodes[1]);
6996 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6997 assert_eq!(events_2.len(), 1);
6998 check_added_monitors!(nodes[1], 1);
6999 payment_event = SendEvent::from_event(events_2.remove(0));
7000 assert_eq!(payment_event.msgs.len(), 1);
7003 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7004 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7005 check_added_monitors!(nodes[2], 0);
7006 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7008 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7009 assert_eq!(events_3.len(), 1);
7010 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7012 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 } } => {
7013 assert!(update_add_htlcs.is_empty());
7014 assert!(update_fulfill_htlcs.is_empty());
7015 assert!(update_fail_htlcs.is_empty());
7016 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7017 assert!(update_fee.is_none());
7018 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7020 _ => panic!("Unexpected event"),
7024 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7026 check_added_monitors!(nodes[1], 0);
7027 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7028 expect_pending_htlcs_forwardable!(nodes[1]);
7029 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7030 assert_eq!(events_4.len(), 1);
7032 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7034 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, .. } } => {
7035 assert!(update_add_htlcs.is_empty());
7036 assert!(update_fulfill_htlcs.is_empty());
7037 assert_eq!(update_fail_htlcs.len(), 1);
7038 assert!(update_fail_malformed_htlcs.is_empty());
7039 assert!(update_fee.is_none());
7041 _ => panic!("Unexpected event"),
7044 check_added_monitors!(nodes[1], 1);
7047 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7048 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7049 // 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
7050 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7052 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7053 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7056 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7057 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7059 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7061 // We route 2 dust-HTLCs between A and B
7062 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7063 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7064 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7066 // Cache one local commitment tx as previous
7067 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7069 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7070 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7071 check_added_monitors!(nodes[1], 0);
7072 expect_pending_htlcs_forwardable!(nodes[1]);
7073 check_added_monitors!(nodes[1], 1);
7075 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7076 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7077 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7078 check_added_monitors!(nodes[0], 1);
7080 // Cache one local commitment tx as lastest
7081 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7083 let events = nodes[0].node.get_and_clear_pending_msg_events();
7085 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7086 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7088 _ => panic!("Unexpected event"),
7091 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7092 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7094 _ => panic!("Unexpected event"),
7097 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7098 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7099 if announce_latest {
7100 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7102 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7105 check_closed_broadcast!(nodes[0], true);
7106 check_added_monitors!(nodes[0], 1);
7107 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7109 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7110 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7111 let events = nodes[0].node.get_and_clear_pending_events();
7112 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7113 assert_eq!(events.len(), 2);
7114 let mut first_failed = false;
7115 for event in events {
7117 Event::PaymentPathFailed { payment_hash, .. } => {
7118 if payment_hash == payment_hash_1 {
7119 assert!(!first_failed);
7120 first_failed = true;
7122 assert_eq!(payment_hash, payment_hash_2);
7125 _ => panic!("Unexpected event"),
7131 fn test_failure_delay_dust_htlc_local_commitment() {
7132 do_test_failure_delay_dust_htlc_local_commitment(true);
7133 do_test_failure_delay_dust_htlc_local_commitment(false);
7136 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7137 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7138 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7139 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7140 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7141 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7142 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7144 let chanmon_cfgs = create_chanmon_cfgs(3);
7145 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7146 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7147 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7148 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7150 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7152 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7153 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7155 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7156 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7158 // We revoked bs_commitment_tx
7160 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7161 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7164 let mut timeout_tx = Vec::new();
7166 // We fail dust-HTLC 1 by broadcast of local commitment tx
7167 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7168 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7169 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7170 expect_payment_failed!(nodes[0], dust_hash, true);
7172 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7173 check_closed_broadcast!(nodes[0], true);
7174 check_added_monitors!(nodes[0], 1);
7175 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7176 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7177 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7178 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7179 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7180 mine_transaction(&nodes[0], &timeout_tx[0]);
7181 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7182 expect_payment_failed!(nodes[0], non_dust_hash, true);
7184 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7185 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7186 check_closed_broadcast!(nodes[0], true);
7187 check_added_monitors!(nodes[0], 1);
7188 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7189 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7190 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7191 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7193 expect_payment_failed!(nodes[0], dust_hash, true);
7194 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7195 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7196 mine_transaction(&nodes[0], &timeout_tx[0]);
7197 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7198 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7199 expect_payment_failed!(nodes[0], non_dust_hash, true);
7201 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7203 let events = nodes[0].node.get_and_clear_pending_events();
7204 assert_eq!(events.len(), 2);
7207 Event::PaymentPathFailed { payment_hash, .. } => {
7208 if payment_hash == dust_hash { first = true; }
7209 else { first = false; }
7211 _ => panic!("Unexpected event"),
7214 Event::PaymentPathFailed { payment_hash, .. } => {
7215 if first { assert_eq!(payment_hash, non_dust_hash); }
7216 else { assert_eq!(payment_hash, dust_hash); }
7218 _ => panic!("Unexpected event"),
7225 fn test_sweep_outbound_htlc_failure_update() {
7226 do_test_sweep_outbound_htlc_failure_update(false, true);
7227 do_test_sweep_outbound_htlc_failure_update(false, false);
7228 do_test_sweep_outbound_htlc_failure_update(true, false);
7232 fn test_user_configurable_csv_delay() {
7233 // We test our channel constructors yield errors when we pass them absurd csv delay
7235 let mut low_our_to_self_config = UserConfig::default();
7236 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7237 let mut high_their_to_self_config = UserConfig::default();
7238 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7239 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7240 let chanmon_cfgs = create_chanmon_cfgs(2);
7241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7243 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7245 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7246 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) {
7248 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())); },
7249 _ => panic!("Unexpected event"),
7251 } else { assert!(false) }
7253 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7254 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7255 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7256 open_channel.to_self_delay = 200;
7257 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) {
7259 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())); },
7260 _ => panic!("Unexpected event"),
7262 } else { assert!(false); }
7264 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7265 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7266 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()));
7267 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7268 accept_channel.to_self_delay = 200;
7269 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7271 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7273 &ErrorAction::SendErrorMessage { ref msg } => {
7274 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()));
7275 reason_msg = msg.data.clone();
7279 } else { panic!(); }
7280 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7282 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7283 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7284 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7285 open_channel.to_self_delay = 200;
7286 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) {
7288 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())); },
7289 _ => panic!("Unexpected event"),
7291 } else { assert!(false); }
7295 fn test_data_loss_protect() {
7296 // We want to be sure that :
7297 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7298 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7299 // * we close channel in case of detecting other being fallen behind
7300 // * we are able to claim our own outputs thanks to to_remote being static
7301 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7307 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7308 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7309 // during signing due to revoked tx
7310 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7311 let keys_manager = &chanmon_cfgs[0].keys_manager;
7314 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7315 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7316 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7318 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7320 // Cache node A state before any channel update
7321 let previous_node_state = nodes[0].node.encode();
7322 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7323 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7325 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7326 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7328 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7329 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7331 // Restore node A from previous state
7332 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7333 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7334 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7335 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7336 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7337 persister = test_utils::TestPersister::new();
7338 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7340 let mut channel_monitors = HashMap::new();
7341 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7342 <(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 {
7343 keys_manager: keys_manager,
7344 fee_estimator: &fee_estimator,
7345 chain_monitor: &monitor,
7347 tx_broadcaster: &tx_broadcaster,
7348 default_config: UserConfig::default(),
7352 nodes[0].node = &node_state_0;
7353 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7354 nodes[0].chain_monitor = &monitor;
7355 nodes[0].chain_source = &chain_source;
7357 check_added_monitors!(nodes[0], 1);
7359 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7360 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7362 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7364 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7365 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7366 check_added_monitors!(nodes[0], 1);
7369 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7370 assert_eq!(node_txn.len(), 0);
7373 let mut reestablish_1 = Vec::with_capacity(1);
7374 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7375 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7376 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7377 reestablish_1.push(msg.clone());
7378 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7379 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7381 &ErrorAction::SendErrorMessage { ref msg } => {
7382 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");
7384 _ => panic!("Unexpected event!"),
7387 panic!("Unexpected event")
7391 // Check we close channel detecting A is fallen-behind
7392 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7393 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7394 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7395 check_added_monitors!(nodes[1], 1);
7397 // Check A is able to claim to_remote output
7398 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7399 assert_eq!(node_txn.len(), 1);
7400 check_spends!(node_txn[0], chan.3);
7401 assert_eq!(node_txn[0].output.len(), 2);
7402 mine_transaction(&nodes[0], &node_txn[0]);
7403 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7404 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() });
7405 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7406 assert_eq!(spend_txn.len(), 1);
7407 check_spends!(spend_txn[0], node_txn[0]);
7411 fn test_check_htlc_underpaying() {
7412 // Send payment through A -> B but A is maliciously
7413 // sending a probe payment (i.e less than expected value0
7414 // to B, B should refuse payment.
7416 let chanmon_cfgs = create_chanmon_cfgs(2);
7417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7419 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7421 // Create some initial channels
7422 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7424 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();
7425 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7426 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7427 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7428 check_added_monitors!(nodes[0], 1);
7430 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7431 assert_eq!(events.len(), 1);
7432 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7433 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7434 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7436 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7437 // and then will wait a second random delay before failing the HTLC back:
7438 expect_pending_htlcs_forwardable!(nodes[1]);
7439 expect_pending_htlcs_forwardable!(nodes[1]);
7441 // Node 3 is expecting payment of 100_000 but received 10_000,
7442 // it should fail htlc like we didn't know the preimage.
7443 nodes[1].node.process_pending_htlc_forwards();
7445 let events = nodes[1].node.get_and_clear_pending_msg_events();
7446 assert_eq!(events.len(), 1);
7447 let (update_fail_htlc, commitment_signed) = match events[0] {
7448 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 } } => {
7449 assert!(update_add_htlcs.is_empty());
7450 assert!(update_fulfill_htlcs.is_empty());
7451 assert_eq!(update_fail_htlcs.len(), 1);
7452 assert!(update_fail_malformed_htlcs.is_empty());
7453 assert!(update_fee.is_none());
7454 (update_fail_htlcs[0].clone(), commitment_signed)
7456 _ => panic!("Unexpected event"),
7458 check_added_monitors!(nodes[1], 1);
7460 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7461 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7463 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7464 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7465 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7466 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7470 fn test_announce_disable_channels() {
7471 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7472 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7474 let chanmon_cfgs = create_chanmon_cfgs(2);
7475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7477 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7479 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7480 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7481 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7484 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7485 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7487 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7488 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7489 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7490 assert_eq!(msg_events.len(), 3);
7491 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7492 for e in msg_events {
7494 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7495 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7496 // Check that each channel gets updated exactly once
7497 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7498 panic!("Generated ChannelUpdate for wrong chan!");
7501 _ => panic!("Unexpected event"),
7505 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7506 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7507 assert_eq!(reestablish_1.len(), 3);
7508 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7509 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7510 assert_eq!(reestablish_2.len(), 3);
7512 // Reestablish chan_1
7513 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7514 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7515 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7516 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7517 // Reestablish chan_2
7518 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7519 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7520 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7521 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7522 // Reestablish chan_3
7523 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7524 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7525 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7526 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7528 nodes[0].node.timer_tick_occurred();
7529 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7530 nodes[0].node.timer_tick_occurred();
7531 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7532 assert_eq!(msg_events.len(), 3);
7533 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7534 for e in msg_events {
7536 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7537 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7538 // Check that each channel gets updated exactly once
7539 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7540 panic!("Generated ChannelUpdate for wrong chan!");
7543 _ => panic!("Unexpected event"),
7549 fn test_priv_forwarding_rejection() {
7550 // If we have a private channel with outbound liquidity, and
7551 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7552 // to forward through that channel.
7553 let chanmon_cfgs = create_chanmon_cfgs(3);
7554 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7555 let mut no_announce_cfg = test_default_channel_config();
7556 no_announce_cfg.channel_options.announced_channel = false;
7557 no_announce_cfg.accept_forwards_to_priv_channels = false;
7558 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7559 let persister: test_utils::TestPersister;
7560 let new_chain_monitor: test_utils::TestChainMonitor;
7561 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7562 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7564 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7566 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7567 // not send for private channels.
7568 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7569 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7570 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7571 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7572 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7574 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7575 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7576 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()));
7577 check_added_monitors!(nodes[2], 1);
7579 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()));
7580 check_added_monitors!(nodes[1], 1);
7582 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7583 confirm_transaction_at(&nodes[1], &tx, conf_height);
7584 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7585 confirm_transaction_at(&nodes[2], &tx, conf_height);
7586 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7587 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7588 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()));
7589 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7590 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7591 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7593 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7594 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7595 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7597 // We should always be able to forward through nodes[1] as long as its out through a public
7599 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7601 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7602 // to nodes[2], which should be rejected:
7603 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7604 let route = get_route(&nodes[0].node.get_our_node_id(),
7605 &nodes[0].net_graph_msg_handler.network_graph,
7606 &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None,
7607 &[&RouteHint(vec![RouteHintHop {
7608 src_node_id: nodes[1].node.get_our_node_id(),
7609 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7610 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7611 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7612 htlc_minimum_msat: None,
7613 htlc_maximum_msat: None,
7614 }])], 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7616 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7617 check_added_monitors!(nodes[0], 1);
7618 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7619 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7620 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7622 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7623 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7624 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7625 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7626 assert!(htlc_fail_updates.update_fee.is_none());
7628 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7629 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7630 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7632 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7633 // to true. Sadly there is currently no way to change it at runtime.
7635 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7636 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7638 let nodes_1_serialized = nodes[1].node.encode();
7639 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7640 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7642 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7643 let mut mon_iter = mons.iter();
7644 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7645 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7648 persister = test_utils::TestPersister::new();
7649 let keys_manager = &chanmon_cfgs[1].keys_manager;
7650 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);
7651 nodes[1].chain_monitor = &new_chain_monitor;
7653 let mut monitor_a_read = &monitor_a_serialized.0[..];
7654 let mut monitor_b_read = &monitor_b_serialized.0[..];
7655 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7656 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7657 assert!(monitor_a_read.is_empty());
7658 assert!(monitor_b_read.is_empty());
7660 no_announce_cfg.accept_forwards_to_priv_channels = true;
7662 let mut nodes_1_read = &nodes_1_serialized[..];
7663 let (_, nodes_1_deserialized_tmp) = {
7664 let mut channel_monitors = HashMap::new();
7665 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7666 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7667 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7668 default_config: no_announce_cfg,
7670 fee_estimator: node_cfgs[1].fee_estimator,
7671 chain_monitor: nodes[1].chain_monitor,
7672 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7673 logger: nodes[1].logger,
7677 assert!(nodes_1_read.is_empty());
7678 nodes_1_deserialized = nodes_1_deserialized_tmp;
7680 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7681 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7682 check_added_monitors!(nodes[1], 2);
7683 nodes[1].node = &nodes_1_deserialized;
7685 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7686 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7687 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7688 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7689 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7690 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7691 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7692 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7694 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7695 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7696 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7697 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7698 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7699 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7700 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7701 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7703 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7704 check_added_monitors!(nodes[0], 1);
7705 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7706 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7710 fn test_bump_penalty_txn_on_revoked_commitment() {
7711 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7712 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7714 let chanmon_cfgs = create_chanmon_cfgs(2);
7715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7717 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7719 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7720 let logger = test_utils::TestLogger::new();
7722 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7723 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7724 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();
7725 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7727 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7728 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7729 assert_eq!(revoked_txn[0].output.len(), 4);
7730 assert_eq!(revoked_txn[0].input.len(), 1);
7731 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7732 let revoked_txid = revoked_txn[0].txid();
7734 let mut penalty_sum = 0;
7735 for outp in revoked_txn[0].output.iter() {
7736 if outp.script_pubkey.is_v0_p2wsh() {
7737 penalty_sum += outp.value;
7741 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7742 let header_114 = connect_blocks(&nodes[1], 14);
7744 // Actually revoke tx by claiming a HTLC
7745 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7746 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7747 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7748 check_added_monitors!(nodes[1], 1);
7750 // One or more justice tx should have been broadcast, check it
7754 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7755 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7756 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7757 assert_eq!(node_txn[0].output.len(), 1);
7758 check_spends!(node_txn[0], revoked_txn[0]);
7759 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7760 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7761 penalty_1 = node_txn[0].txid();
7765 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7766 connect_blocks(&nodes[1], 15);
7767 let mut penalty_2 = penalty_1;
7768 let mut feerate_2 = 0;
7770 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7771 assert_eq!(node_txn.len(), 1);
7772 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7773 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7774 assert_eq!(node_txn[0].output.len(), 1);
7775 check_spends!(node_txn[0], revoked_txn[0]);
7776 penalty_2 = node_txn[0].txid();
7777 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7778 assert_ne!(penalty_2, penalty_1);
7779 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7780 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7781 // Verify 25% bump heuristic
7782 assert!(feerate_2 * 100 >= feerate_1 * 125);
7786 assert_ne!(feerate_2, 0);
7788 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7789 connect_blocks(&nodes[1], 1);
7791 let mut feerate_3 = 0;
7793 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7794 assert_eq!(node_txn.len(), 1);
7795 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7796 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7797 assert_eq!(node_txn[0].output.len(), 1);
7798 check_spends!(node_txn[0], revoked_txn[0]);
7799 penalty_3 = node_txn[0].txid();
7800 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7801 assert_ne!(penalty_3, penalty_2);
7802 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7803 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7804 // Verify 25% bump heuristic
7805 assert!(feerate_3 * 100 >= feerate_2 * 125);
7809 assert_ne!(feerate_3, 0);
7811 nodes[1].node.get_and_clear_pending_events();
7812 nodes[1].node.get_and_clear_pending_msg_events();
7816 fn test_bump_penalty_txn_on_revoked_htlcs() {
7817 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7818 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7820 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7821 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7826 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7827 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7828 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7829 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7830 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7831 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7832 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7833 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7835 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7836 assert_eq!(revoked_local_txn[0].input.len(), 1);
7837 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7839 // Revoke local commitment tx
7840 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7842 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7843 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7844 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7845 check_closed_broadcast!(nodes[1], true);
7846 check_added_monitors!(nodes[1], 1);
7847 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7848 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7850 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7851 assert_eq!(revoked_htlc_txn.len(), 3);
7852 check_spends!(revoked_htlc_txn[1], chan.3);
7854 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7855 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7856 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7858 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7859 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7860 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7861 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7863 // Broadcast set of revoked txn on A
7864 let hash_128 = connect_blocks(&nodes[0], 40);
7865 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7866 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7867 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7868 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7869 let events = nodes[0].node.get_and_clear_pending_events();
7870 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7872 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7873 _ => panic!("Unexpected event"),
7879 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7880 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7881 // Verify claim tx are spending revoked HTLC txn
7883 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7884 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7885 // which are included in the same block (they are broadcasted because we scan the
7886 // transactions linearly and generate claims as we go, they likely should be removed in the
7888 assert_eq!(node_txn[0].input.len(), 1);
7889 check_spends!(node_txn[0], revoked_local_txn[0]);
7890 assert_eq!(node_txn[1].input.len(), 1);
7891 check_spends!(node_txn[1], revoked_local_txn[0]);
7892 assert_eq!(node_txn[2].input.len(), 1);
7893 check_spends!(node_txn[2], revoked_local_txn[0]);
7895 // Each of the three justice transactions claim a separate (single) output of the three
7896 // available, which we check here:
7897 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7898 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7899 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7901 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7902 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7904 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7905 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7906 // a remote commitment tx has already been confirmed).
7907 check_spends!(node_txn[3], chan.3);
7909 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7910 // output, checked above).
7911 assert_eq!(node_txn[4].input.len(), 2);
7912 assert_eq!(node_txn[4].output.len(), 1);
7913 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7915 first = node_txn[4].txid();
7916 // Store both feerates for later comparison
7917 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7918 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7919 penalty_txn = vec![node_txn[2].clone()];
7923 // Connect one more block to see if bumped penalty are issued for HTLC txn
7924 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7925 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7926 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7927 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7929 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7930 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7932 check_spends!(node_txn[0], revoked_local_txn[0]);
7933 check_spends!(node_txn[1], revoked_local_txn[0]);
7934 // Note that these are both bogus - they spend outputs already claimed in block 129:
7935 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7936 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7938 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7939 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7945 // Few more blocks to confirm penalty txn
7946 connect_blocks(&nodes[0], 4);
7947 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7948 let header_144 = connect_blocks(&nodes[0], 9);
7950 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7951 assert_eq!(node_txn.len(), 1);
7953 assert_eq!(node_txn[0].input.len(), 2);
7954 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7955 // Verify bumped tx is different and 25% bump heuristic
7956 assert_ne!(first, node_txn[0].txid());
7957 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7958 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7959 assert!(feerate_2 * 100 > feerate_1 * 125);
7960 let txn = vec![node_txn[0].clone()];
7964 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7965 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7966 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7967 connect_blocks(&nodes[0], 20);
7969 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7970 // We verify than no new transaction has been broadcast because previously
7971 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7972 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7973 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7974 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7975 // up bumped justice generation.
7976 assert_eq!(node_txn.len(), 0);
7979 check_closed_broadcast!(nodes[0], true);
7980 check_added_monitors!(nodes[0], 1);
7984 fn test_bump_penalty_txn_on_remote_commitment() {
7985 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7986 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7989 // Provide preimage for one
7990 // Check aggregation
7992 let chanmon_cfgs = create_chanmon_cfgs(2);
7993 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7994 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7995 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7997 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7998 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7999 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8001 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8002 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8003 assert_eq!(remote_txn[0].output.len(), 4);
8004 assert_eq!(remote_txn[0].input.len(), 1);
8005 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8007 // Claim a HTLC without revocation (provide B monitor with preimage)
8008 nodes[1].node.claim_funds(payment_preimage);
8009 mine_transaction(&nodes[1], &remote_txn[0]);
8010 check_added_monitors!(nodes[1], 2);
8011 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8013 // One or more claim tx should have been broadcast, check it
8017 let feerate_timeout;
8018 let feerate_preimage;
8020 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8021 // 9 transactions including:
8022 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8023 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8024 // 2 * HTLC-Success (one RBF bump we'll check later)
8026 assert_eq!(node_txn.len(), 8);
8027 assert_eq!(node_txn[0].input.len(), 1);
8028 assert_eq!(node_txn[6].input.len(), 1);
8029 check_spends!(node_txn[0], remote_txn[0]);
8030 check_spends!(node_txn[6], remote_txn[0]);
8031 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
8032 preimage_bump = node_txn[3].clone();
8034 check_spends!(node_txn[1], chan.3);
8035 check_spends!(node_txn[2], node_txn[1]);
8036 assert_eq!(node_txn[1], node_txn[4]);
8037 assert_eq!(node_txn[2], node_txn[5]);
8039 timeout = node_txn[6].txid();
8040 let index = node_txn[6].input[0].previous_output.vout;
8041 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8042 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8044 preimage = node_txn[0].txid();
8045 let index = node_txn[0].input[0].previous_output.vout;
8046 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8047 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8051 assert_ne!(feerate_timeout, 0);
8052 assert_ne!(feerate_preimage, 0);
8054 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8055 connect_blocks(&nodes[1], 15);
8057 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8058 assert_eq!(node_txn.len(), 1);
8059 assert_eq!(node_txn[0].input.len(), 1);
8060 assert_eq!(preimage_bump.input.len(), 1);
8061 check_spends!(node_txn[0], remote_txn[0]);
8062 check_spends!(preimage_bump, remote_txn[0]);
8064 let index = preimage_bump.input[0].previous_output.vout;
8065 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8066 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8067 assert!(new_feerate * 100 > feerate_timeout * 125);
8068 assert_ne!(timeout, preimage_bump.txid());
8070 let index = node_txn[0].input[0].previous_output.vout;
8071 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8072 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8073 assert!(new_feerate * 100 > feerate_preimage * 125);
8074 assert_ne!(preimage, node_txn[0].txid());
8079 nodes[1].node.get_and_clear_pending_events();
8080 nodes[1].node.get_and_clear_pending_msg_events();
8084 fn test_counterparty_raa_skip_no_crash() {
8085 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8086 // commitment transaction, we would have happily carried on and provided them the next
8087 // commitment transaction based on one RAA forward. This would probably eventually have led to
8088 // channel closure, but it would not have resulted in funds loss. Still, our
8089 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
8090 // check simply that the channel is closed in response to such an RAA, but don't check whether
8091 // we decide to punish our counterparty for revoking their funds (as we don't currently
8093 let chanmon_cfgs = create_chanmon_cfgs(2);
8094 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8095 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8096 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8097 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8099 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8100 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8102 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8104 // Make signer believe we got a counterparty signature, so that it allows the revocation
8105 keys.get_enforcement_state().last_holder_commitment -= 1;
8106 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8108 // Must revoke without gaps
8109 keys.get_enforcement_state().last_holder_commitment -= 1;
8110 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8112 keys.get_enforcement_state().last_holder_commitment -= 1;
8113 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8114 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8116 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8117 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8118 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8119 check_added_monitors!(nodes[1], 1);
8120 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
8124 fn test_bump_txn_sanitize_tracking_maps() {
8125 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8126 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8128 let chanmon_cfgs = create_chanmon_cfgs(2);
8129 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8130 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8131 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8133 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8134 // Lock HTLC in both directions
8135 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8136 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8138 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8139 assert_eq!(revoked_local_txn[0].input.len(), 1);
8140 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8142 // Revoke local commitment tx
8143 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8145 // Broadcast set of revoked txn on A
8146 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8147 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8148 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8150 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8151 check_closed_broadcast!(nodes[0], true);
8152 check_added_monitors!(nodes[0], 1);
8153 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8155 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8156 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8157 check_spends!(node_txn[0], revoked_local_txn[0]);
8158 check_spends!(node_txn[1], revoked_local_txn[0]);
8159 check_spends!(node_txn[2], revoked_local_txn[0]);
8160 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8164 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8165 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8166 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8168 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8169 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8170 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8171 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8177 fn test_override_channel_config() {
8178 let chanmon_cfgs = create_chanmon_cfgs(2);
8179 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8180 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8181 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8183 // Node0 initiates a channel to node1 using the override config.
8184 let mut override_config = UserConfig::default();
8185 override_config.own_channel_config.our_to_self_delay = 200;
8187 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8189 // Assert the channel created by node0 is using the override config.
8190 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8191 assert_eq!(res.channel_flags, 0);
8192 assert_eq!(res.to_self_delay, 200);
8196 fn test_override_0msat_htlc_minimum() {
8197 let mut zero_config = UserConfig::default();
8198 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8199 let chanmon_cfgs = create_chanmon_cfgs(2);
8200 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8201 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8202 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8204 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8205 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8206 assert_eq!(res.htlc_minimum_msat, 1);
8208 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8209 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8210 assert_eq!(res.htlc_minimum_msat, 1);
8214 fn test_simple_mpp() {
8215 // Simple test of sending a multi-path payment.
8216 let chanmon_cfgs = create_chanmon_cfgs(4);
8217 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8218 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8219 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8221 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8222 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8223 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8224 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8225 let logger = test_utils::TestLogger::new();
8227 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8228 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8229 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();
8230 let path = route.paths[0].clone();
8231 route.paths.push(path);
8232 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8233 route.paths[0][0].short_channel_id = chan_1_id;
8234 route.paths[0][1].short_channel_id = chan_3_id;
8235 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8236 route.paths[1][0].short_channel_id = chan_2_id;
8237 route.paths[1][1].short_channel_id = chan_4_id;
8238 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8239 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8243 fn test_preimage_storage() {
8244 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8245 let chanmon_cfgs = create_chanmon_cfgs(2);
8246 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8247 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8248 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8250 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8253 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8255 let logger = test_utils::TestLogger::new();
8256 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8257 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();
8258 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8259 check_added_monitors!(nodes[0], 1);
8260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8261 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8262 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8263 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8265 // Note that after leaving the above scope we have no knowledge of any arguments or return
8266 // values from previous calls.
8267 expect_pending_htlcs_forwardable!(nodes[1]);
8268 let events = nodes[1].node.get_and_clear_pending_events();
8269 assert_eq!(events.len(), 1);
8271 Event::PaymentReceived { ref purpose, .. } => {
8273 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8274 assert_eq!(*user_payment_id, 42);
8275 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8277 _ => panic!("expected PaymentPurpose::InvoicePayment")
8280 _ => panic!("Unexpected event"),
8285 fn test_secret_timeout() {
8286 // Simple test of payment secret storage time outs
8287 let chanmon_cfgs = create_chanmon_cfgs(2);
8288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8290 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8292 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8294 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8296 // We should fail to register the same payment hash twice, at least until we've connected a
8297 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8298 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8299 assert_eq!(err, "Duplicate payment hash");
8300 } else { panic!(); }
8302 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8304 header: BlockHeader {
8306 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8307 merkle_root: Default::default(),
8308 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8312 connect_block(&nodes[1], &block);
8313 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8314 assert_eq!(err, "Duplicate payment hash");
8315 } else { panic!(); }
8317 // If we then connect the second block, we should be able to register the same payment hash
8318 // again with a different user_payment_id (this time getting a new payment secret).
8319 block.header.prev_blockhash = block.header.block_hash();
8320 block.header.time += 1;
8321 connect_block(&nodes[1], &block);
8322 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8323 assert_ne!(payment_secret_1, our_payment_secret);
8326 let logger = test_utils::TestLogger::new();
8327 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8328 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();
8329 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8330 check_added_monitors!(nodes[0], 1);
8331 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8332 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8333 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8334 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8336 // Note that after leaving the above scope we have no knowledge of any arguments or return
8337 // values from previous calls.
8338 expect_pending_htlcs_forwardable!(nodes[1]);
8339 let events = nodes[1].node.get_and_clear_pending_events();
8340 assert_eq!(events.len(), 1);
8342 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, user_payment_id }, .. } => {
8343 assert!(payment_preimage.is_none());
8344 assert_eq!(user_payment_id, 42);
8345 assert_eq!(payment_secret, our_payment_secret);
8346 // We don't actually have the payment preimage with which to claim this payment!
8348 _ => panic!("Unexpected event"),
8353 fn test_bad_secret_hash() {
8354 // Simple test of unregistered payment hash/invalid payment secret handling
8355 let chanmon_cfgs = create_chanmon_cfgs(2);
8356 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8357 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8358 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8360 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8362 let random_payment_hash = PaymentHash([42; 32]);
8363 let random_payment_secret = PaymentSecret([43; 32]);
8364 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8366 let logger = test_utils::TestLogger::new();
8367 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8368 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();
8370 // All the below cases should end up being handled exactly identically, so we macro the
8371 // resulting events.
8372 macro_rules! handle_unknown_invalid_payment_data {
8374 check_added_monitors!(nodes[0], 1);
8375 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8376 let payment_event = SendEvent::from_event(events.pop().unwrap());
8377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8378 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8380 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8381 // again to process the pending backwards-failure of the HTLC
8382 expect_pending_htlcs_forwardable!(nodes[1]);
8383 expect_pending_htlcs_forwardable!(nodes[1]);
8384 check_added_monitors!(nodes[1], 1);
8386 // We should fail the payment back
8387 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8388 match events.pop().unwrap() {
8389 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8390 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8391 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8393 _ => panic!("Unexpected event"),
8398 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8399 // Error data is the HTLC value (100,000) and current block height
8400 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8402 // Send a payment with the right payment hash but the wrong payment secret
8403 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8404 handle_unknown_invalid_payment_data!();
8405 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8407 // Send a payment with a random payment hash, but the right payment secret
8408 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8409 handle_unknown_invalid_payment_data!();
8410 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8412 // Send a payment with a random payment hash and random payment secret
8413 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8414 handle_unknown_invalid_payment_data!();
8415 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8419 fn test_update_err_monitor_lockdown() {
8420 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8421 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8422 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8424 // This scenario may happen in a watchtower setup, where watchtower process a block height
8425 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8426 // commitment at same time.
8428 let chanmon_cfgs = create_chanmon_cfgs(2);
8429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8431 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8433 // Create some initial channel
8434 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8435 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8437 // Rebalance the network to generate htlc in the two directions
8438 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8440 // Route a HTLC from node 0 to node 1 (but don't settle)
8441 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8443 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8444 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8445 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8446 let persister = test_utils::TestPersister::new();
8448 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8449 let monitor = monitors.get(&outpoint).unwrap();
8450 let mut w = test_utils::TestVecWriter(Vec::new());
8451 monitor.write(&mut w).unwrap();
8452 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8453 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8454 assert!(new_monitor == *monitor);
8455 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);
8456 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8459 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8460 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8461 // transaction lock time requirements here.
8462 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8463 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8465 // Try to update ChannelMonitor
8466 assert!(nodes[1].node.claim_funds(preimage));
8467 check_added_monitors!(nodes[1], 1);
8468 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8469 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8470 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8471 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8472 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8473 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8474 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8475 } else { assert!(false); }
8476 } else { assert!(false); };
8477 // Our local monitor is in-sync and hasn't processed yet timeout
8478 check_added_monitors!(nodes[0], 1);
8479 let events = nodes[0].node.get_and_clear_pending_events();
8480 assert_eq!(events.len(), 1);
8484 fn test_concurrent_monitor_claim() {
8485 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8486 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8487 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8488 // state N+1 confirms. Alice claims output from state N+1.
8490 let chanmon_cfgs = create_chanmon_cfgs(2);
8491 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8492 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8493 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8495 // Create some initial channel
8496 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8497 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8499 // Rebalance the network to generate htlc in the two directions
8500 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8502 // Route a HTLC from node 0 to node 1 (but don't settle)
8503 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8505 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8506 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8507 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8508 let persister = test_utils::TestPersister::new();
8509 let watchtower_alice = {
8510 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8511 let monitor = monitors.get(&outpoint).unwrap();
8512 let mut w = test_utils::TestVecWriter(Vec::new());
8513 monitor.write(&mut w).unwrap();
8514 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8515 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8516 assert!(new_monitor == *monitor);
8517 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);
8518 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8521 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8522 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8523 // transaction lock time requirements here.
8524 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8525 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8527 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8529 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8530 assert_eq!(txn.len(), 2);
8534 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8535 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8536 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8537 let persister = test_utils::TestPersister::new();
8538 let watchtower_bob = {
8539 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8540 let monitor = monitors.get(&outpoint).unwrap();
8541 let mut w = test_utils::TestVecWriter(Vec::new());
8542 monitor.write(&mut w).unwrap();
8543 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8544 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8545 assert!(new_monitor == *monitor);
8546 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);
8547 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8550 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8551 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8553 // Route another payment to generate another update with still previous HTLC pending
8554 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8556 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8557 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();
8558 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8560 check_added_monitors!(nodes[1], 1);
8562 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8563 assert_eq!(updates.update_add_htlcs.len(), 1);
8564 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8565 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8566 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8567 // Watchtower Alice should already have seen the block and reject the update
8568 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8569 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8570 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8571 } else { assert!(false); }
8572 } else { assert!(false); };
8573 // Our local monitor is in-sync and hasn't processed yet timeout
8574 check_added_monitors!(nodes[0], 1);
8576 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
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 + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8580 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8583 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8584 assert_eq!(txn.len(), 2);
8585 bob_state_y = txn[0].clone();
8589 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8590 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8591 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);
8593 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8594 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8595 // the onchain detection of the HTLC output
8596 assert_eq!(htlc_txn.len(), 2);
8597 check_spends!(htlc_txn[0], bob_state_y);
8598 check_spends!(htlc_txn[1], bob_state_y);
8603 fn test_pre_lockin_no_chan_closed_update() {
8604 // Test that if a peer closes a channel in response to a funding_created message we don't
8605 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8608 // Doing so would imply a channel monitor update before the initial channel monitor
8609 // registration, violating our API guarantees.
8611 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8612 // then opening a second channel with the same funding output as the first (which is not
8613 // rejected because the first channel does not exist in the ChannelManager) and closing it
8614 // before receiving funding_signed.
8615 let chanmon_cfgs = create_chanmon_cfgs(2);
8616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8618 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8620 // Create an initial channel
8621 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8622 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8623 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8624 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8625 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8627 // Move the first channel through the funding flow...
8628 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8630 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8631 check_added_monitors!(nodes[0], 0);
8633 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8634 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8635 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8636 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8637 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() });
8641 fn test_htlc_no_detection() {
8642 // This test is a mutation to underscore the detection logic bug we had
8643 // before #653. HTLC value routed is above the remaining balance, thus
8644 // inverting HTLC and `to_remote` output. HTLC will come second and
8645 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8646 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8647 // outputs order detection for correct spending children filtring.
8649 let chanmon_cfgs = create_chanmon_cfgs(2);
8650 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8651 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8652 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8654 // Create some initial channels
8655 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8657 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8658 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8659 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8660 assert_eq!(local_txn[0].input.len(), 1);
8661 assert_eq!(local_txn[0].output.len(), 3);
8662 check_spends!(local_txn[0], chan_1.3);
8664 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8665 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8666 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8667 // We deliberately connect the local tx twice as this should provoke a failure calling
8668 // this test before #653 fix.
8669 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);
8670 check_closed_broadcast!(nodes[0], true);
8671 check_added_monitors!(nodes[0], 1);
8672 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8673 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8675 let htlc_timeout = {
8676 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8677 assert_eq!(node_txn[1].input.len(), 1);
8678 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8679 check_spends!(node_txn[1], local_txn[0]);
8683 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8684 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8685 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8686 expect_payment_failed!(nodes[0], our_payment_hash, true);
8689 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8690 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8691 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8692 // Carol, Alice would be the upstream node, and Carol the downstream.)
8694 // Steps of the test:
8695 // 1) Alice sends a HTLC to Carol through Bob.
8696 // 2) Carol doesn't settle the HTLC.
8697 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8698 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8699 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8700 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8701 // 5) Carol release the preimage to Bob off-chain.
8702 // 6) Bob claims the offered output on the broadcasted commitment.
8703 let chanmon_cfgs = create_chanmon_cfgs(3);
8704 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8705 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8706 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8708 // Create some initial channels
8709 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8710 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8712 // Steps (1) and (2):
8713 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8714 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8716 // Check that Alice's commitment transaction now contains an output for this HTLC.
8717 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8718 check_spends!(alice_txn[0], chan_ab.3);
8719 assert_eq!(alice_txn[0].output.len(), 2);
8720 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8721 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8722 assert_eq!(alice_txn.len(), 2);
8724 // Steps (3) and (4):
8725 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8726 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8727 let mut force_closing_node = 0; // Alice force-closes
8728 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8729 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8730 check_closed_broadcast!(nodes[force_closing_node], true);
8731 check_added_monitors!(nodes[force_closing_node], 1);
8732 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8733 if go_onchain_before_fulfill {
8734 let txn_to_broadcast = match broadcast_alice {
8735 true => alice_txn.clone(),
8736 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8738 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8739 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8740 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8741 if broadcast_alice {
8742 check_closed_broadcast!(nodes[1], true);
8743 check_added_monitors!(nodes[1], 1);
8744 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8746 assert_eq!(bob_txn.len(), 1);
8747 check_spends!(bob_txn[0], chan_ab.3);
8751 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8752 // process of removing the HTLC from their commitment transactions.
8753 assert!(nodes[2].node.claim_funds(payment_preimage));
8754 check_added_monitors!(nodes[2], 1);
8755 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8756 assert!(carol_updates.update_add_htlcs.is_empty());
8757 assert!(carol_updates.update_fail_htlcs.is_empty());
8758 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8759 assert!(carol_updates.update_fee.is_none());
8760 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8762 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8763 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8764 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8765 if !go_onchain_before_fulfill && broadcast_alice {
8766 let events = nodes[1].node.get_and_clear_pending_msg_events();
8767 assert_eq!(events.len(), 1);
8769 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8770 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8772 _ => panic!("Unexpected event"),
8775 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8776 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8777 // Carol<->Bob's updated commitment transaction info.
8778 check_added_monitors!(nodes[1], 2);
8780 let events = nodes[1].node.get_and_clear_pending_msg_events();
8781 assert_eq!(events.len(), 2);
8782 let bob_revocation = match events[0] {
8783 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8784 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8787 _ => panic!("Unexpected event"),
8789 let bob_updates = match events[1] {
8790 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8791 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8794 _ => panic!("Unexpected event"),
8797 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8798 check_added_monitors!(nodes[2], 1);
8799 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8800 check_added_monitors!(nodes[2], 1);
8802 let events = nodes[2].node.get_and_clear_pending_msg_events();
8803 assert_eq!(events.len(), 1);
8804 let carol_revocation = match events[0] {
8805 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8806 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8809 _ => panic!("Unexpected event"),
8811 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8812 check_added_monitors!(nodes[1], 1);
8814 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8815 // here's where we put said channel's commitment tx on-chain.
8816 let mut txn_to_broadcast = alice_txn.clone();
8817 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8818 if !go_onchain_before_fulfill {
8819 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8820 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8821 // If Bob was the one to force-close, he will have already passed these checks earlier.
8822 if broadcast_alice {
8823 check_closed_broadcast!(nodes[1], true);
8824 check_added_monitors!(nodes[1], 1);
8825 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8827 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8828 if broadcast_alice {
8829 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8830 // new block being connected. The ChannelManager being notified triggers a monitor update,
8831 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8832 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8834 assert_eq!(bob_txn.len(), 3);
8835 check_spends!(bob_txn[1], chan_ab.3);
8837 assert_eq!(bob_txn.len(), 2);
8838 check_spends!(bob_txn[0], chan_ab.3);
8843 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8844 // broadcasted commitment transaction.
8846 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8847 if go_onchain_before_fulfill {
8848 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8849 assert_eq!(bob_txn.len(), 2);
8851 let script_weight = match broadcast_alice {
8852 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8853 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8855 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8856 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8857 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8858 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8859 if broadcast_alice && !go_onchain_before_fulfill {
8860 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8861 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8863 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8864 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8870 fn test_onchain_htlc_settlement_after_close() {
8871 do_test_onchain_htlc_settlement_after_close(true, true);
8872 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8873 do_test_onchain_htlc_settlement_after_close(true, false);
8874 do_test_onchain_htlc_settlement_after_close(false, false);
8878 fn test_duplicate_chan_id() {
8879 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8880 // already open we reject it and keep the old channel.
8882 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8883 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8884 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8885 // updating logic for the existing channel.
8886 let chanmon_cfgs = create_chanmon_cfgs(2);
8887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8889 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8891 // Create an initial channel
8892 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8893 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8894 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8895 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()));
8897 // Try to create a second channel with the same temporary_channel_id as the first and check
8898 // that it is rejected.
8899 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8901 let events = nodes[1].node.get_and_clear_pending_msg_events();
8902 assert_eq!(events.len(), 1);
8904 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8905 // Technically, at this point, nodes[1] would be justified in thinking both the
8906 // first (valid) and second (invalid) channels are closed, given they both have
8907 // the same non-temporary channel_id. However, currently we do not, so we just
8908 // move forward with it.
8909 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8910 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8912 _ => panic!("Unexpected event"),
8916 // Move the first channel through the funding flow...
8917 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8919 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8920 check_added_monitors!(nodes[0], 0);
8922 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8923 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8925 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8926 assert_eq!(added_monitors.len(), 1);
8927 assert_eq!(added_monitors[0].0, funding_output);
8928 added_monitors.clear();
8930 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8932 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8933 let channel_id = funding_outpoint.to_channel_id();
8935 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8938 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8939 // Technically this is allowed by the spec, but we don't support it and there's little reason
8940 // to. Still, it shouldn't cause any other issues.
8941 open_chan_msg.temporary_channel_id = channel_id;
8942 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8944 let events = nodes[1].node.get_and_clear_pending_msg_events();
8945 assert_eq!(events.len(), 1);
8947 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8948 // Technically, at this point, nodes[1] would be justified in thinking both
8949 // channels are closed, but currently we do not, so we just move forward with it.
8950 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8951 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8953 _ => panic!("Unexpected event"),
8957 // Now try to create a second channel which has a duplicate funding output.
8958 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8959 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8960 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8961 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()));
8962 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8964 let funding_created = {
8965 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8966 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8967 let logger = test_utils::TestLogger::new();
8968 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8970 check_added_monitors!(nodes[0], 0);
8971 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8972 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8973 // still needs to be cleared here.
8974 check_added_monitors!(nodes[1], 1);
8976 // ...still, nodes[1] will reject the duplicate channel.
8978 let events = nodes[1].node.get_and_clear_pending_msg_events();
8979 assert_eq!(events.len(), 1);
8981 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8982 // Technically, at this point, nodes[1] would be justified in thinking both
8983 // channels are closed, but currently we do not, so we just move forward with it.
8984 assert_eq!(msg.channel_id, channel_id);
8985 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8987 _ => panic!("Unexpected event"),
8991 // finally, finish creating the original channel and send a payment over it to make sure
8992 // everything is functional.
8993 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8995 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8996 assert_eq!(added_monitors.len(), 1);
8997 assert_eq!(added_monitors[0].0, funding_output);
8998 added_monitors.clear();
9001 let events_4 = nodes[0].node.get_and_clear_pending_events();
9002 assert_eq!(events_4.len(), 0);
9003 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9004 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9006 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9007 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9008 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9009 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9013 fn test_error_chans_closed() {
9014 // Test that we properly handle error messages, closing appropriate channels.
9016 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9017 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9018 // we can test various edge cases around it to ensure we don't regress.
9019 let chanmon_cfgs = create_chanmon_cfgs(3);
9020 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9021 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9022 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9024 // Create some initial channels
9025 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9026 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9027 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9029 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9030 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9031 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9033 // Closing a channel from a different peer has no effect
9034 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9035 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9037 // Closing one channel doesn't impact others
9038 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9039 check_added_monitors!(nodes[0], 1);
9040 check_closed_broadcast!(nodes[0], false);
9041 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9042 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9043 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9044 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);
9045 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);
9047 // A null channel ID should close all channels
9048 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9049 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9050 check_added_monitors!(nodes[0], 2);
9051 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
9052 let events = nodes[0].node.get_and_clear_pending_msg_events();
9053 assert_eq!(events.len(), 2);
9055 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9056 assert_eq!(msg.contents.flags & 2, 2);
9058 _ => panic!("Unexpected event"),
9061 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9062 assert_eq!(msg.contents.flags & 2, 2);
9064 _ => panic!("Unexpected event"),
9066 // Note that at this point users of a standard PeerHandler will end up calling
9067 // peer_disconnected with no_connection_possible set to false, duplicating the
9068 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9069 // users with their own peer handling logic. We duplicate the call here, however.
9070 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9071 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9073 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9074 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9075 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9079 fn test_invalid_funding_tx() {
9080 // Test that we properly handle invalid funding transactions sent to us from a peer.
9082 // Previously, all other major lightning implementations had failed to properly sanitize
9083 // funding transactions from their counterparties, leading to a multi-implementation critical
9084 // security vulnerability (though we always sanitized properly, we've previously had
9085 // un-released crashes in the sanitization process).
9086 let chanmon_cfgs = create_chanmon_cfgs(2);
9087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9089 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9091 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9092 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()));
9093 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()));
9095 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9096 for output in tx.output.iter_mut() {
9097 // Make the confirmed funding transaction have a bogus script_pubkey
9098 output.script_pubkey = bitcoin::Script::new();
9101 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9102 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()));
9103 check_added_monitors!(nodes[1], 1);
9105 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()));
9106 check_added_monitors!(nodes[0], 1);
9108 let events_1 = nodes[0].node.get_and_clear_pending_events();
9109 assert_eq!(events_1.len(), 0);
9111 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9112 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9113 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9115 confirm_transaction_at(&nodes[1], &tx, 1);
9116 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
9117 check_added_monitors!(nodes[1], 1);
9118 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9119 assert_eq!(events_2.len(), 1);
9120 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9121 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9122 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9123 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9124 } else { panic!(); }
9125 } else { panic!(); }
9126 assert_eq!(nodes[1].node.list_channels().len(), 0);
9129 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9130 // In the first version of the chain::Confirm interface, after a refactor was made to not
9131 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9132 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9133 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9134 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9135 // spending transaction until height N+1 (or greater). This was due to the way
9136 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9137 // spending transaction at the height the input transaction was confirmed at, not whether we
9138 // should broadcast a spending transaction at the current height.
9139 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9140 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9141 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9142 // until we learned about an additional block.
9144 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9145 // aren't broadcasting transactions too early (ie not broadcasting them at all).
9146 let chanmon_cfgs = create_chanmon_cfgs(3);
9147 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9148 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9149 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9150 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9152 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9153 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9154 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9155 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
9156 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9158 nodes[1].node.force_close_channel(&channel_id).unwrap();
9159 check_closed_broadcast!(nodes[1], true);
9160 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
9161 check_added_monitors!(nodes[1], 1);
9162 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9163 assert_eq!(node_txn.len(), 1);
9165 let conf_height = nodes[1].best_block_info().1;
9166 if !test_height_before_timelock {
9167 connect_blocks(&nodes[1], 24 * 6);
9169 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9170 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9171 if test_height_before_timelock {
9172 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9173 // generate any events or broadcast any transactions
9174 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9175 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9177 // We should broadcast an HTLC transaction spending our funding transaction first
9178 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9179 assert_eq!(spending_txn.len(), 2);
9180 assert_eq!(spending_txn[0], node_txn[0]);
9181 check_spends!(spending_txn[1], node_txn[0]);
9182 // We should also generate a SpendableOutputs event with the to_self output (as its
9184 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9185 assert_eq!(descriptor_spend_txn.len(), 1);
9187 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9188 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9189 // additional block built on top of the current chain.
9190 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9191 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9192 expect_pending_htlcs_forwardable!(nodes[1]);
9193 check_added_monitors!(nodes[1], 1);
9195 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9196 assert!(updates.update_add_htlcs.is_empty());
9197 assert!(updates.update_fulfill_htlcs.is_empty());
9198 assert_eq!(updates.update_fail_htlcs.len(), 1);
9199 assert!(updates.update_fail_malformed_htlcs.is_empty());
9200 assert!(updates.update_fee.is_none());
9201 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9202 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9203 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9208 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9209 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9210 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9214 fn test_keysend_payments_to_public_node() {
9215 let chanmon_cfgs = create_chanmon_cfgs(2);
9216 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9217 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9218 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9220 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9221 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9222 let payer_pubkey = nodes[0].node.get_our_node_id();
9223 let payee_pubkey = nodes[1].node.get_our_node_id();
9224 let route = get_route(&payer_pubkey, network_graph, &payee_pubkey, None,
9225 None, &vec![], 10000, 40,
9226 nodes[0].logger).unwrap();
9228 let test_preimage = PaymentPreimage([42; 32]);
9229 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9230 check_added_monitors!(nodes[0], 1);
9231 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9232 assert_eq!(events.len(), 1);
9233 let event = events.pop().unwrap();
9234 let path = vec![&nodes[1]];
9235 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9236 claim_payment(&nodes[0], &path, test_preimage);
9240 fn test_keysend_payments_to_private_node() {
9241 let chanmon_cfgs = create_chanmon_cfgs(2);
9242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9244 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9246 let payer_pubkey = nodes[0].node.get_our_node_id();
9247 let payee_pubkey = nodes[1].node.get_our_node_id();
9248 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9249 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9251 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9252 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9253 let first_hops = nodes[0].node.list_usable_channels();
9254 let route = get_keysend_route(&payer_pubkey, &network_graph, &payee_pubkey,
9255 Some(&first_hops.iter().collect::<Vec<_>>()), &vec![], 10000, 40,
9256 nodes[0].logger).unwrap();
9258 let test_preimage = PaymentPreimage([42; 32]);
9259 let payment_hash = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9260 check_added_monitors!(nodes[0], 1);
9261 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9262 assert_eq!(events.len(), 1);
9263 let event = events.pop().unwrap();
9264 let path = vec![&nodes[1]];
9265 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9266 claim_payment(&nodes[0], &path, test_preimage);