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, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, MIN_AFFORDABLE_HTLC_COUNT};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::{HTLC_SUCCESS_TX_WEIGHT, HTLC_TIMEOUT_TX_WEIGHT, HTLCOutputInCommitment};
26 use routing::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Payee, Route, RouteHop, RouteHint, RouteHintHop, RouteParameters, find_route, get_route};
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::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());
131 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
135 // send (1) commitment_signed -.
136 // <- update_add_htlc/commitment_signed
137 // send (2) RAA (awaiting remote revoke) -.
138 // (1) commitment_signed is delivered ->
139 // .- send (3) RAA (awaiting remote revoke)
140 // (2) RAA is delivered ->
141 // .- send (4) commitment_signed
142 // <- (3) RAA is delivered
143 // send (5) commitment_signed -.
144 // <- (4) commitment_signed is delivered
146 // (5) commitment_signed is delivered ->
148 // (6) RAA is delivered ->
150 // First nodes[0] generates an update_fee
152 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
155 nodes[0].node.timer_tick_occurred();
156 check_added_monitors!(nodes[0], 1);
158 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events_0.len(), 1);
160 let (update_msg, commitment_signed) = match events_0[0] { // (1)
161 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162 (update_fee.as_ref(), commitment_signed)
164 _ => panic!("Unexpected event"),
167 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
171 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
172 check_added_monitors!(nodes[1], 1);
174 let payment_event = {
175 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
176 assert_eq!(events_1.len(), 1);
177 SendEvent::from_event(events_1.remove(0))
179 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
180 assert_eq!(payment_event.msgs.len(), 1);
182 // ...now when the messages get delivered everyone should be happy
183 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
185 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
186 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
187 check_added_monitors!(nodes[0], 1);
189 // deliver(1), generate (3):
190 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
191 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
192 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
193 check_added_monitors!(nodes[1], 1);
195 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
196 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
197 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
198 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
199 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fee.is_none()); // (4)
202 check_added_monitors!(nodes[1], 1);
204 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
205 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
206 assert!(as_update.update_add_htlcs.is_empty()); // (5)
207 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
208 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fee.is_none()); // (5)
211 check_added_monitors!(nodes[0], 1);
213 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
214 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
215 // only (6) so get_event_msg's assert(len == 1) passes
216 check_added_monitors!(nodes[0], 1);
218 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
219 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
220 check_added_monitors!(nodes[1], 1);
222 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
223 check_added_monitors!(nodes[0], 1);
225 let events_2 = nodes[0].node.get_and_clear_pending_events();
226 assert_eq!(events_2.len(), 1);
228 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
229 _ => panic!("Unexpected event"),
232 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
233 check_added_monitors!(nodes[1], 1);
237 fn test_update_fee_unordered_raa() {
238 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
239 // crash in an earlier version of the update_fee patch)
240 let chanmon_cfgs = create_chanmon_cfgs(2);
241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
243 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
244 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
249 // First nodes[0] generates an update_fee
251 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
254 nodes[0].node.timer_tick_occurred();
255 check_added_monitors!(nodes[0], 1);
257 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258 assert_eq!(events_0.len(), 1);
259 let update_msg = match events_0[0] { // (1)
260 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
263 _ => panic!("Unexpected event"),
266 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
268 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
270 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
271 check_added_monitors!(nodes[1], 1);
273 let payment_event = {
274 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275 assert_eq!(events_1.len(), 1);
276 SendEvent::from_event(events_1.remove(0))
278 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279 assert_eq!(payment_event.msgs.len(), 1);
281 // ...now when the messages get delivered everyone should be happy
282 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286 check_added_monitors!(nodes[0], 1);
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289 check_added_monitors!(nodes[1], 1);
291 // We can't continue, sadly, because our (1) now has a bogus signature
295 fn test_multi_flight_update_fee() {
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
303 // update_fee/commitment_signed ->
304 // .- send (1) RAA and (2) commitment_signed
305 // update_fee (never committed) ->
307 // We have to manually generate the above update_fee, it is allowed by the protocol but we
308 // don't track which updates correspond to which revoke_and_ack responses so we're in
309 // AwaitingRAA mode and will not generate the update_fee yet.
310 // <- (1) RAA delivered
311 // (3) is generated and send (4) CS -.
312 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
313 // know the per_commitment_point to use for it.
314 // <- (2) commitment_signed delivered
316 // B should send no response here
317 // (4) commitment_signed delivered ->
318 // <- RAA/commitment_signed delivered
321 // First nodes[0] generates an update_fee
324 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
325 initial_feerate = *feerate_lock;
326 *feerate_lock = initial_feerate + 20;
328 nodes[0].node.timer_tick_occurred();
329 check_added_monitors!(nodes[0], 1);
331 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
332 assert_eq!(events_0.len(), 1);
333 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
334 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
335 (update_fee.as_ref().unwrap(), commitment_signed)
337 _ => panic!("Unexpected event"),
340 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
341 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
342 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
343 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
344 check_added_monitors!(nodes[1], 1);
346 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
349 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
350 *feerate_lock = initial_feerate + 40;
352 nodes[0].node.timer_tick_occurred();
353 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356 // Create the (3) update_fee message that nodes[0] will generate before it does...
357 let mut update_msg_2 = msgs::UpdateFee {
358 channel_id: update_msg_1.channel_id.clone(),
359 feerate_per_kw: (initial_feerate + 30) as u32,
362 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
364 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
366 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
368 // Deliver (1), generating (3) and (4)
369 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
370 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
371 check_added_monitors!(nodes[0], 1);
372 assert!(as_second_update.update_add_htlcs.is_empty());
373 assert!(as_second_update.update_fulfill_htlcs.is_empty());
374 assert!(as_second_update.update_fail_htlcs.is_empty());
375 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
376 // Check that the update_fee newly generated matches what we delivered:
377 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
378 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
380 // Deliver (2) commitment_signed
381 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
382 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383 check_added_monitors!(nodes[0], 1);
384 // No commitment_signed so get_event_msg's assert(len == 1) passes
386 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
387 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388 check_added_monitors!(nodes[1], 1);
391 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
392 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
393 check_added_monitors!(nodes[1], 1);
395 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
396 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
397 check_added_monitors!(nodes[0], 1);
399 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
400 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
401 // No commitment_signed so get_event_msg's assert(len == 1) passes
402 check_added_monitors!(nodes[0], 1);
404 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
405 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
406 check_added_monitors!(nodes[1], 1);
409 fn do_test_1_conf_open(connect_style: ConnectStyle) {
410 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
411 // tests that we properly send one in that case.
412 let mut alice_config = UserConfig::default();
413 alice_config.own_channel_config.minimum_depth = 1;
414 alice_config.channel_options.announced_channel = true;
415 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
416 let mut bob_config = UserConfig::default();
417 bob_config.own_channel_config.minimum_depth = 1;
418 bob_config.channel_options.announced_channel = true;
419 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
420 let chanmon_cfgs = create_chanmon_cfgs(2);
421 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
422 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
423 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
424 *nodes[0].connect_style.borrow_mut() = connect_style;
426 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
427 mine_transaction(&nodes[1], &tx);
428 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()));
430 mine_transaction(&nodes[0], &tx);
431 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
432 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
435 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
436 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
437 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
441 fn test_1_conf_open() {
442 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
443 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
444 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
447 fn do_test_sanity_on_in_flight_opens(steps: u8) {
448 // Previously, we had issues deserializing channels when we hadn't connected the first block
449 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
450 // serialization round-trips and simply do steps towards opening a channel and then drop the
453 let chanmon_cfgs = create_chanmon_cfgs(2);
454 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
455 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
456 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
458 if steps & 0b1000_0000 != 0{
460 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
463 connect_block(&nodes[0], &block);
464 connect_block(&nodes[1], &block);
467 if steps & 0x0f == 0 { return; }
468 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
469 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
471 if steps & 0x0f == 1 { return; }
472 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
473 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
475 if steps & 0x0f == 2 { return; }
476 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
478 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
480 if steps & 0x0f == 3 { return; }
481 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
482 check_added_monitors!(nodes[0], 0);
483 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
485 if steps & 0x0f == 4 { return; }
486 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
488 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
489 assert_eq!(added_monitors.len(), 1);
490 assert_eq!(added_monitors[0].0, funding_output);
491 added_monitors.clear();
493 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
495 if steps & 0x0f == 5 { return; }
496 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
498 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
499 assert_eq!(added_monitors.len(), 1);
500 assert_eq!(added_monitors[0].0, funding_output);
501 added_monitors.clear();
504 let events_4 = nodes[0].node.get_and_clear_pending_events();
505 assert_eq!(events_4.len(), 0);
507 if steps & 0x0f == 6 { return; }
508 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
510 if steps & 0x0f == 7 { return; }
511 confirm_transaction_at(&nodes[0], &tx, 2);
512 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
513 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
517 fn test_sanity_on_in_flight_opens() {
518 do_test_sanity_on_in_flight_opens(0);
519 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(1);
521 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(2);
523 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(3);
525 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(4);
527 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
528 do_test_sanity_on_in_flight_opens(5);
529 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
530 do_test_sanity_on_in_flight_opens(6);
531 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
532 do_test_sanity_on_in_flight_opens(7);
533 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
534 do_test_sanity_on_in_flight_opens(8);
535 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
539 fn test_update_fee_vanilla() {
540 let chanmon_cfgs = create_chanmon_cfgs(2);
541 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
542 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
543 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
544 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
547 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
550 nodes[0].node.timer_tick_occurred();
551 check_added_monitors!(nodes[0], 1);
553 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
554 assert_eq!(events_0.len(), 1);
555 let (update_msg, commitment_signed) = match events_0[0] {
556 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 } } => {
557 (update_fee.as_ref(), commitment_signed)
559 _ => panic!("Unexpected event"),
561 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
563 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
564 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
565 check_added_monitors!(nodes[1], 1);
567 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
568 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
569 check_added_monitors!(nodes[0], 1);
571 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
572 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
573 // No commitment_signed so get_event_msg's assert(len == 1) passes
574 check_added_monitors!(nodes[0], 1);
576 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
577 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
578 check_added_monitors!(nodes[1], 1);
582 fn test_update_fee_that_funder_cannot_afford() {
583 let chanmon_cfgs = create_chanmon_cfgs(2);
584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
587 let channel_value = 5000;
589 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000, InitFeatures::known(), InitFeatures::known());
590 let channel_id = chan.2;
591 let secp_ctx = Secp256k1::new();
592 let bs_channel_reserve_sats = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value);
594 // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
595 // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
596 // calculate two different feerates here - the expected local limit as well as the expected
598 let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (COMMITMENT_TX_BASE_WEIGHT + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
599 let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / COMMITMENT_TX_BASE_WEIGHT) as u32;
601 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
602 *feerate_lock = feerate;
604 nodes[0].node.timer_tick_occurred();
605 check_added_monitors!(nodes[0], 1);
606 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
608 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
610 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
612 // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
614 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
616 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
617 assert_eq!(commitment_tx.output.len(), 2);
618 let total_fee: u64 = commit_tx_fee_msat(feerate, 0) / 1000;
619 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
620 actual_fee = channel_value - actual_fee;
621 assert_eq!(total_fee, actual_fee);
625 // Increment the feerate by a small constant, accounting for rounding errors
626 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
629 nodes[0].node.timer_tick_occurred();
630 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
631 check_added_monitors!(nodes[0], 0);
633 const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
635 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
636 // needed to sign the new commitment tx and (2) sign the new commitment tx.
637 let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
638 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
639 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
640 let chan_signer = local_chan.get_signer();
641 let pubkeys = chan_signer.pubkeys();
642 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
643 pubkeys.funding_pubkey)
645 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
646 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
647 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
648 let chan_signer = remote_chan.get_signer();
649 let pubkeys = chan_signer.pubkeys();
650 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
651 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
652 pubkeys.funding_pubkey)
655 // Assemble the set of keys we can use for signatures for our commitment_signed message.
656 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
657 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
660 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
661 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
662 let local_chan_signer = local_chan.get_signer();
663 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
664 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
665 INITIAL_COMMITMENT_NUMBER - 1,
667 channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0) / 1000,
668 false, local_funding, remote_funding,
669 commit_tx_keys.clone(),
670 non_buffer_feerate + 4,
672 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
674 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
677 let commit_signed_msg = msgs::CommitmentSigned {
680 htlc_signatures: res.1
683 let update_fee = msgs::UpdateFee {
685 feerate_per_kw: non_buffer_feerate + 4,
688 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
690 //While producing the commitment_signed response after handling a received update_fee request the
691 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
692 //Should produce and error.
693 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
694 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
695 check_added_monitors!(nodes[1], 1);
696 check_closed_broadcast!(nodes[1], true);
697 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
701 fn test_update_fee_with_fundee_update_add_htlc() {
702 let chanmon_cfgs = create_chanmon_cfgs(2);
703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
705 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
706 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
709 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
712 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
715 nodes[0].node.timer_tick_occurred();
716 check_added_monitors!(nodes[0], 1);
718 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
719 assert_eq!(events_0.len(), 1);
720 let (update_msg, commitment_signed) = match events_0[0] {
721 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 } } => {
722 (update_fee.as_ref(), commitment_signed)
724 _ => panic!("Unexpected event"),
726 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
727 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
728 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
729 check_added_monitors!(nodes[1], 1);
731 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
733 // nothing happens since node[1] is in AwaitingRemoteRevoke
734 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
736 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
737 assert_eq!(added_monitors.len(), 0);
738 added_monitors.clear();
740 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
741 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
742 // node[1] has nothing to do
744 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
745 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
746 check_added_monitors!(nodes[0], 1);
748 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
749 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
750 // No commitment_signed so get_event_msg's assert(len == 1) passes
751 check_added_monitors!(nodes[0], 1);
752 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
753 check_added_monitors!(nodes[1], 1);
754 // AwaitingRemoteRevoke ends here
756 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
757 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
758 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
759 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
760 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
761 assert_eq!(commitment_update.update_fee.is_none(), true);
763 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
764 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
765 check_added_monitors!(nodes[0], 1);
766 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
768 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
769 check_added_monitors!(nodes[1], 1);
770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
772 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
773 check_added_monitors!(nodes[1], 1);
774 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
775 // No commitment_signed so get_event_msg's assert(len == 1) passes
777 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
778 check_added_monitors!(nodes[0], 1);
779 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
781 expect_pending_htlcs_forwardable!(nodes[0]);
783 let events = nodes[0].node.get_and_clear_pending_events();
784 assert_eq!(events.len(), 1);
786 Event::PaymentReceived { .. } => { },
787 _ => panic!("Unexpected event"),
790 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
792 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
793 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
794 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
795 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
796 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
800 fn test_update_fee() {
801 let chanmon_cfgs = create_chanmon_cfgs(2);
802 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
803 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
804 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
805 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
806 let channel_id = chan.2;
809 // (1) update_fee/commitment_signed ->
810 // <- (2) revoke_and_ack
811 // .- send (3) commitment_signed
812 // (4) update_fee/commitment_signed ->
813 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
814 // <- (3) commitment_signed delivered
815 // send (6) revoke_and_ack -.
816 // <- (5) deliver revoke_and_ack
817 // (6) deliver revoke_and_ack ->
818 // .- send (7) commitment_signed in response to (4)
819 // <- (7) deliver commitment_signed
822 // Create and deliver (1)...
825 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
826 feerate = *feerate_lock;
827 *feerate_lock = feerate + 20;
829 nodes[0].node.timer_tick_occurred();
830 check_added_monitors!(nodes[0], 1);
832 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
833 assert_eq!(events_0.len(), 1);
834 let (update_msg, commitment_signed) = match events_0[0] {
835 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 } } => {
836 (update_fee.as_ref(), commitment_signed)
838 _ => panic!("Unexpected event"),
840 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
842 // Generate (2) and (3):
843 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
844 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
845 check_added_monitors!(nodes[1], 1);
848 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
849 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
850 check_added_monitors!(nodes[0], 1);
852 // Create and deliver (4)...
854 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
855 *feerate_lock = feerate + 30;
857 nodes[0].node.timer_tick_occurred();
858 check_added_monitors!(nodes[0], 1);
859 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
860 assert_eq!(events_0.len(), 1);
861 let (update_msg, commitment_signed) = match events_0[0] {
862 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 } } => {
863 (update_fee.as_ref(), commitment_signed)
865 _ => panic!("Unexpected event"),
868 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
869 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
870 check_added_monitors!(nodes[1], 1);
872 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
873 // No commitment_signed so get_event_msg's assert(len == 1) passes
875 // Handle (3), creating (6):
876 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
877 check_added_monitors!(nodes[0], 1);
878 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
879 // No commitment_signed so get_event_msg's assert(len == 1) passes
882 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
883 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
884 check_added_monitors!(nodes[0], 1);
886 // Deliver (6), creating (7):
887 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
888 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889 assert!(commitment_update.update_add_htlcs.is_empty());
890 assert!(commitment_update.update_fulfill_htlcs.is_empty());
891 assert!(commitment_update.update_fail_htlcs.is_empty());
892 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
893 assert!(commitment_update.update_fee.is_none());
894 check_added_monitors!(nodes[1], 1);
897 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
898 check_added_monitors!(nodes[0], 1);
899 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
900 // No commitment_signed so get_event_msg's assert(len == 1) passes
902 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
903 check_added_monitors!(nodes[1], 1);
904 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
906 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
907 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
908 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
909 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
910 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
914 fn fake_network_test() {
915 // Simple test which builds a network of ChannelManagers, connects them to each other, and
916 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
917 let chanmon_cfgs = create_chanmon_cfgs(4);
918 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
919 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
920 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
922 // Create some initial channels
923 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
924 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
925 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
927 // Rebalance the network a bit by relaying one payment through all the channels...
928 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
929 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
930 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
931 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
933 // Send some more payments
934 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
935 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
936 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
938 // Test failure packets
939 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
940 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
942 // Add a new channel that skips 3
943 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
945 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
946 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
947 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
948 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
949 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
950 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
951 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
953 // Do some rebalance loop payments, simultaneously
954 let mut hops = Vec::with_capacity(3);
956 pubkey: nodes[2].node.get_our_node_id(),
957 node_features: NodeFeatures::empty(),
958 short_channel_id: chan_2.0.contents.short_channel_id,
959 channel_features: ChannelFeatures::empty(),
961 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
964 pubkey: nodes[3].node.get_our_node_id(),
965 node_features: NodeFeatures::empty(),
966 short_channel_id: chan_3.0.contents.short_channel_id,
967 channel_features: ChannelFeatures::empty(),
969 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
972 pubkey: nodes[1].node.get_our_node_id(),
973 node_features: NodeFeatures::known(),
974 short_channel_id: chan_4.0.contents.short_channel_id,
975 channel_features: ChannelFeatures::known(),
977 cltv_expiry_delta: TEST_FINAL_CLTV,
979 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;
980 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;
981 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
983 let mut hops = Vec::with_capacity(3);
985 pubkey: nodes[3].node.get_our_node_id(),
986 node_features: NodeFeatures::empty(),
987 short_channel_id: chan_4.0.contents.short_channel_id,
988 channel_features: ChannelFeatures::empty(),
990 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
993 pubkey: nodes[2].node.get_our_node_id(),
994 node_features: NodeFeatures::empty(),
995 short_channel_id: chan_3.0.contents.short_channel_id,
996 channel_features: ChannelFeatures::empty(),
998 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1000 hops.push(RouteHop {
1001 pubkey: nodes[1].node.get_our_node_id(),
1002 node_features: NodeFeatures::known(),
1003 short_channel_id: chan_2.0.contents.short_channel_id,
1004 channel_features: ChannelFeatures::known(),
1006 cltv_expiry_delta: TEST_FINAL_CLTV,
1008 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;
1009 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;
1010 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops], payee: None }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1012 // Claim the rebalances...
1013 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1014 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1016 // Add a duplicate new channel from 2 to 4
1017 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1019 // Send some payments across both channels
1020 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1021 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1022 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1025 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1026 let events = nodes[0].node.get_and_clear_pending_msg_events();
1027 assert_eq!(events.len(), 0);
1028 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);
1030 //TODO: Test that routes work again here as we've been notified that the channel is full
1032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1033 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1034 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1036 // Close down the channels...
1037 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1038 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
1039 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1040 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1041 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1042 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1043 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1044 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
1045 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1046 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1047 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1048 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1049 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1050 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
1051 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
1055 fn holding_cell_htlc_counting() {
1056 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1057 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1058 // commitment dance rounds.
1059 let chanmon_cfgs = create_chanmon_cfgs(3);
1060 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1061 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1062 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1063 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1064 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1066 let mut payments = Vec::new();
1067 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1068 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1069 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1070 payments.push((payment_preimage, payment_hash));
1072 check_added_monitors!(nodes[1], 1);
1074 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1075 assert_eq!(events.len(), 1);
1076 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1077 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1079 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1080 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1082 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1084 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1085 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1086 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1087 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1090 // This should also be true if we try to forward a payment.
1091 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1093 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1094 check_added_monitors!(nodes[0], 1);
1097 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1098 assert_eq!(events.len(), 1);
1099 let payment_event = SendEvent::from_event(events.pop().unwrap());
1100 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1102 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1103 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1104 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1105 // fails), the second will process the resulting failure and fail the HTLC backward.
1106 expect_pending_htlcs_forwardable!(nodes[1]);
1107 expect_pending_htlcs_forwardable!(nodes[1]);
1108 check_added_monitors!(nodes[1], 1);
1110 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1111 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1112 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1114 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1116 // Now forward all the pending HTLCs and claim them back
1117 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1118 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1119 check_added_monitors!(nodes[2], 1);
1121 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1122 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1123 check_added_monitors!(nodes[1], 1);
1124 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1126 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1127 check_added_monitors!(nodes[1], 1);
1128 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1130 for ref update in as_updates.update_add_htlcs.iter() {
1131 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1133 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1134 check_added_monitors!(nodes[2], 1);
1135 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1136 check_added_monitors!(nodes[2], 1);
1137 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1139 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1140 check_added_monitors!(nodes[1], 1);
1141 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1142 check_added_monitors!(nodes[1], 1);
1143 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1145 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1146 check_added_monitors!(nodes[2], 1);
1148 expect_pending_htlcs_forwardable!(nodes[2]);
1150 let events = nodes[2].node.get_and_clear_pending_events();
1151 assert_eq!(events.len(), payments.len());
1152 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1154 &Event::PaymentReceived { ref payment_hash, .. } => {
1155 assert_eq!(*payment_hash, *hash);
1157 _ => panic!("Unexpected event"),
1161 for (preimage, _) in payments.drain(..) {
1162 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1165 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1169 fn duplicate_htlc_test() {
1170 // Test that we accept duplicate payment_hash HTLCs across the network and that
1171 // claiming/failing them are all separate and don't affect each other
1172 let chanmon_cfgs = create_chanmon_cfgs(6);
1173 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1174 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1175 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1177 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1178 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1179 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1180 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1181 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1182 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1184 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1186 *nodes[0].network_payment_count.borrow_mut() -= 1;
1187 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1189 *nodes[0].network_payment_count.borrow_mut() -= 1;
1190 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1192 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1193 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1194 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1198 fn test_duplicate_htlc_different_direction_onchain() {
1199 // Test that ChannelMonitor doesn't generate 2 preimage txn
1200 // when we have 2 HTLCs with same preimage that go across a node
1201 // in opposite directions, even with the same payment secret.
1202 let chanmon_cfgs = create_chanmon_cfgs(2);
1203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1207 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1210 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1212 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1214 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1215 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200).unwrap();
1216 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1218 // Provide preimage to node 0 by claiming payment
1219 nodes[0].node.claim_funds(payment_preimage);
1220 check_added_monitors!(nodes[0], 1);
1222 // Broadcast node 1 commitment txn
1223 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1225 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1226 let mut has_both_htlcs = 0; // check htlcs match ones committed
1227 for outp in remote_txn[0].output.iter() {
1228 if outp.value == 800_000 / 1000 {
1229 has_both_htlcs += 1;
1230 } else if outp.value == 900_000 / 1000 {
1231 has_both_htlcs += 1;
1234 assert_eq!(has_both_htlcs, 2);
1236 mine_transaction(&nodes[0], &remote_txn[0]);
1237 check_added_monitors!(nodes[0], 1);
1238 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1239 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1241 // Check we only broadcast 1 timeout tx
1242 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1243 assert_eq!(claim_txn.len(), 8);
1244 assert_eq!(claim_txn[1], claim_txn[4]);
1245 assert_eq!(claim_txn[2], claim_txn[5]);
1246 check_spends!(claim_txn[1], chan_1.3);
1247 check_spends!(claim_txn[2], claim_txn[1]);
1248 check_spends!(claim_txn[7], claim_txn[1]);
1250 assert_eq!(claim_txn[0].input.len(), 1);
1251 assert_eq!(claim_txn[3].input.len(), 1);
1252 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1254 assert_eq!(claim_txn[0].input.len(), 1);
1255 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1256 check_spends!(claim_txn[0], remote_txn[0]);
1257 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1258 assert_eq!(claim_txn[6].input.len(), 1);
1259 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1260 check_spends!(claim_txn[6], remote_txn[0]);
1261 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1263 let events = nodes[0].node.get_and_clear_pending_msg_events();
1264 assert_eq!(events.len(), 3);
1267 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1268 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1269 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1270 assert_eq!(msg.data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1272 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, .. } } => {
1273 assert!(update_add_htlcs.is_empty());
1274 assert!(update_fail_htlcs.is_empty());
1275 assert_eq!(update_fulfill_htlcs.len(), 1);
1276 assert!(update_fail_malformed_htlcs.is_empty());
1277 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1279 _ => panic!("Unexpected event"),
1285 fn test_basic_channel_reserve() {
1286 let chanmon_cfgs = create_chanmon_cfgs(2);
1287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1289 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1290 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1292 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1293 let channel_reserve = chan_stat.channel_reserve_msat;
1295 // The 2* and +1 are for the fee spike reserve.
1296 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1297 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1299 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1301 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1303 &APIError::ChannelUnavailable{ref err} =>
1304 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1305 _ => panic!("Unexpected error variant"),
1308 _ => panic!("Unexpected error variant"),
1310 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1311 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);
1313 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1317 fn test_fee_spike_violation_fails_htlc() {
1318 let chanmon_cfgs = create_chanmon_cfgs(2);
1319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1322 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1324 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1325 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1326 let secp_ctx = Secp256k1::new();
1327 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1329 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1331 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1332 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1333 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1334 let msg = msgs::UpdateAddHTLC {
1337 amount_msat: htlc_msat,
1338 payment_hash: payment_hash,
1339 cltv_expiry: htlc_cltv,
1340 onion_routing_packet: onion_packet,
1343 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1345 // Now manually create the commitment_signed message corresponding to the update_add
1346 // nodes[0] just sent. In the code for construction of this message, "local" refers
1347 // to the sender of the message, and "remote" refers to the receiver.
1349 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1351 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1353 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1354 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1355 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1356 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1357 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1358 let chan_signer = local_chan.get_signer();
1359 // Make the signer believe we validated another commitment, so we can release the secret
1360 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1362 let pubkeys = chan_signer.pubkeys();
1363 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1364 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1365 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1366 chan_signer.pubkeys().funding_pubkey)
1368 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1369 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1370 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1371 let chan_signer = remote_chan.get_signer();
1372 let pubkeys = chan_signer.pubkeys();
1373 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1374 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1375 chan_signer.pubkeys().funding_pubkey)
1378 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1379 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1380 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1382 // Build the remote commitment transaction so we can sign it, and then later use the
1383 // signature for the commitment_signed message.
1384 let local_chan_balance = 1313;
1386 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1388 amount_msat: 3460001,
1389 cltv_expiry: htlc_cltv,
1391 transaction_output_index: Some(1),
1394 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1397 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1398 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1399 let local_chan_signer = local_chan.get_signer();
1400 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1404 false, local_funding, remote_funding,
1405 commit_tx_keys.clone(),
1407 &mut vec![(accepted_htlc_info, ())],
1408 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1410 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1413 let commit_signed_msg = msgs::CommitmentSigned {
1416 htlc_signatures: res.1
1419 // Send the commitment_signed message to the nodes[1].
1420 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1421 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1423 // Send the RAA to nodes[1].
1424 let raa_msg = msgs::RevokeAndACK {
1426 per_commitment_secret: local_secret,
1427 next_per_commitment_point: next_local_point
1429 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1431 let events = nodes[1].node.get_and_clear_pending_msg_events();
1432 assert_eq!(events.len(), 1);
1433 // Make sure the HTLC failed in the way we expect.
1435 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1436 assert_eq!(update_fail_htlcs.len(), 1);
1437 update_fail_htlcs[0].clone()
1439 _ => panic!("Unexpected event"),
1441 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1442 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1444 check_added_monitors!(nodes[1], 2);
1448 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1449 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1450 // Set the fee rate for the channel very high, to the point where the fundee
1451 // sending any above-dust amount would result in a channel reserve violation.
1452 // In this test we check that we would be prevented from sending an HTLC in
1454 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1455 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1456 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1457 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1459 let mut push_amt = 100_000_000;
1460 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1461 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1463 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1465 // Sending exactly enough to hit the reserve amount should be accepted
1466 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1467 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1470 // However one more HTLC should be significantly over the reserve amount and fail.
1471 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1472 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1473 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1474 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1475 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);
1479 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1480 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1481 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1484 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1486 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1487 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1488 // transaction fee with 0 HTLCs (183 sats)).
1489 let mut push_amt = 100_000_000;
1490 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1491 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1492 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1494 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1495 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1496 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1499 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 700_000);
1500 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1501 let secp_ctx = Secp256k1::new();
1502 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1503 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1504 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1505 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 700_000, &Some(payment_secret), cur_height, &None).unwrap();
1506 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1507 let msg = msgs::UpdateAddHTLC {
1509 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1510 amount_msat: htlc_msat,
1511 payment_hash: payment_hash,
1512 cltv_expiry: htlc_cltv,
1513 onion_routing_packet: onion_packet,
1516 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1517 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1518 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);
1519 assert_eq!(nodes[0].node.list_channels().len(), 0);
1520 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1521 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1522 check_added_monitors!(nodes[0], 1);
1523 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() });
1527 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1528 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1529 // calculating our commitment transaction fee (this was previously broken).
1530 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1531 let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1535 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1537 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1538 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1539 // transaction fee with 0 HTLCs (183 sats)).
1540 let mut push_amt = 100_000_000;
1541 push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64);
1542 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1543 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1545 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1546 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1547 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1548 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1549 // commitment transaction fee.
1550 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1552 // Send four HTLCs to cover the initial push_msat buffer we're required to include
1553 for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1554 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1557 // One more than the dust amt should fail, however.
1558 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1559 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1560 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1564 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1565 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1566 // calculating our counterparty's commitment transaction fee (this was previously broken).
1567 let chanmon_cfgs = create_chanmon_cfgs(2);
1568 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1569 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1570 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1571 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1573 let payment_amt = 46000; // Dust amount
1574 // In the previous code, these first four payments would succeed.
1575 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1576 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1577 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1578 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1580 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1581 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1582 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1583 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1584 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1585 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1587 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1588 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1589 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1590 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1594 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1595 let chanmon_cfgs = create_chanmon_cfgs(3);
1596 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1597 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1598 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1599 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1600 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1603 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1604 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1605 let feerate = get_feerate!(nodes[0], chan.2);
1607 // Add a 2* and +1 for the fee spike reserve.
1608 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1609 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;
1610 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1612 // Add a pending HTLC.
1613 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1614 let payment_event_1 = {
1615 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1616 check_added_monitors!(nodes[0], 1);
1618 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1619 assert_eq!(events.len(), 1);
1620 SendEvent::from_event(events.remove(0))
1622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1624 // Attempt to trigger a channel reserve violation --> payment failure.
1625 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1626 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;
1627 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1628 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1630 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1631 let secp_ctx = Secp256k1::new();
1632 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1633 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1634 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1635 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1636 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1637 let msg = msgs::UpdateAddHTLC {
1640 amount_msat: htlc_msat + 1,
1641 payment_hash: our_payment_hash_1,
1642 cltv_expiry: htlc_cltv,
1643 onion_routing_packet: onion_packet,
1646 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1647 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1648 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1649 assert_eq!(nodes[1].node.list_channels().len(), 1);
1650 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1651 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1652 check_added_monitors!(nodes[1], 1);
1653 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1657 fn test_inbound_outbound_capacity_is_not_zero() {
1658 let chanmon_cfgs = create_chanmon_cfgs(2);
1659 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1660 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1661 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1662 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1663 let channels0 = node_chanmgrs[0].list_channels();
1664 let channels1 = node_chanmgrs[1].list_channels();
1665 assert_eq!(channels0.len(), 1);
1666 assert_eq!(channels1.len(), 1);
1668 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1669 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1670 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1672 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1673 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1676 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1677 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1681 fn test_channel_reserve_holding_cell_htlcs() {
1682 let chanmon_cfgs = create_chanmon_cfgs(3);
1683 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1684 // When this test was written, the default base fee floated based on the HTLC count.
1685 // It is now fixed, so we simply set the fee to the expected value here.
1686 let mut config = test_default_channel_config();
1687 config.channel_options.forwarding_fee_base_msat = 239;
1688 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1689 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1690 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1691 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1693 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1694 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1696 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1697 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1699 macro_rules! expect_forward {
1701 let mut events = $node.node.get_and_clear_pending_msg_events();
1702 assert_eq!(events.len(), 1);
1703 check_added_monitors!($node, 1);
1704 let payment_event = SendEvent::from_event(events.remove(0));
1709 let feemsat = 239; // set above
1710 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1711 let feerate = get_feerate!(nodes[0], chan_1.2);
1713 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1715 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1717 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1718 route.paths[0].last_mut().unwrap().fee_msat += 1;
1719 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1720 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1721 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)));
1722 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1723 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);
1726 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1727 // nodes[0]'s wealth
1729 let amt_msat = recv_value_0 + total_fee_msat;
1730 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1731 // Also, ensure that each payment has enough to be over the dust limit to
1732 // ensure it'll be included in each commit tx fee calculation.
1733 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1734 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1735 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1738 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1740 let (stat01_, stat11_, stat12_, stat22_) = (
1741 get_channel_value_stat!(nodes[0], chan_1.2),
1742 get_channel_value_stat!(nodes[1], chan_1.2),
1743 get_channel_value_stat!(nodes[1], chan_2.2),
1744 get_channel_value_stat!(nodes[2], chan_2.2),
1747 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1748 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1749 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1750 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1751 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1754 // adding pending output.
1755 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1756 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1757 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1758 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1759 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1760 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1761 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1762 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1763 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1765 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1766 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1767 let amt_msat_1 = recv_value_1 + total_fee_msat;
1769 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);
1770 let payment_event_1 = {
1771 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1772 check_added_monitors!(nodes[0], 1);
1774 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1775 assert_eq!(events.len(), 1);
1776 SendEvent::from_event(events.remove(0))
1778 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1780 // channel reserve test with htlc pending output > 0
1781 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1783 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1784 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1785 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1786 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1789 // split the rest to test holding cell
1790 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1791 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1792 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1793 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1795 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1796 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);
1799 // now see if they go through on both sides
1800 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);
1801 // but this will stuck in the holding cell
1802 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1803 check_added_monitors!(nodes[0], 0);
1804 let events = nodes[0].node.get_and_clear_pending_events();
1805 assert_eq!(events.len(), 0);
1807 // test with outbound holding cell amount > 0
1809 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1810 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1811 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1812 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1813 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);
1816 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);
1817 // this will also stuck in the holding cell
1818 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1819 check_added_monitors!(nodes[0], 0);
1820 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1821 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1823 // flush the pending htlc
1824 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1825 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1826 check_added_monitors!(nodes[1], 1);
1828 // the pending htlc should be promoted to committed
1829 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1830 check_added_monitors!(nodes[0], 1);
1831 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1833 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1834 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1835 // No commitment_signed so get_event_msg's assert(len == 1) passes
1836 check_added_monitors!(nodes[0], 1);
1838 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1839 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1840 check_added_monitors!(nodes[1], 1);
1842 expect_pending_htlcs_forwardable!(nodes[1]);
1844 let ref payment_event_11 = expect_forward!(nodes[1]);
1845 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1846 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1848 expect_pending_htlcs_forwardable!(nodes[2]);
1849 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1851 // flush the htlcs in the holding cell
1852 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1853 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1855 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1856 expect_pending_htlcs_forwardable!(nodes[1]);
1858 let ref payment_event_3 = expect_forward!(nodes[1]);
1859 assert_eq!(payment_event_3.msgs.len(), 2);
1860 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1861 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1863 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1864 expect_pending_htlcs_forwardable!(nodes[2]);
1866 let events = nodes[2].node.get_and_clear_pending_events();
1867 assert_eq!(events.len(), 2);
1869 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1870 assert_eq!(our_payment_hash_21, *payment_hash);
1871 assert_eq!(recv_value_21, amt);
1873 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1874 assert!(payment_preimage.is_none());
1875 assert_eq!(our_payment_secret_21, *payment_secret);
1877 _ => panic!("expected PaymentPurpose::InvoicePayment")
1880 _ => panic!("Unexpected event"),
1883 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1884 assert_eq!(our_payment_hash_22, *payment_hash);
1885 assert_eq!(recv_value_22, amt);
1887 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1888 assert!(payment_preimage.is_none());
1889 assert_eq!(our_payment_secret_22, *payment_secret);
1891 _ => panic!("expected PaymentPurpose::InvoicePayment")
1894 _ => panic!("Unexpected event"),
1897 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1898 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1899 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1901 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1902 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1903 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1905 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1906 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);
1907 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1908 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1909 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1911 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1912 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1916 fn channel_reserve_in_flight_removes() {
1917 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1918 // can send to its counterparty, but due to update ordering, the other side may not yet have
1919 // considered those HTLCs fully removed.
1920 // This tests that we don't count HTLCs which will not be included in the next remote
1921 // commitment transaction towards the reserve value (as it implies no commitment transaction
1922 // will be generated which violates the remote reserve value).
1923 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1925 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1926 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1927 // you only consider the value of the first HTLC, it may not),
1928 // * start routing a third HTLC from A to B,
1929 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1930 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1931 // * deliver the first fulfill from B
1932 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1934 // * deliver A's response CS and RAA.
1935 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1936 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1937 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1938 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1939 let chanmon_cfgs = create_chanmon_cfgs(2);
1940 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1941 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1942 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1943 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1945 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1946 // Route the first two HTLCs.
1947 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1948 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1950 // Start routing the third HTLC (this is just used to get everyone in the right state).
1951 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1953 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1954 check_added_monitors!(nodes[0], 1);
1955 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1956 assert_eq!(events.len(), 1);
1957 SendEvent::from_event(events.remove(0))
1960 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1961 // initial fulfill/CS.
1962 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1963 check_added_monitors!(nodes[1], 1);
1964 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1966 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1967 // remove the second HTLC when we send the HTLC back from B to A.
1968 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1969 check_added_monitors!(nodes[1], 1);
1970 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1972 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1973 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1974 check_added_monitors!(nodes[0], 1);
1975 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1976 expect_payment_sent!(nodes[0], payment_preimage_1);
1978 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1979 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1980 check_added_monitors!(nodes[1], 1);
1981 // B is already AwaitingRAA, so cant generate a CS here
1982 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1984 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1985 check_added_monitors!(nodes[1], 1);
1986 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1988 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1989 check_added_monitors!(nodes[0], 1);
1990 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1992 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1993 check_added_monitors!(nodes[1], 1);
1994 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1996 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1997 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1998 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1999 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2000 // on-chain as necessary).
2001 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2002 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2003 check_added_monitors!(nodes[0], 1);
2004 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2005 expect_payment_sent!(nodes[0], payment_preimage_2);
2007 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2008 check_added_monitors!(nodes[1], 1);
2009 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2011 expect_pending_htlcs_forwardable!(nodes[1]);
2012 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2014 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2015 // resolve the second HTLC from A's point of view.
2016 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2017 check_added_monitors!(nodes[0], 1);
2018 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2020 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2021 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2022 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2024 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2025 check_added_monitors!(nodes[1], 1);
2026 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2027 assert_eq!(events.len(), 1);
2028 SendEvent::from_event(events.remove(0))
2031 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2032 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2033 check_added_monitors!(nodes[0], 1);
2034 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2036 // Now just resolve all the outstanding messages/HTLCs for completeness...
2038 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2039 check_added_monitors!(nodes[1], 1);
2040 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2042 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2043 check_added_monitors!(nodes[1], 1);
2045 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2046 check_added_monitors!(nodes[0], 1);
2047 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2049 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2050 check_added_monitors!(nodes[1], 1);
2051 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2053 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2054 check_added_monitors!(nodes[0], 1);
2056 expect_pending_htlcs_forwardable!(nodes[0]);
2057 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2059 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2060 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2064 fn channel_monitor_network_test() {
2065 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2066 // tests that ChannelMonitor is able to recover from various states.
2067 let chanmon_cfgs = create_chanmon_cfgs(5);
2068 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2069 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2070 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2072 // Create some initial channels
2073 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2074 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2075 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2076 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2078 // Make sure all nodes are at the same starting height
2079 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2080 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2081 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2082 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2083 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2085 // Rebalance the network a bit by relaying one payment through all the channels...
2086 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2087 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2088 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2089 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2091 // Simple case with no pending HTLCs:
2092 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2093 check_added_monitors!(nodes[1], 1);
2094 check_closed_broadcast!(nodes[1], false);
2096 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2097 assert_eq!(node_txn.len(), 1);
2098 mine_transaction(&nodes[0], &node_txn[0]);
2099 check_added_monitors!(nodes[0], 1);
2100 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2102 check_closed_broadcast!(nodes[0], true);
2103 assert_eq!(nodes[0].node.list_channels().len(), 0);
2104 assert_eq!(nodes[1].node.list_channels().len(), 1);
2105 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2106 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2108 // One pending HTLC is discarded by the force-close:
2109 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2111 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2112 // broadcasted until we reach the timelock time).
2113 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2114 check_closed_broadcast!(nodes[1], false);
2115 check_added_monitors!(nodes[1], 1);
2117 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2118 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2119 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2120 mine_transaction(&nodes[2], &node_txn[0]);
2121 check_added_monitors!(nodes[2], 1);
2122 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2124 check_closed_broadcast!(nodes[2], true);
2125 assert_eq!(nodes[1].node.list_channels().len(), 0);
2126 assert_eq!(nodes[2].node.list_channels().len(), 1);
2127 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2128 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2130 macro_rules! claim_funds {
2131 ($node: expr, $prev_node: expr, $preimage: expr) => {
2133 assert!($node.node.claim_funds($preimage));
2134 check_added_monitors!($node, 1);
2136 let events = $node.node.get_and_clear_pending_msg_events();
2137 assert_eq!(events.len(), 1);
2139 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2140 assert!(update_add_htlcs.is_empty());
2141 assert!(update_fail_htlcs.is_empty());
2142 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2144 _ => panic!("Unexpected event"),
2150 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2151 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2152 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2153 check_added_monitors!(nodes[2], 1);
2154 check_closed_broadcast!(nodes[2], false);
2155 let node2_commitment_txid;
2157 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2158 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2159 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2160 node2_commitment_txid = node_txn[0].txid();
2162 // Claim the payment on nodes[3], giving it knowledge of the preimage
2163 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2164 mine_transaction(&nodes[3], &node_txn[0]);
2165 check_added_monitors!(nodes[3], 1);
2166 check_preimage_claim(&nodes[3], &node_txn);
2168 check_closed_broadcast!(nodes[3], true);
2169 assert_eq!(nodes[2].node.list_channels().len(), 0);
2170 assert_eq!(nodes[3].node.list_channels().len(), 1);
2171 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2172 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2174 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2175 // confusing us in the following tests.
2176 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2178 // One pending HTLC to time out:
2179 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2180 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2183 let (close_chan_update_1, close_chan_update_2) = {
2184 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2185 let events = nodes[3].node.get_and_clear_pending_msg_events();
2186 assert_eq!(events.len(), 2);
2187 let close_chan_update_1 = match events[0] {
2188 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2191 _ => panic!("Unexpected event"),
2194 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2195 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2197 _ => panic!("Unexpected event"),
2199 check_added_monitors!(nodes[3], 1);
2201 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2203 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2204 node_txn.retain(|tx| {
2205 if tx.input[0].previous_output.txid == node2_commitment_txid {
2211 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2213 // Claim the payment on nodes[4], giving it knowledge of the preimage
2214 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2216 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2217 let events = nodes[4].node.get_and_clear_pending_msg_events();
2218 assert_eq!(events.len(), 2);
2219 let close_chan_update_2 = match events[0] {
2220 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2223 _ => panic!("Unexpected event"),
2226 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2227 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2229 _ => panic!("Unexpected event"),
2231 check_added_monitors!(nodes[4], 1);
2232 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2234 mine_transaction(&nodes[4], &node_txn[0]);
2235 check_preimage_claim(&nodes[4], &node_txn);
2236 (close_chan_update_1, close_chan_update_2)
2238 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2239 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2240 assert_eq!(nodes[3].node.list_channels().len(), 0);
2241 assert_eq!(nodes[4].node.list_channels().len(), 0);
2243 nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon).unwrap();
2244 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2245 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2249 fn test_justice_tx() {
2250 // Test justice txn built on revoked HTLC-Success tx, against both sides
2251 let mut alice_config = UserConfig::default();
2252 alice_config.channel_options.announced_channel = true;
2253 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2254 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2255 let mut bob_config = UserConfig::default();
2256 bob_config.channel_options.announced_channel = true;
2257 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2258 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2259 let user_cfgs = [Some(alice_config), Some(bob_config)];
2260 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2261 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2262 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2263 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2264 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2265 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2266 // Create some new channels:
2267 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2269 // A pending HTLC which will be revoked:
2270 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2271 // Get the will-be-revoked local txn from nodes[0]
2272 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2273 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2274 assert_eq!(revoked_local_txn[0].input.len(), 1);
2275 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2276 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2277 assert_eq!(revoked_local_txn[1].input.len(), 1);
2278 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2279 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2280 // Revoke the old state
2281 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2284 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2286 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2287 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2288 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2290 check_spends!(node_txn[0], revoked_local_txn[0]);
2291 node_txn.swap_remove(0);
2292 node_txn.truncate(1);
2294 check_added_monitors!(nodes[1], 1);
2295 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2296 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2298 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2299 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2300 // Verify broadcast of revoked HTLC-timeout
2301 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2302 check_added_monitors!(nodes[0], 1);
2303 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2304 // Broadcast revoked HTLC-timeout on node 1
2305 mine_transaction(&nodes[1], &node_txn[1]);
2306 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2308 get_announce_close_broadcast_events(&nodes, 0, 1);
2310 assert_eq!(nodes[0].node.list_channels().len(), 0);
2311 assert_eq!(nodes[1].node.list_channels().len(), 0);
2313 // We test justice_tx build by A on B's revoked HTLC-Success tx
2314 // Create some new channels:
2315 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2317 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2321 // A pending HTLC which will be revoked:
2322 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2323 // Get the will-be-revoked local txn from B
2324 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2325 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2326 assert_eq!(revoked_local_txn[0].input.len(), 1);
2327 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2328 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2329 // Revoke the old state
2330 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2332 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2334 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2335 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2336 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2338 check_spends!(node_txn[0], revoked_local_txn[0]);
2339 node_txn.swap_remove(0);
2341 check_added_monitors!(nodes[0], 1);
2342 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2344 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2345 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2346 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2347 check_added_monitors!(nodes[1], 1);
2348 mine_transaction(&nodes[0], &node_txn[1]);
2349 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2350 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2352 get_announce_close_broadcast_events(&nodes, 0, 1);
2353 assert_eq!(nodes[0].node.list_channels().len(), 0);
2354 assert_eq!(nodes[1].node.list_channels().len(), 0);
2358 fn revoked_output_claim() {
2359 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2360 // transaction is broadcast by its counterparty
2361 let chanmon_cfgs = create_chanmon_cfgs(2);
2362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2364 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2365 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2366 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2367 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2368 assert_eq!(revoked_local_txn.len(), 1);
2369 // Only output is the full channel value back to nodes[0]:
2370 assert_eq!(revoked_local_txn[0].output.len(), 1);
2371 // Send a payment through, updating everyone's latest commitment txn
2372 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2374 // Inform nodes[1] that nodes[0] broadcast a stale tx
2375 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2376 check_added_monitors!(nodes[1], 1);
2377 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2378 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2379 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2381 check_spends!(node_txn[0], revoked_local_txn[0]);
2382 check_spends!(node_txn[1], chan_1.3);
2384 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2385 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2386 get_announce_close_broadcast_events(&nodes, 0, 1);
2387 check_added_monitors!(nodes[0], 1);
2388 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2392 fn claim_htlc_outputs_shared_tx() {
2393 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2394 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2395 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2400 // Create some new channel:
2401 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2403 // Rebalance the network to generate htlc in the two directions
2404 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2405 // 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
2406 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2407 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2409 // Get the will-be-revoked local txn from node[0]
2410 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2411 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2412 assert_eq!(revoked_local_txn[0].input.len(), 1);
2413 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2414 assert_eq!(revoked_local_txn[1].input.len(), 1);
2415 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2416 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2417 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2419 //Revoke the old state
2420 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2423 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2424 check_added_monitors!(nodes[0], 1);
2425 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2426 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2427 check_added_monitors!(nodes[1], 1);
2428 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2429 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2430 expect_payment_failed!(nodes[1], payment_hash_2, true);
2432 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2433 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2435 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2436 check_spends!(node_txn[0], revoked_local_txn[0]);
2438 let mut witness_lens = BTreeSet::new();
2439 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2440 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2441 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2442 assert_eq!(witness_lens.len(), 3);
2443 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2444 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2445 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2447 // Next nodes[1] broadcasts its current local tx state:
2448 assert_eq!(node_txn[1].input.len(), 1);
2449 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2451 get_announce_close_broadcast_events(&nodes, 0, 1);
2452 assert_eq!(nodes[0].node.list_channels().len(), 0);
2453 assert_eq!(nodes[1].node.list_channels().len(), 0);
2457 fn claim_htlc_outputs_single_tx() {
2458 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2459 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2460 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2461 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2462 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2463 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2465 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2467 // Rebalance the network to generate htlc in the two directions
2468 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2469 // 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
2470 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2471 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2472 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2474 // Get the will-be-revoked local txn from node[0]
2475 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2477 //Revoke the old state
2478 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2481 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2482 check_added_monitors!(nodes[0], 1);
2483 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2484 check_added_monitors!(nodes[1], 1);
2485 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2486 let mut events = nodes[0].node.get_and_clear_pending_events();
2487 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2489 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2490 _ => panic!("Unexpected event"),
2493 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2494 expect_payment_failed!(nodes[1], payment_hash_2, true);
2496 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2497 assert_eq!(node_txn.len(), 9);
2498 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2499 // ChannelManager: local commmitment + local HTLC-timeout (2)
2500 // 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)
2501 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2503 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2504 assert_eq!(node_txn[0].input.len(), 1);
2505 check_spends!(node_txn[0], chan_1.3);
2506 assert_eq!(node_txn[1].input.len(), 1);
2507 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2508 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2509 check_spends!(node_txn[1], node_txn[0]);
2511 // Justice transactions are indices 1-2-4
2512 assert_eq!(node_txn[2].input.len(), 1);
2513 assert_eq!(node_txn[3].input.len(), 1);
2514 assert_eq!(node_txn[4].input.len(), 1);
2516 check_spends!(node_txn[2], revoked_local_txn[0]);
2517 check_spends!(node_txn[3], revoked_local_txn[0]);
2518 check_spends!(node_txn[4], revoked_local_txn[0]);
2520 let mut witness_lens = BTreeSet::new();
2521 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2522 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2523 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2524 assert_eq!(witness_lens.len(), 3);
2525 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2526 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2527 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2529 get_announce_close_broadcast_events(&nodes, 0, 1);
2530 assert_eq!(nodes[0].node.list_channels().len(), 0);
2531 assert_eq!(nodes[1].node.list_channels().len(), 0);
2535 fn test_htlc_on_chain_success() {
2536 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2537 // the preimage backward accordingly. So here we test that ChannelManager is
2538 // broadcasting the right event to other nodes in payment path.
2539 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2540 // A --------------------> B ----------------------> C (preimage)
2541 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2542 // commitment transaction was broadcast.
2543 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2545 // B should be able to claim via preimage if A then broadcasts its local tx.
2546 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2547 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2548 // PaymentSent event).
2550 let chanmon_cfgs = create_chanmon_cfgs(3);
2551 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2552 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2553 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2555 // Create some initial channels
2556 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2557 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2559 // Ensure all nodes are at the same height
2560 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2561 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2562 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2563 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2565 // Rebalance the network a bit by relaying one payment through all the channels...
2566 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2567 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2569 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2570 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2572 // Broadcast legit commitment tx from C on B's chain
2573 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2574 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2575 assert_eq!(commitment_tx.len(), 1);
2576 check_spends!(commitment_tx[0], chan_2.3);
2577 nodes[2].node.claim_funds(our_payment_preimage);
2578 nodes[2].node.claim_funds(our_payment_preimage_2);
2579 check_added_monitors!(nodes[2], 2);
2580 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2581 assert!(updates.update_add_htlcs.is_empty());
2582 assert!(updates.update_fail_htlcs.is_empty());
2583 assert!(updates.update_fail_malformed_htlcs.is_empty());
2584 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2586 mine_transaction(&nodes[2], &commitment_tx[0]);
2587 check_closed_broadcast!(nodes[2], true);
2588 check_added_monitors!(nodes[2], 1);
2589 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2590 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)
2591 assert_eq!(node_txn.len(), 5);
2592 assert_eq!(node_txn[0], node_txn[3]);
2593 assert_eq!(node_txn[1], node_txn[4]);
2594 assert_eq!(node_txn[2], commitment_tx[0]);
2595 check_spends!(node_txn[0], commitment_tx[0]);
2596 check_spends!(node_txn[1], commitment_tx[0]);
2597 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2598 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2599 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2600 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2601 assert_eq!(node_txn[0].lock_time, 0);
2602 assert_eq!(node_txn[1].lock_time, 0);
2604 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2605 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2606 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2607 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2609 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2610 assert_eq!(added_monitors.len(), 1);
2611 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2612 added_monitors.clear();
2614 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2615 assert_eq!(forwarded_events.len(), 3);
2616 match forwarded_events[0] {
2617 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2618 _ => panic!("Unexpected event"),
2620 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2621 } else { panic!(); }
2622 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2623 } else { panic!(); }
2624 let events = nodes[1].node.get_and_clear_pending_msg_events();
2626 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2627 assert_eq!(added_monitors.len(), 2);
2628 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2629 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2630 added_monitors.clear();
2632 assert_eq!(events.len(), 3);
2634 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2635 _ => panic!("Unexpected event"),
2638 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2639 _ => panic!("Unexpected event"),
2643 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, .. } } => {
2644 assert!(update_add_htlcs.is_empty());
2645 assert!(update_fail_htlcs.is_empty());
2646 assert_eq!(update_fulfill_htlcs.len(), 1);
2647 assert!(update_fail_malformed_htlcs.is_empty());
2648 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2650 _ => panic!("Unexpected event"),
2652 macro_rules! check_tx_local_broadcast {
2653 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2654 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2655 assert_eq!(node_txn.len(), 3);
2656 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2657 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2658 check_spends!(node_txn[1], $commitment_tx);
2659 check_spends!(node_txn[2], $commitment_tx);
2660 assert_ne!(node_txn[1].lock_time, 0);
2661 assert_ne!(node_txn[2].lock_time, 0);
2663 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2664 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2665 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2666 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2668 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2669 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2670 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2671 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2673 check_spends!(node_txn[0], $chan_tx);
2674 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2678 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2679 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2680 // timeout-claim of the output that nodes[2] just claimed via success.
2681 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2683 // Broadcast legit commitment tx from A on B's chain
2684 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2685 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2686 check_spends!(node_a_commitment_tx[0], chan_1.3);
2687 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2688 check_closed_broadcast!(nodes[1], true);
2689 check_added_monitors!(nodes[1], 1);
2690 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2691 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2692 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2693 let commitment_spend =
2694 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2695 check_spends!(node_txn[1], commitment_tx[0]);
2696 check_spends!(node_txn[2], commitment_tx[0]);
2697 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2700 check_spends!(node_txn[0], commitment_tx[0]);
2701 check_spends!(node_txn[1], commitment_tx[0]);
2702 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2706 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2707 assert_eq!(commitment_spend.input.len(), 2);
2708 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2709 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2710 assert_eq!(commitment_spend.lock_time, 0);
2711 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2712 check_spends!(node_txn[3], chan_1.3);
2713 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2714 check_spends!(node_txn[4], node_txn[3]);
2715 check_spends!(node_txn[5], node_txn[3]);
2716 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2717 // we already checked the same situation with A.
2719 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2720 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2721 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2722 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2723 check_closed_broadcast!(nodes[0], true);
2724 check_added_monitors!(nodes[0], 1);
2725 let events = nodes[0].node.get_and_clear_pending_events();
2726 assert_eq!(events.len(), 3);
2727 let mut first_claimed = false;
2728 for event in events {
2730 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
2731 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2732 assert!(!first_claimed);
2733 first_claimed = true;
2735 assert_eq!(payment_preimage, our_payment_preimage_2);
2736 assert_eq!(payment_hash, payment_hash_2);
2739 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2740 _ => panic!("Unexpected event"),
2743 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2746 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2747 // Test that in case of a unilateral close onchain, we detect the state of output and
2748 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2749 // broadcasting the right event to other nodes in payment path.
2750 // A ------------------> B ----------------------> C (timeout)
2751 // B's commitment tx C's commitment tx
2753 // B's HTLC timeout tx B's timeout tx
2755 let chanmon_cfgs = create_chanmon_cfgs(3);
2756 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2757 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2758 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2759 *nodes[0].connect_style.borrow_mut() = connect_style;
2760 *nodes[1].connect_style.borrow_mut() = connect_style;
2761 *nodes[2].connect_style.borrow_mut() = connect_style;
2763 // Create some intial channels
2764 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2765 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2767 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2768 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2769 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2771 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2773 // Broadcast legit commitment tx from C on B's chain
2774 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2775 check_spends!(commitment_tx[0], chan_2.3);
2776 nodes[2].node.fail_htlc_backwards(&payment_hash);
2777 check_added_monitors!(nodes[2], 0);
2778 expect_pending_htlcs_forwardable!(nodes[2]);
2779 check_added_monitors!(nodes[2], 1);
2781 let events = nodes[2].node.get_and_clear_pending_msg_events();
2782 assert_eq!(events.len(), 1);
2784 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, .. } } => {
2785 assert!(update_add_htlcs.is_empty());
2786 assert!(!update_fail_htlcs.is_empty());
2787 assert!(update_fulfill_htlcs.is_empty());
2788 assert!(update_fail_malformed_htlcs.is_empty());
2789 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2791 _ => panic!("Unexpected event"),
2793 mine_transaction(&nodes[2], &commitment_tx[0]);
2794 check_closed_broadcast!(nodes[2], true);
2795 check_added_monitors!(nodes[2], 1);
2796 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2797 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2798 assert_eq!(node_txn.len(), 1);
2799 check_spends!(node_txn[0], chan_2.3);
2800 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2802 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2803 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2804 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2805 mine_transaction(&nodes[1], &commitment_tx[0]);
2806 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2809 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2810 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2811 assert_eq!(node_txn[0], node_txn[3]);
2812 assert_eq!(node_txn[1], node_txn[4]);
2814 check_spends!(node_txn[2], commitment_tx[0]);
2815 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2817 check_spends!(node_txn[0], chan_2.3);
2818 check_spends!(node_txn[1], node_txn[0]);
2819 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2820 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2822 timeout_tx = node_txn[2].clone();
2826 mine_transaction(&nodes[1], &timeout_tx);
2827 check_added_monitors!(nodes[1], 1);
2828 check_closed_broadcast!(nodes[1], true);
2830 // B will rebroadcast a fee-bumped timeout transaction here.
2831 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2832 assert_eq!(node_txn.len(), 1);
2833 check_spends!(node_txn[0], commitment_tx[0]);
2836 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2838 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2839 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2840 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2841 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2842 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2843 if node_txn.len() == 1 {
2844 check_spends!(node_txn[0], chan_2.3);
2846 assert_eq!(node_txn.len(), 0);
2850 expect_pending_htlcs_forwardable!(nodes[1]);
2851 check_added_monitors!(nodes[1], 1);
2852 let events = nodes[1].node.get_and_clear_pending_msg_events();
2853 assert_eq!(events.len(), 1);
2855 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, .. } } => {
2856 assert!(update_add_htlcs.is_empty());
2857 assert!(!update_fail_htlcs.is_empty());
2858 assert!(update_fulfill_htlcs.is_empty());
2859 assert!(update_fail_malformed_htlcs.is_empty());
2860 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2862 _ => panic!("Unexpected event"),
2865 // Broadcast legit commitment tx from B on A's chain
2866 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2867 check_spends!(commitment_tx[0], chan_1.3);
2869 mine_transaction(&nodes[0], &commitment_tx[0]);
2870 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2872 check_closed_broadcast!(nodes[0], true);
2873 check_added_monitors!(nodes[0], 1);
2874 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2875 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2876 assert_eq!(node_txn.len(), 2);
2877 check_spends!(node_txn[0], chan_1.3);
2878 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2879 check_spends!(node_txn[1], commitment_tx[0]);
2880 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2884 fn test_htlc_on_chain_timeout() {
2885 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2886 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2887 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2891 fn test_simple_commitment_revoked_fail_backward() {
2892 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2893 // and fail backward accordingly.
2895 let chanmon_cfgs = create_chanmon_cfgs(3);
2896 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2897 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2898 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2900 // Create some initial channels
2901 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2902 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2904 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2905 // Get the will-be-revoked local txn from nodes[2]
2906 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2907 // Revoke the old state
2908 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2910 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2912 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2913 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2914 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2915 check_added_monitors!(nodes[1], 1);
2916 check_closed_broadcast!(nodes[1], true);
2918 expect_pending_htlcs_forwardable!(nodes[1]);
2919 check_added_monitors!(nodes[1], 1);
2920 let events = nodes[1].node.get_and_clear_pending_msg_events();
2921 assert_eq!(events.len(), 1);
2923 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, .. } } => {
2924 assert!(update_add_htlcs.is_empty());
2925 assert_eq!(update_fail_htlcs.len(), 1);
2926 assert!(update_fulfill_htlcs.is_empty());
2927 assert!(update_fail_malformed_htlcs.is_empty());
2928 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2930 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2931 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2932 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2934 _ => panic!("Unexpected event"),
2938 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2939 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2940 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2941 // commitment transaction anymore.
2942 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2943 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2944 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2945 // technically disallowed and we should probably handle it reasonably.
2946 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2947 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2949 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2950 // commitment_signed (implying it will be in the latest remote commitment transaction).
2951 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2952 // and once they revoke the previous commitment transaction (allowing us to send a new
2953 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2954 let chanmon_cfgs = create_chanmon_cfgs(3);
2955 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2956 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2957 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2959 // Create some initial channels
2960 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2961 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2963 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 });
2964 // Get the will-be-revoked local txn from nodes[2]
2965 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2966 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2967 // Revoke the old state
2968 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2970 let value = if use_dust {
2971 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2972 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2973 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2976 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2977 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2978 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2980 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2981 expect_pending_htlcs_forwardable!(nodes[2]);
2982 check_added_monitors!(nodes[2], 1);
2983 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2984 assert!(updates.update_add_htlcs.is_empty());
2985 assert!(updates.update_fulfill_htlcs.is_empty());
2986 assert!(updates.update_fail_malformed_htlcs.is_empty());
2987 assert_eq!(updates.update_fail_htlcs.len(), 1);
2988 assert!(updates.update_fee.is_none());
2989 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2990 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2991 // Drop the last RAA from 3 -> 2
2993 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2994 expect_pending_htlcs_forwardable!(nodes[2]);
2995 check_added_monitors!(nodes[2], 1);
2996 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2997 assert!(updates.update_add_htlcs.is_empty());
2998 assert!(updates.update_fulfill_htlcs.is_empty());
2999 assert!(updates.update_fail_malformed_htlcs.is_empty());
3000 assert_eq!(updates.update_fail_htlcs.len(), 1);
3001 assert!(updates.update_fee.is_none());
3002 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3003 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3004 check_added_monitors!(nodes[1], 1);
3005 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3006 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3007 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3008 check_added_monitors!(nodes[2], 1);
3010 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3011 expect_pending_htlcs_forwardable!(nodes[2]);
3012 check_added_monitors!(nodes[2], 1);
3013 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3014 assert!(updates.update_add_htlcs.is_empty());
3015 assert!(updates.update_fulfill_htlcs.is_empty());
3016 assert!(updates.update_fail_malformed_htlcs.is_empty());
3017 assert_eq!(updates.update_fail_htlcs.len(), 1);
3018 assert!(updates.update_fee.is_none());
3019 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3020 // At this point first_payment_hash has dropped out of the latest two commitment
3021 // transactions that nodes[1] is tracking...
3022 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3023 check_added_monitors!(nodes[1], 1);
3024 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3025 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3026 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3027 check_added_monitors!(nodes[2], 1);
3029 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3030 // on nodes[2]'s RAA.
3031 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3032 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3033 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3034 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3035 check_added_monitors!(nodes[1], 0);
3038 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3039 // One monitor for the new revocation preimage, no second on as we won't generate a new
3040 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3041 check_added_monitors!(nodes[1], 1);
3042 let events = nodes[1].node.get_and_clear_pending_events();
3043 assert_eq!(events.len(), 1);
3045 Event::PendingHTLCsForwardable { .. } => { },
3046 _ => panic!("Unexpected event"),
3048 // Deliberately don't process the pending fail-back so they all fail back at once after
3049 // block connection just like the !deliver_bs_raa case
3052 let mut failed_htlcs = HashSet::new();
3053 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3055 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3056 check_added_monitors!(nodes[1], 1);
3057 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3059 let events = nodes[1].node.get_and_clear_pending_events();
3060 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3062 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
3063 _ => panic!("Unexepected event"),
3066 Event::PaymentPathFailed { ref payment_hash, .. } => {
3067 assert_eq!(*payment_hash, fourth_payment_hash);
3069 _ => panic!("Unexpected event"),
3071 if !deliver_bs_raa {
3073 Event::PendingHTLCsForwardable { .. } => { },
3074 _ => panic!("Unexpected event"),
3077 nodes[1].node.process_pending_htlc_forwards();
3078 check_added_monitors!(nodes[1], 1);
3080 let events = nodes[1].node.get_and_clear_pending_msg_events();
3081 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3082 match events[if deliver_bs_raa { 1 } else { 0 }] {
3083 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3084 _ => panic!("Unexpected event"),
3086 match events[if deliver_bs_raa { 2 } else { 1 }] {
3087 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3088 assert_eq!(channel_id, chan_2.2);
3089 assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3091 _ => panic!("Unexpected event"),
3095 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, .. } } => {
3096 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3097 assert_eq!(update_add_htlcs.len(), 1);
3098 assert!(update_fulfill_htlcs.is_empty());
3099 assert!(update_fail_htlcs.is_empty());
3100 assert!(update_fail_malformed_htlcs.is_empty());
3102 _ => panic!("Unexpected event"),
3105 match events[if deliver_bs_raa { 3 } else { 2 }] {
3106 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, .. } } => {
3107 assert!(update_add_htlcs.is_empty());
3108 assert_eq!(update_fail_htlcs.len(), 3);
3109 assert!(update_fulfill_htlcs.is_empty());
3110 assert!(update_fail_malformed_htlcs.is_empty());
3111 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3113 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3114 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3115 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3117 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3119 let events = nodes[0].node.get_and_clear_pending_events();
3120 assert_eq!(events.len(), 3);
3122 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3123 assert!(failed_htlcs.insert(payment_hash.0));
3124 // If we delivered B's RAA we got an unknown preimage error, not something
3125 // that we should update our routing table for.
3126 if !deliver_bs_raa {
3127 assert!(network_update.is_some());
3130 _ => panic!("Unexpected event"),
3133 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3134 assert!(failed_htlcs.insert(payment_hash.0));
3135 assert!(network_update.is_some());
3137 _ => panic!("Unexpected event"),
3140 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3141 assert!(failed_htlcs.insert(payment_hash.0));
3142 assert!(network_update.is_some());
3144 _ => panic!("Unexpected event"),
3147 _ => panic!("Unexpected event"),
3150 assert!(failed_htlcs.contains(&first_payment_hash.0));
3151 assert!(failed_htlcs.contains(&second_payment_hash.0));
3152 assert!(failed_htlcs.contains(&third_payment_hash.0));
3156 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3157 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3158 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3159 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3160 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3164 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3165 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3166 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3167 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3168 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3172 fn fail_backward_pending_htlc_upon_channel_failure() {
3173 let chanmon_cfgs = create_chanmon_cfgs(2);
3174 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3175 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3176 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3177 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3179 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3181 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3182 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3183 check_added_monitors!(nodes[0], 1);
3185 let payment_event = {
3186 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3187 assert_eq!(events.len(), 1);
3188 SendEvent::from_event(events.remove(0))
3190 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3191 assert_eq!(payment_event.msgs.len(), 1);
3194 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3195 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3197 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3198 check_added_monitors!(nodes[0], 0);
3200 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3203 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3205 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3207 let secp_ctx = Secp256k1::new();
3208 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3209 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3210 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3211 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3212 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3214 // Send a 0-msat update_add_htlc to fail the channel.
3215 let update_add_htlc = msgs::UpdateAddHTLC {
3221 onion_routing_packet,
3223 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3225 let events = nodes[0].node.get_and_clear_pending_events();
3226 assert_eq!(events.len(), 2);
3227 // Check that Alice fails backward the pending HTLC from the second payment.
3229 Event::PaymentPathFailed { payment_hash, .. } => {
3230 assert_eq!(payment_hash, failed_payment_hash);
3232 _ => panic!("Unexpected event"),
3235 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3236 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3238 _ => panic!("Unexpected event {:?}", events[1]),
3240 check_closed_broadcast!(nodes[0], true);
3241 check_added_monitors!(nodes[0], 1);
3245 fn test_htlc_ignore_latest_remote_commitment() {
3246 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3247 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3248 let chanmon_cfgs = create_chanmon_cfgs(2);
3249 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3250 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3251 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3252 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3254 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3255 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3256 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3257 check_closed_broadcast!(nodes[0], true);
3258 check_added_monitors!(nodes[0], 1);
3259 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3261 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3262 assert_eq!(node_txn.len(), 3);
3263 assert_eq!(node_txn[0], node_txn[1]);
3265 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3266 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3267 check_closed_broadcast!(nodes[1], true);
3268 check_added_monitors!(nodes[1], 1);
3269 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3271 // Duplicate the connect_block call since this may happen due to other listeners
3272 // registering new transactions
3273 header.prev_blockhash = header.block_hash();
3274 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3278 fn test_force_close_fail_back() {
3279 // Check which HTLCs are failed-backwards on channel force-closure
3280 let chanmon_cfgs = create_chanmon_cfgs(3);
3281 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3282 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3283 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3284 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3285 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3287 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3289 let mut payment_event = {
3290 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3291 check_added_monitors!(nodes[0], 1);
3293 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3294 assert_eq!(events.len(), 1);
3295 SendEvent::from_event(events.remove(0))
3298 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3299 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3301 expect_pending_htlcs_forwardable!(nodes[1]);
3303 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3304 assert_eq!(events_2.len(), 1);
3305 payment_event = SendEvent::from_event(events_2.remove(0));
3306 assert_eq!(payment_event.msgs.len(), 1);
3308 check_added_monitors!(nodes[1], 1);
3309 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3310 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3311 check_added_monitors!(nodes[2], 1);
3312 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3314 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3315 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3316 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3318 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3319 check_closed_broadcast!(nodes[2], true);
3320 check_added_monitors!(nodes[2], 1);
3321 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3323 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3324 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3325 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3326 // back to nodes[1] upon timeout otherwise.
3327 assert_eq!(node_txn.len(), 1);
3331 mine_transaction(&nodes[1], &tx);
3333 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3334 check_closed_broadcast!(nodes[1], true);
3335 check_added_monitors!(nodes[1], 1);
3336 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3338 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3340 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3341 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3343 mine_transaction(&nodes[2], &tx);
3344 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3345 assert_eq!(node_txn.len(), 1);
3346 assert_eq!(node_txn[0].input.len(), 1);
3347 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3348 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3349 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3351 check_spends!(node_txn[0], tx);
3355 fn test_dup_events_on_peer_disconnect() {
3356 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3357 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3358 // as we used to generate the event immediately upon receipt of the payment preimage in the
3359 // update_fulfill_htlc message.
3361 let chanmon_cfgs = create_chanmon_cfgs(2);
3362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3364 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3365 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3367 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3369 assert!(nodes[1].node.claim_funds(payment_preimage));
3370 check_added_monitors!(nodes[1], 1);
3371 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3372 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3373 expect_payment_sent!(nodes[0], payment_preimage);
3375 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3376 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3378 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3379 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3383 fn test_simple_peer_disconnect() {
3384 // Test that we can reconnect when there are no lost messages
3385 let chanmon_cfgs = create_chanmon_cfgs(3);
3386 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3387 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3388 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3389 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3390 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3392 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3393 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3394 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3396 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3397 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3398 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3399 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3401 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3402 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3403 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3405 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3406 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3407 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3408 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3410 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3411 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3413 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3414 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3416 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3418 let events = nodes[0].node.get_and_clear_pending_events();
3419 assert_eq!(events.len(), 2);
3421 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3422 assert_eq!(payment_preimage, payment_preimage_3);
3423 assert_eq!(payment_hash, payment_hash_3);
3425 _ => panic!("Unexpected event"),
3428 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3429 assert_eq!(payment_hash, payment_hash_5);
3430 assert!(rejected_by_dest);
3432 _ => panic!("Unexpected event"),
3436 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3437 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3440 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3441 // Test that we can reconnect when in-flight HTLC updates get dropped
3442 let chanmon_cfgs = create_chanmon_cfgs(2);
3443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3445 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3447 let mut as_funding_locked = None;
3448 if messages_delivered == 0 {
3449 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3450 as_funding_locked = Some(funding_locked);
3451 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3452 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3453 // it before the channel_reestablish message.
3455 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3458 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3460 let payment_event = {
3461 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3462 check_added_monitors!(nodes[0], 1);
3464 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3465 assert_eq!(events.len(), 1);
3466 SendEvent::from_event(events.remove(0))
3468 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3470 if messages_delivered < 2 {
3471 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3473 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3474 if messages_delivered >= 3 {
3475 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3476 check_added_monitors!(nodes[1], 1);
3477 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3479 if messages_delivered >= 4 {
3480 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3481 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3482 check_added_monitors!(nodes[0], 1);
3484 if messages_delivered >= 5 {
3485 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3486 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3487 // No commitment_signed so get_event_msg's assert(len == 1) passes
3488 check_added_monitors!(nodes[0], 1);
3490 if messages_delivered >= 6 {
3491 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3492 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3493 check_added_monitors!(nodes[1], 1);
3500 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3501 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3502 if messages_delivered < 3 {
3503 if simulate_broken_lnd {
3504 // lnd has a long-standing bug where they send a funding_locked prior to a
3505 // channel_reestablish if you reconnect prior to funding_locked time.
3507 // Here we simulate that behavior, delivering a funding_locked immediately on
3508 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3509 // in `reconnect_nodes` but we currently don't fail based on that.
3511 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3512 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3514 // Even if the funding_locked messages get exchanged, as long as nothing further was
3515 // received on either side, both sides will need to resend them.
3516 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3517 } else if messages_delivered == 3 {
3518 // nodes[0] still wants its RAA + commitment_signed
3519 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3520 } else if messages_delivered == 4 {
3521 // nodes[0] still wants its commitment_signed
3522 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3523 } else if messages_delivered == 5 {
3524 // nodes[1] still wants its final RAA
3525 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3526 } else if messages_delivered == 6 {
3527 // Everything was delivered...
3528 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3531 let events_1 = nodes[1].node.get_and_clear_pending_events();
3532 assert_eq!(events_1.len(), 1);
3534 Event::PendingHTLCsForwardable { .. } => { },
3535 _ => panic!("Unexpected event"),
3538 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3539 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3540 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3542 nodes[1].node.process_pending_htlc_forwards();
3544 let events_2 = nodes[1].node.get_and_clear_pending_events();
3545 assert_eq!(events_2.len(), 1);
3547 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3548 assert_eq!(payment_hash_1, *payment_hash);
3549 assert_eq!(amt, 1000000);
3551 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3552 assert!(payment_preimage.is_none());
3553 assert_eq!(payment_secret_1, *payment_secret);
3555 _ => panic!("expected PaymentPurpose::InvoicePayment")
3558 _ => panic!("Unexpected event"),
3561 nodes[1].node.claim_funds(payment_preimage_1);
3562 check_added_monitors!(nodes[1], 1);
3564 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3565 assert_eq!(events_3.len(), 1);
3566 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3567 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3568 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3569 assert!(updates.update_add_htlcs.is_empty());
3570 assert!(updates.update_fail_htlcs.is_empty());
3571 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3572 assert!(updates.update_fail_malformed_htlcs.is_empty());
3573 assert!(updates.update_fee.is_none());
3574 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3576 _ => panic!("Unexpected event"),
3579 if messages_delivered >= 1 {
3580 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3582 let events_4 = nodes[0].node.get_and_clear_pending_events();
3583 assert_eq!(events_4.len(), 1);
3585 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3586 assert_eq!(payment_preimage_1, *payment_preimage);
3587 assert_eq!(payment_hash_1, *payment_hash);
3589 _ => panic!("Unexpected event"),
3592 if messages_delivered >= 2 {
3593 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3594 check_added_monitors!(nodes[0], 1);
3595 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3597 if messages_delivered >= 3 {
3598 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3599 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3600 check_added_monitors!(nodes[1], 1);
3602 if messages_delivered >= 4 {
3603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3604 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3605 // No commitment_signed so get_event_msg's assert(len == 1) passes
3606 check_added_monitors!(nodes[1], 1);
3608 if messages_delivered >= 5 {
3609 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3610 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3611 check_added_monitors!(nodes[0], 1);
3618 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3619 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3620 if messages_delivered < 2 {
3621 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3622 if messages_delivered < 1 {
3623 let events_4 = nodes[0].node.get_and_clear_pending_events();
3624 assert_eq!(events_4.len(), 1);
3626 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3627 assert_eq!(payment_preimage_1, *payment_preimage);
3628 assert_eq!(payment_hash_1, *payment_hash);
3630 _ => panic!("Unexpected event"),
3633 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3635 } else if messages_delivered == 2 {
3636 // nodes[0] still wants its RAA + commitment_signed
3637 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3638 } else if messages_delivered == 3 {
3639 // nodes[0] still wants its commitment_signed
3640 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3641 } else if messages_delivered == 4 {
3642 // nodes[1] still wants its final RAA
3643 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3644 } else if messages_delivered == 5 {
3645 // Everything was delivered...
3646 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3649 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3650 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3651 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3653 // Channel should still work fine...
3654 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3655 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3656 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3660 fn test_drop_messages_peer_disconnect_a() {
3661 do_test_drop_messages_peer_disconnect(0, true);
3662 do_test_drop_messages_peer_disconnect(0, false);
3663 do_test_drop_messages_peer_disconnect(1, false);
3664 do_test_drop_messages_peer_disconnect(2, false);
3668 fn test_drop_messages_peer_disconnect_b() {
3669 do_test_drop_messages_peer_disconnect(3, false);
3670 do_test_drop_messages_peer_disconnect(4, false);
3671 do_test_drop_messages_peer_disconnect(5, false);
3672 do_test_drop_messages_peer_disconnect(6, false);
3676 fn test_funding_peer_disconnect() {
3677 // Test that we can lock in our funding tx while disconnected
3678 let chanmon_cfgs = create_chanmon_cfgs(2);
3679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3681 let persister: test_utils::TestPersister;
3682 let new_chain_monitor: test_utils::TestChainMonitor;
3683 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3684 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3685 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3687 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3688 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3690 confirm_transaction(&nodes[0], &tx);
3691 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3693 assert_eq!(events_1.len(), 1);
3695 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3696 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3697 chan_id = msg.channel_id;
3699 _ => panic!("Unexpected event"),
3702 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3704 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3705 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3707 confirm_transaction(&nodes[1], &tx);
3708 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3709 assert_eq!(events_2.len(), 2);
3710 let funding_locked = match events_2[0] {
3711 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3712 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3715 _ => panic!("Unexpected event"),
3717 let bs_announcement_sigs = match events_2[1] {
3718 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3719 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3722 _ => panic!("Unexpected event"),
3725 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3727 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3728 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3729 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3730 assert_eq!(events_3.len(), 2);
3731 let as_announcement_sigs = match events_3[0] {
3732 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3733 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3736 _ => panic!("Unexpected event"),
3738 let (as_announcement, as_update) = match events_3[1] {
3739 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3740 (msg.clone(), update_msg.clone())
3742 _ => panic!("Unexpected event"),
3745 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3746 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3747 assert_eq!(events_4.len(), 1);
3748 let (_, bs_update) = match events_4[0] {
3749 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3750 (msg.clone(), update_msg.clone())
3752 _ => panic!("Unexpected event"),
3755 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3756 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3757 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3759 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3760 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3761 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3763 // Check that after deserialization and reconnection we can still generate an identical
3764 // channel_announcement from the cached signatures.
3765 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3767 let nodes_0_serialized = nodes[0].node.encode();
3768 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3769 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
3771 persister = test_utils::TestPersister::new();
3772 let keys_manager = &chanmon_cfgs[0].keys_manager;
3773 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);
3774 nodes[0].chain_monitor = &new_chain_monitor;
3775 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3776 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3777 &mut chan_0_monitor_read, keys_manager).unwrap();
3778 assert!(chan_0_monitor_read.is_empty());
3780 let mut nodes_0_read = &nodes_0_serialized[..];
3781 let (_, nodes_0_deserialized_tmp) = {
3782 let mut channel_monitors = HashMap::new();
3783 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3784 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3785 default_config: UserConfig::default(),
3787 fee_estimator: node_cfgs[0].fee_estimator,
3788 chain_monitor: nodes[0].chain_monitor,
3789 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3790 logger: nodes[0].logger,
3794 nodes_0_deserialized = nodes_0_deserialized_tmp;
3795 assert!(nodes_0_read.is_empty());
3797 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3798 nodes[0].node = &nodes_0_deserialized;
3799 check_added_monitors!(nodes[0], 1);
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3803 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3804 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3805 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3806 let mut found_announcement = false;
3807 for event in msgs.iter() {
3809 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3810 if *msg == as_announcement { found_announcement = true; }
3812 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3813 _ => panic!("Unexpected event"),
3816 assert!(found_announcement);
3820 fn test_drop_messages_peer_disconnect_dual_htlc() {
3821 // Test that we can handle reconnecting when both sides of a channel have pending
3822 // commitment_updates when we disconnect.
3823 let chanmon_cfgs = create_chanmon_cfgs(2);
3824 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3825 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3826 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3827 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3829 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3831 // Now try to send a second payment which will fail to send
3832 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3833 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3834 check_added_monitors!(nodes[0], 1);
3836 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3837 assert_eq!(events_1.len(), 1);
3839 MessageSendEvent::UpdateHTLCs { .. } => {},
3840 _ => panic!("Unexpected event"),
3843 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3844 check_added_monitors!(nodes[1], 1);
3846 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3847 assert_eq!(events_2.len(), 1);
3849 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 } } => {
3850 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3851 assert!(update_add_htlcs.is_empty());
3852 assert_eq!(update_fulfill_htlcs.len(), 1);
3853 assert!(update_fail_htlcs.is_empty());
3854 assert!(update_fail_malformed_htlcs.is_empty());
3855 assert!(update_fee.is_none());
3857 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3858 let events_3 = nodes[0].node.get_and_clear_pending_events();
3859 assert_eq!(events_3.len(), 1);
3861 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3862 assert_eq!(*payment_preimage, payment_preimage_1);
3863 assert_eq!(*payment_hash, payment_hash_1);
3865 _ => panic!("Unexpected event"),
3868 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3869 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3870 // No commitment_signed so get_event_msg's assert(len == 1) passes
3871 check_added_monitors!(nodes[0], 1);
3873 _ => panic!("Unexpected event"),
3876 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3877 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3879 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3880 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3881 assert_eq!(reestablish_1.len(), 1);
3882 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3883 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3884 assert_eq!(reestablish_2.len(), 1);
3886 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3887 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3888 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3889 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3891 assert!(as_resp.0.is_none());
3892 assert!(bs_resp.0.is_none());
3894 assert!(bs_resp.1.is_none());
3895 assert!(bs_resp.2.is_none());
3897 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3899 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3900 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3901 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3902 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3903 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3904 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3905 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3906 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3907 // No commitment_signed so get_event_msg's assert(len == 1) passes
3908 check_added_monitors!(nodes[1], 1);
3910 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3911 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3912 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3913 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3914 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3915 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3916 assert!(bs_second_commitment_signed.update_fee.is_none());
3917 check_added_monitors!(nodes[1], 1);
3919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3920 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3921 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3922 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3923 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3924 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3925 assert!(as_commitment_signed.update_fee.is_none());
3926 check_added_monitors!(nodes[0], 1);
3928 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3929 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3930 // No commitment_signed so get_event_msg's assert(len == 1) passes
3931 check_added_monitors!(nodes[0], 1);
3933 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3934 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3935 // No commitment_signed so get_event_msg's assert(len == 1) passes
3936 check_added_monitors!(nodes[1], 1);
3938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3939 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3940 check_added_monitors!(nodes[1], 1);
3942 expect_pending_htlcs_forwardable!(nodes[1]);
3944 let events_5 = nodes[1].node.get_and_clear_pending_events();
3945 assert_eq!(events_5.len(), 1);
3947 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3948 assert_eq!(payment_hash_2, *payment_hash);
3950 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3951 assert!(payment_preimage.is_none());
3952 assert_eq!(payment_secret_2, *payment_secret);
3954 _ => panic!("expected PaymentPurpose::InvoicePayment")
3957 _ => panic!("Unexpected event"),
3960 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3961 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3962 check_added_monitors!(nodes[0], 1);
3964 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3967 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3968 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3969 // to avoid our counterparty failing the channel.
3970 let chanmon_cfgs = create_chanmon_cfgs(2);
3971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3973 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3975 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3977 let our_payment_hash = if send_partial_mpp {
3978 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3979 // Use the utility function send_payment_along_path to send the payment with MPP data which
3980 // indicates there are more HTLCs coming.
3981 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.
3982 let payment_id = PaymentId([42; 32]);
3983 nodes[0].node.send_payment_along_path(&route.paths[0], &route.payee, &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3984 check_added_monitors!(nodes[0], 1);
3985 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3986 assert_eq!(events.len(), 1);
3987 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3988 // hop should *not* yet generate any PaymentReceived event(s).
3989 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3992 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3995 let mut block = Block {
3996 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3999 connect_block(&nodes[0], &block);
4000 connect_block(&nodes[1], &block);
4001 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4002 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4003 block.header.prev_blockhash = block.block_hash();
4004 connect_block(&nodes[0], &block);
4005 connect_block(&nodes[1], &block);
4008 expect_pending_htlcs_forwardable!(nodes[1]);
4010 check_added_monitors!(nodes[1], 1);
4011 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4012 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4013 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4014 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4015 assert!(htlc_timeout_updates.update_fee.is_none());
4017 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4018 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4019 // 100_000 msat as u64, followed by the height at which we failed back above
4020 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4021 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4022 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4026 fn test_htlc_timeout() {
4027 do_test_htlc_timeout(true);
4028 do_test_htlc_timeout(false);
4031 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4032 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4033 let chanmon_cfgs = create_chanmon_cfgs(3);
4034 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4035 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4036 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4037 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4038 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4040 // Make sure all nodes are at the same starting height
4041 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4042 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4043 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4045 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4046 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4048 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4050 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4051 check_added_monitors!(nodes[1], 1);
4053 // Now attempt to route a second payment, which should be placed in the holding cell
4054 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4055 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4056 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4058 check_added_monitors!(nodes[0], 1);
4059 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4060 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4061 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4062 expect_pending_htlcs_forwardable!(nodes[1]);
4064 check_added_monitors!(nodes[1], 0);
4066 connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4067 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4068 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4069 connect_blocks(&nodes[1], 1);
4072 expect_pending_htlcs_forwardable!(nodes[1]);
4073 check_added_monitors!(nodes[1], 1);
4074 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4075 assert_eq!(fail_commit.len(), 1);
4076 match fail_commit[0] {
4077 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4078 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4079 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4081 _ => unreachable!(),
4083 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4085 expect_payment_failed!(nodes[1], second_payment_hash, true);
4090 fn test_holding_cell_htlc_add_timeouts() {
4091 do_test_holding_cell_htlc_add_timeouts(false);
4092 do_test_holding_cell_htlc_add_timeouts(true);
4096 fn test_no_txn_manager_serialize_deserialize() {
4097 let chanmon_cfgs = create_chanmon_cfgs(2);
4098 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4099 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4100 let logger: test_utils::TestLogger;
4101 let fee_estimator: test_utils::TestFeeEstimator;
4102 let persister: test_utils::TestPersister;
4103 let new_chain_monitor: test_utils::TestChainMonitor;
4104 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4105 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4107 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4109 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4111 let nodes_0_serialized = nodes[0].node.encode();
4112 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4113 get_monitor!(nodes[0], OutPoint { txid: tx.txid(), index: 0 }.to_channel_id())
4114 .write(&mut chan_0_monitor_serialized).unwrap();
4116 logger = test_utils::TestLogger::new();
4117 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4118 persister = test_utils::TestPersister::new();
4119 let keys_manager = &chanmon_cfgs[0].keys_manager;
4120 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4121 nodes[0].chain_monitor = &new_chain_monitor;
4122 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4123 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4124 &mut chan_0_monitor_read, keys_manager).unwrap();
4125 assert!(chan_0_monitor_read.is_empty());
4127 let mut nodes_0_read = &nodes_0_serialized[..];
4128 let config = UserConfig::default();
4129 let (_, nodes_0_deserialized_tmp) = {
4130 let mut channel_monitors = HashMap::new();
4131 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4132 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4133 default_config: config,
4135 fee_estimator: &fee_estimator,
4136 chain_monitor: nodes[0].chain_monitor,
4137 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4142 nodes_0_deserialized = nodes_0_deserialized_tmp;
4143 assert!(nodes_0_read.is_empty());
4145 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4146 nodes[0].node = &nodes_0_deserialized;
4147 assert_eq!(nodes[0].node.list_channels().len(), 1);
4148 check_added_monitors!(nodes[0], 1);
4150 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4151 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4152 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4153 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4155 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4156 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4157 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4158 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4160 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4161 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4162 for node in nodes.iter() {
4163 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4164 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4165 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4168 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4172 fn test_manager_serialize_deserialize_events() {
4173 // This test makes sure the events field in ChannelManager survives de/serialization
4174 let chanmon_cfgs = create_chanmon_cfgs(2);
4175 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4176 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4177 let fee_estimator: test_utils::TestFeeEstimator;
4178 let persister: test_utils::TestPersister;
4179 let logger: test_utils::TestLogger;
4180 let new_chain_monitor: test_utils::TestChainMonitor;
4181 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4182 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4184 // Start creating a channel, but stop right before broadcasting the funding transaction
4185 let channel_value = 100000;
4186 let push_msat = 10001;
4187 let a_flags = InitFeatures::known();
4188 let b_flags = InitFeatures::known();
4189 let node_a = nodes.remove(0);
4190 let node_b = nodes.remove(0);
4191 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4192 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()));
4193 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()));
4195 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4197 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4198 check_added_monitors!(node_a, 0);
4200 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()));
4202 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4203 assert_eq!(added_monitors.len(), 1);
4204 assert_eq!(added_monitors[0].0, funding_output);
4205 added_monitors.clear();
4208 let bs_funding_signed = get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id());
4209 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &bs_funding_signed);
4211 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4212 assert_eq!(added_monitors.len(), 1);
4213 assert_eq!(added_monitors[0].0, funding_output);
4214 added_monitors.clear();
4216 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4221 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4222 let nodes_0_serialized = nodes[0].node.encode();
4223 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4224 get_monitor!(nodes[0], bs_funding_signed.channel_id).write(&mut chan_0_monitor_serialized).unwrap();
4226 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4227 logger = test_utils::TestLogger::new();
4228 persister = test_utils::TestPersister::new();
4229 let keys_manager = &chanmon_cfgs[0].keys_manager;
4230 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4231 nodes[0].chain_monitor = &new_chain_monitor;
4232 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4233 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4234 &mut chan_0_monitor_read, keys_manager).unwrap();
4235 assert!(chan_0_monitor_read.is_empty());
4237 let mut nodes_0_read = &nodes_0_serialized[..];
4238 let config = UserConfig::default();
4239 let (_, nodes_0_deserialized_tmp) = {
4240 let mut channel_monitors = HashMap::new();
4241 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4242 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4243 default_config: config,
4245 fee_estimator: &fee_estimator,
4246 chain_monitor: nodes[0].chain_monitor,
4247 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4252 nodes_0_deserialized = nodes_0_deserialized_tmp;
4253 assert!(nodes_0_read.is_empty());
4255 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4257 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4258 nodes[0].node = &nodes_0_deserialized;
4260 // After deserializing, make sure the funding_transaction is still held by the channel manager
4261 let events_4 = nodes[0].node.get_and_clear_pending_events();
4262 assert_eq!(events_4.len(), 0);
4263 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4264 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4266 // Make sure the channel is functioning as though the de/serialization never happened
4267 assert_eq!(nodes[0].node.list_channels().len(), 1);
4268 check_added_monitors!(nodes[0], 1);
4270 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4271 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4272 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4273 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4275 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4276 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4277 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4278 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4280 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4281 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4282 for node in nodes.iter() {
4283 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4284 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4285 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4288 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4292 fn test_simple_manager_serialize_deserialize() {
4293 let chanmon_cfgs = create_chanmon_cfgs(2);
4294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4296 let logger: test_utils::TestLogger;
4297 let fee_estimator: test_utils::TestFeeEstimator;
4298 let persister: test_utils::TestPersister;
4299 let new_chain_monitor: test_utils::TestChainMonitor;
4300 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4301 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4302 let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4304 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4305 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4307 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4309 let nodes_0_serialized = nodes[0].node.encode();
4310 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4311 get_monitor!(nodes[0], chan_id).write(&mut chan_0_monitor_serialized).unwrap();
4313 logger = test_utils::TestLogger::new();
4314 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4315 persister = test_utils::TestPersister::new();
4316 let keys_manager = &chanmon_cfgs[0].keys_manager;
4317 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4318 nodes[0].chain_monitor = &new_chain_monitor;
4319 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4320 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4321 &mut chan_0_monitor_read, keys_manager).unwrap();
4322 assert!(chan_0_monitor_read.is_empty());
4324 let mut nodes_0_read = &nodes_0_serialized[..];
4325 let (_, nodes_0_deserialized_tmp) = {
4326 let mut channel_monitors = HashMap::new();
4327 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4328 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4329 default_config: UserConfig::default(),
4331 fee_estimator: &fee_estimator,
4332 chain_monitor: nodes[0].chain_monitor,
4333 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4338 nodes_0_deserialized = nodes_0_deserialized_tmp;
4339 assert!(nodes_0_read.is_empty());
4341 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4342 nodes[0].node = &nodes_0_deserialized;
4343 check_added_monitors!(nodes[0], 1);
4345 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4347 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4348 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4352 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4353 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4354 let chanmon_cfgs = create_chanmon_cfgs(4);
4355 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4356 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4357 let logger: test_utils::TestLogger;
4358 let fee_estimator: test_utils::TestFeeEstimator;
4359 let persister: test_utils::TestPersister;
4360 let new_chain_monitor: test_utils::TestChainMonitor;
4361 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4362 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4363 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
4364 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known()).2;
4365 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4367 let mut node_0_stale_monitors_serialized = Vec::new();
4368 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4369 let mut writer = test_utils::TestVecWriter(Vec::new());
4370 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4371 node_0_stale_monitors_serialized.push(writer.0);
4374 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4376 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4377 let nodes_0_serialized = nodes[0].node.encode();
4379 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4380 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4381 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4382 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4384 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4386 let mut node_0_monitors_serialized = Vec::new();
4387 for chan_id_iter in &[chan_id_1, chan_id_2, channel_id] {
4388 let mut writer = test_utils::TestVecWriter(Vec::new());
4389 get_monitor!(nodes[0], chan_id_iter).write(&mut writer).unwrap();
4390 node_0_monitors_serialized.push(writer.0);
4393 logger = test_utils::TestLogger::new();
4394 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4395 persister = test_utils::TestPersister::new();
4396 let keys_manager = &chanmon_cfgs[0].keys_manager;
4397 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4398 nodes[0].chain_monitor = &new_chain_monitor;
4401 let mut node_0_stale_monitors = Vec::new();
4402 for serialized in node_0_stale_monitors_serialized.iter() {
4403 let mut read = &serialized[..];
4404 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4405 assert!(read.is_empty());
4406 node_0_stale_monitors.push(monitor);
4409 let mut node_0_monitors = Vec::new();
4410 for serialized in node_0_monitors_serialized.iter() {
4411 let mut read = &serialized[..];
4412 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4413 assert!(read.is_empty());
4414 node_0_monitors.push(monitor);
4417 let mut nodes_0_read = &nodes_0_serialized[..];
4418 if let Err(msgs::DecodeError::InvalidValue) =
4419 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4420 default_config: UserConfig::default(),
4422 fee_estimator: &fee_estimator,
4423 chain_monitor: nodes[0].chain_monitor,
4424 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4426 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4428 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4431 let mut nodes_0_read = &nodes_0_serialized[..];
4432 let (_, nodes_0_deserialized_tmp) =
4433 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4434 default_config: UserConfig::default(),
4436 fee_estimator: &fee_estimator,
4437 chain_monitor: nodes[0].chain_monitor,
4438 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4440 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4442 nodes_0_deserialized = nodes_0_deserialized_tmp;
4443 assert!(nodes_0_read.is_empty());
4445 { // Channel close should result in a commitment tx
4446 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4447 assert_eq!(txn.len(), 1);
4448 check_spends!(txn[0], funding_tx);
4449 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4452 for monitor in node_0_monitors.drain(..) {
4453 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4454 check_added_monitors!(nodes[0], 1);
4456 nodes[0].node = &nodes_0_deserialized;
4457 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4459 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4460 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4461 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4462 //... and we can even still claim the payment!
4463 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4465 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4466 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4467 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4468 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4469 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4470 assert_eq!(msg_events.len(), 1);
4471 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4473 &ErrorAction::SendErrorMessage { ref msg } => {
4474 assert_eq!(msg.channel_id, channel_id);
4476 _ => panic!("Unexpected event!"),
4481 macro_rules! check_spendable_outputs {
4482 ($node: expr, $keysinterface: expr) => {
4484 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4485 let mut txn = Vec::new();
4486 let mut all_outputs = Vec::new();
4487 let secp_ctx = Secp256k1::new();
4488 for event in events.drain(..) {
4490 Event::SpendableOutputs { mut outputs } => {
4491 for outp in outputs.drain(..) {
4492 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4493 all_outputs.push(outp);
4496 _ => panic!("Unexpected event"),
4499 if all_outputs.len() > 1 {
4500 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) {
4510 fn test_claim_sizeable_push_msat() {
4511 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4512 let chanmon_cfgs = create_chanmon_cfgs(2);
4513 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4514 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4515 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4517 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4518 nodes[1].node.force_close_channel(&chan.2).unwrap();
4519 check_closed_broadcast!(nodes[1], true);
4520 check_added_monitors!(nodes[1], 1);
4521 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4522 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4523 assert_eq!(node_txn.len(), 1);
4524 check_spends!(node_txn[0], chan.3);
4525 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
4527 mine_transaction(&nodes[1], &node_txn[0]);
4528 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4530 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4531 assert_eq!(spend_txn.len(), 1);
4532 assert_eq!(spend_txn[0].input.len(), 1);
4533 check_spends!(spend_txn[0], node_txn[0]);
4534 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4538 fn test_claim_on_remote_sizeable_push_msat() {
4539 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4540 // to_remote output is encumbered by a P2WPKH
4541 let chanmon_cfgs = create_chanmon_cfgs(2);
4542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4544 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4546 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000, InitFeatures::known(), InitFeatures::known());
4547 nodes[0].node.force_close_channel(&chan.2).unwrap();
4548 check_closed_broadcast!(nodes[0], true);
4549 check_added_monitors!(nodes[0], 1);
4550 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4552 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4553 assert_eq!(node_txn.len(), 1);
4554 check_spends!(node_txn[0], chan.3);
4555 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
4557 mine_transaction(&nodes[1], &node_txn[0]);
4558 check_closed_broadcast!(nodes[1], true);
4559 check_added_monitors!(nodes[1], 1);
4560 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4561 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4563 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4564 assert_eq!(spend_txn.len(), 1);
4565 check_spends!(spend_txn[0], node_txn[0]);
4569 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4570 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4571 // to_remote output is encumbered by a P2WPKH
4573 let chanmon_cfgs = create_chanmon_cfgs(2);
4574 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4575 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4576 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4578 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4579 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4580 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4581 assert_eq!(revoked_local_txn[0].input.len(), 1);
4582 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4584 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4585 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4586 check_closed_broadcast!(nodes[1], true);
4587 check_added_monitors!(nodes[1], 1);
4588 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4590 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4591 mine_transaction(&nodes[1], &node_txn[0]);
4592 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4594 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4595 assert_eq!(spend_txn.len(), 3);
4596 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4597 check_spends!(spend_txn[1], node_txn[0]);
4598 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4602 fn test_static_spendable_outputs_preimage_tx() {
4603 let chanmon_cfgs = create_chanmon_cfgs(2);
4604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4606 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4608 // Create some initial channels
4609 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4611 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4613 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4614 assert_eq!(commitment_tx[0].input.len(), 1);
4615 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4617 // Settle A's commitment tx on B's chain
4618 assert!(nodes[1].node.claim_funds(payment_preimage));
4619 check_added_monitors!(nodes[1], 1);
4620 mine_transaction(&nodes[1], &commitment_tx[0]);
4621 check_added_monitors!(nodes[1], 1);
4622 let events = nodes[1].node.get_and_clear_pending_msg_events();
4624 MessageSendEvent::UpdateHTLCs { .. } => {},
4625 _ => panic!("Unexpected event"),
4628 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4629 _ => panic!("Unexepected event"),
4632 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4633 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4634 assert_eq!(node_txn.len(), 3);
4635 check_spends!(node_txn[0], commitment_tx[0]);
4636 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4637 check_spends!(node_txn[1], chan_1.3);
4638 check_spends!(node_txn[2], node_txn[1]);
4640 mine_transaction(&nodes[1], &node_txn[0]);
4641 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4642 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4644 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4645 assert_eq!(spend_txn.len(), 1);
4646 check_spends!(spend_txn[0], node_txn[0]);
4650 fn test_static_spendable_outputs_timeout_tx() {
4651 let chanmon_cfgs = create_chanmon_cfgs(2);
4652 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4653 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4654 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4656 // Create some initial channels
4657 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4659 // Rebalance the network a bit by relaying one payment through all the channels ...
4660 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4662 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4664 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4665 assert_eq!(commitment_tx[0].input.len(), 1);
4666 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4668 // Settle A's commitment tx on B' chain
4669 mine_transaction(&nodes[1], &commitment_tx[0]);
4670 check_added_monitors!(nodes[1], 1);
4671 let events = nodes[1].node.get_and_clear_pending_msg_events();
4673 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4674 _ => panic!("Unexpected event"),
4676 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4678 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4679 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4680 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4681 check_spends!(node_txn[0], chan_1.3.clone());
4682 check_spends!(node_txn[1], commitment_tx[0].clone());
4683 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4685 mine_transaction(&nodes[1], &node_txn[1]);
4686 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4687 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4688 expect_payment_failed!(nodes[1], our_payment_hash, true);
4690 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4691 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4692 check_spends!(spend_txn[0], commitment_tx[0]);
4693 check_spends!(spend_txn[1], node_txn[1]);
4694 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4698 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4699 let chanmon_cfgs = create_chanmon_cfgs(2);
4700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4704 // Create some initial channels
4705 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4707 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4708 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4709 assert_eq!(revoked_local_txn[0].input.len(), 1);
4710 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4712 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4714 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4715 check_closed_broadcast!(nodes[1], true);
4716 check_added_monitors!(nodes[1], 1);
4717 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4719 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4720 assert_eq!(node_txn.len(), 2);
4721 assert_eq!(node_txn[0].input.len(), 2);
4722 check_spends!(node_txn[0], revoked_local_txn[0]);
4724 mine_transaction(&nodes[1], &node_txn[0]);
4725 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4727 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4728 assert_eq!(spend_txn.len(), 1);
4729 check_spends!(spend_txn[0], node_txn[0]);
4733 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4734 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4735 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4736 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4737 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4738 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4740 // Create some initial channels
4741 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4743 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4744 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4745 assert_eq!(revoked_local_txn[0].input.len(), 1);
4746 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4748 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4750 // A will generate HTLC-Timeout from revoked commitment tx
4751 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4752 check_closed_broadcast!(nodes[0], true);
4753 check_added_monitors!(nodes[0], 1);
4754 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4755 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4757 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4758 assert_eq!(revoked_htlc_txn.len(), 2);
4759 check_spends!(revoked_htlc_txn[0], chan_1.3);
4760 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4761 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4762 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4763 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4765 // B will generate justice tx from A's revoked commitment/HTLC tx
4766 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4767 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4768 check_closed_broadcast!(nodes[1], true);
4769 check_added_monitors!(nodes[1], 1);
4770 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4772 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4773 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4774 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4775 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4776 // transactions next...
4777 assert_eq!(node_txn[0].input.len(), 3);
4778 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4780 assert_eq!(node_txn[1].input.len(), 2);
4781 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4782 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4783 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4785 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4786 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4789 assert_eq!(node_txn[2].input.len(), 1);
4790 check_spends!(node_txn[2], chan_1.3);
4792 mine_transaction(&nodes[1], &node_txn[1]);
4793 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4795 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4796 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4797 assert_eq!(spend_txn.len(), 1);
4798 assert_eq!(spend_txn[0].input.len(), 1);
4799 check_spends!(spend_txn[0], node_txn[1]);
4803 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4804 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4805 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4806 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4807 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4808 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4810 // Create some initial channels
4811 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4813 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4814 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4815 assert_eq!(revoked_local_txn[0].input.len(), 1);
4816 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4818 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4819 assert_eq!(revoked_local_txn[0].output.len(), 2);
4821 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4823 // B will generate HTLC-Success from revoked commitment tx
4824 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4825 check_closed_broadcast!(nodes[1], true);
4826 check_added_monitors!(nodes[1], 1);
4827 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4828 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4830 assert_eq!(revoked_htlc_txn.len(), 2);
4831 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4832 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4833 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4835 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4836 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4837 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4839 // A will generate justice tx from B's revoked commitment/HTLC tx
4840 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4841 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4842 check_closed_broadcast!(nodes[0], true);
4843 check_added_monitors!(nodes[0], 1);
4844 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4846 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4847 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4849 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4850 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4851 // transactions next...
4852 assert_eq!(node_txn[0].input.len(), 2);
4853 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4854 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4855 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4857 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4858 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4861 assert_eq!(node_txn[1].input.len(), 1);
4862 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4864 check_spends!(node_txn[2], chan_1.3);
4866 mine_transaction(&nodes[0], &node_txn[1]);
4867 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4869 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4870 // didn't try to generate any new transactions.
4872 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4873 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4874 assert_eq!(spend_txn.len(), 3);
4875 assert_eq!(spend_txn[0].input.len(), 1);
4876 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4877 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4878 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4879 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4883 fn test_onchain_to_onchain_claim() {
4884 // Test that in case of channel closure, we detect the state of output and claim HTLC
4885 // on downstream peer's remote commitment tx.
4886 // First, have C claim an HTLC against its own latest commitment transaction.
4887 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4889 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4892 let chanmon_cfgs = create_chanmon_cfgs(3);
4893 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4894 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4895 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4897 // Create some initial channels
4898 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4899 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4901 // Ensure all nodes are at the same height
4902 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4903 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4904 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4905 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4907 // Rebalance the network a bit by relaying one payment through all the channels ...
4908 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4909 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4911 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4912 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4913 check_spends!(commitment_tx[0], chan_2.3);
4914 nodes[2].node.claim_funds(payment_preimage);
4915 check_added_monitors!(nodes[2], 1);
4916 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4917 assert!(updates.update_add_htlcs.is_empty());
4918 assert!(updates.update_fail_htlcs.is_empty());
4919 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4920 assert!(updates.update_fail_malformed_htlcs.is_empty());
4922 mine_transaction(&nodes[2], &commitment_tx[0]);
4923 check_closed_broadcast!(nodes[2], true);
4924 check_added_monitors!(nodes[2], 1);
4925 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4927 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4928 assert_eq!(c_txn.len(), 3);
4929 assert_eq!(c_txn[0], c_txn[2]);
4930 assert_eq!(commitment_tx[0], c_txn[1]);
4931 check_spends!(c_txn[1], chan_2.3);
4932 check_spends!(c_txn[2], c_txn[1]);
4933 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4934 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4935 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4936 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4938 // 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
4939 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4940 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4941 check_added_monitors!(nodes[1], 1);
4942 let events = nodes[1].node.get_and_clear_pending_events();
4943 assert_eq!(events.len(), 2);
4945 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4946 _ => panic!("Unexpected event"),
4949 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
4950 assert_eq!(fee_earned_msat, Some(1000));
4951 assert_eq!(claim_from_onchain_tx, true);
4953 _ => panic!("Unexpected event"),
4956 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4957 // ChannelMonitor: claim tx
4958 assert_eq!(b_txn.len(), 1);
4959 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4962 check_added_monitors!(nodes[1], 1);
4963 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4964 assert_eq!(msg_events.len(), 3);
4965 match msg_events[0] {
4966 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4967 _ => panic!("Unexpected event"),
4969 match msg_events[1] {
4970 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
4971 _ => panic!("Unexpected event"),
4973 match msg_events[2] {
4974 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, .. } } => {
4975 assert!(update_add_htlcs.is_empty());
4976 assert!(update_fail_htlcs.is_empty());
4977 assert_eq!(update_fulfill_htlcs.len(), 1);
4978 assert!(update_fail_malformed_htlcs.is_empty());
4979 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4981 _ => panic!("Unexpected event"),
4983 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4984 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4985 mine_transaction(&nodes[1], &commitment_tx[0]);
4986 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4987 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4988 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4989 assert_eq!(b_txn.len(), 3);
4990 check_spends!(b_txn[1], chan_1.3);
4991 check_spends!(b_txn[2], b_txn[1]);
4992 check_spends!(b_txn[0], commitment_tx[0]);
4993 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4994 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4995 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4997 check_closed_broadcast!(nodes[1], true);
4998 check_added_monitors!(nodes[1], 1);
5002 fn test_duplicate_payment_hash_one_failure_one_success() {
5003 // Topology : A --> B --> C --> D
5004 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5005 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5006 // we forward one of the payments onwards to D.
5007 let chanmon_cfgs = create_chanmon_cfgs(4);
5008 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5009 // When this test was written, the default base fee floated based on the HTLC count.
5010 // It is now fixed, so we simply set the fee to the expected value here.
5011 let mut config = test_default_channel_config();
5012 config.channel_options.forwarding_fee_base_msat = 196;
5013 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5014 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5015 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5017 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5018 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5019 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5021 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5022 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5023 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5024 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5025 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5027 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5029 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200).unwrap();
5030 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5031 // script push size limit so that the below script length checks match
5032 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5033 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5034 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5036 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5037 assert_eq!(commitment_txn[0].input.len(), 1);
5038 check_spends!(commitment_txn[0], chan_2.3);
5040 mine_transaction(&nodes[1], &commitment_txn[0]);
5041 check_closed_broadcast!(nodes[1], true);
5042 check_added_monitors!(nodes[1], 1);
5043 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5044 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5046 let htlc_timeout_tx;
5047 { // Extract one of the two HTLC-Timeout transaction
5048 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5049 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5050 assert_eq!(node_txn.len(), 4);
5051 check_spends!(node_txn[0], chan_2.3);
5053 check_spends!(node_txn[1], commitment_txn[0]);
5054 assert_eq!(node_txn[1].input.len(), 1);
5055 check_spends!(node_txn[2], commitment_txn[0]);
5056 assert_eq!(node_txn[2].input.len(), 1);
5057 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5058 check_spends!(node_txn[3], commitment_txn[0]);
5059 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5061 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5062 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5063 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5064 htlc_timeout_tx = node_txn[1].clone();
5067 nodes[2].node.claim_funds(our_payment_preimage);
5068 mine_transaction(&nodes[2], &commitment_txn[0]);
5069 check_added_monitors!(nodes[2], 2);
5070 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5071 let events = nodes[2].node.get_and_clear_pending_msg_events();
5073 MessageSendEvent::UpdateHTLCs { .. } => {},
5074 _ => panic!("Unexpected event"),
5077 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5078 _ => panic!("Unexepected event"),
5080 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5081 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)
5082 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5083 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5084 assert_eq!(htlc_success_txn[0].input.len(), 1);
5085 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5086 assert_eq!(htlc_success_txn[1].input.len(), 1);
5087 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5088 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5089 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5090 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5091 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5092 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5094 mine_transaction(&nodes[1], &htlc_timeout_tx);
5095 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5096 expect_pending_htlcs_forwardable!(nodes[1]);
5097 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5098 assert!(htlc_updates.update_add_htlcs.is_empty());
5099 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5100 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5101 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5102 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5103 check_added_monitors!(nodes[1], 1);
5105 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5106 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5108 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5110 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5112 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5113 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5114 // and nodes[2] fee) is rounded down and then claimed in full.
5115 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5116 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5117 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5118 assert!(updates.update_add_htlcs.is_empty());
5119 assert!(updates.update_fail_htlcs.is_empty());
5120 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5121 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5122 assert!(updates.update_fail_malformed_htlcs.is_empty());
5123 check_added_monitors!(nodes[1], 1);
5125 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5126 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5128 let events = nodes[0].node.get_and_clear_pending_events();
5130 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
5131 assert_eq!(*payment_preimage, our_payment_preimage);
5132 assert_eq!(*payment_hash, duplicate_payment_hash);
5134 _ => panic!("Unexpected event"),
5139 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5140 let chanmon_cfgs = create_chanmon_cfgs(2);
5141 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5142 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5143 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5145 // Create some initial channels
5146 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5148 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5149 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5150 assert_eq!(local_txn.len(), 1);
5151 assert_eq!(local_txn[0].input.len(), 1);
5152 check_spends!(local_txn[0], chan_1.3);
5154 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5155 nodes[1].node.claim_funds(payment_preimage);
5156 check_added_monitors!(nodes[1], 1);
5157 mine_transaction(&nodes[1], &local_txn[0]);
5158 check_added_monitors!(nodes[1], 1);
5159 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5160 let events = nodes[1].node.get_and_clear_pending_msg_events();
5162 MessageSendEvent::UpdateHTLCs { .. } => {},
5163 _ => panic!("Unexpected event"),
5166 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5167 _ => panic!("Unexepected event"),
5170 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5171 assert_eq!(node_txn.len(), 3);
5172 assert_eq!(node_txn[0], node_txn[2]);
5173 assert_eq!(node_txn[1], local_txn[0]);
5174 assert_eq!(node_txn[0].input.len(), 1);
5175 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5176 check_spends!(node_txn[0], local_txn[0]);
5180 mine_transaction(&nodes[1], &node_tx);
5181 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5183 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5184 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5185 assert_eq!(spend_txn.len(), 1);
5186 assert_eq!(spend_txn[0].input.len(), 1);
5187 check_spends!(spend_txn[0], node_tx);
5188 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5191 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5192 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5193 // unrevoked commitment transaction.
5194 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5195 // a remote RAA before they could be failed backwards (and combinations thereof).
5196 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5197 // use the same payment hashes.
5198 // Thus, we use a six-node network:
5203 // And test where C fails back to A/B when D announces its latest commitment transaction
5204 let chanmon_cfgs = create_chanmon_cfgs(6);
5205 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5206 // When this test was written, the default base fee floated based on the HTLC count.
5207 // It is now fixed, so we simply set the fee to the expected value here.
5208 let mut config = test_default_channel_config();
5209 config.channel_options.forwarding_fee_base_msat = 196;
5210 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5211 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5212 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5214 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5215 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5216 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5217 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5218 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5220 // Rebalance and check output sanity...
5221 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5222 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5223 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5225 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5227 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
5229 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
5230 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5232 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).unwrap()); // not added < dust limit + HTLC tx fee
5234 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).unwrap()); // not added < dust limit + HTLC tx fee
5236 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5238 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5239 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5241 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).unwrap());
5243 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).unwrap());
5246 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5248 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5249 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).unwrap()); // not added < dust limit + HTLC tx fee
5252 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
5254 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5255 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).unwrap());
5257 // Double-check that six of the new HTLC were added
5258 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5259 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5260 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5261 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5263 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5264 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5265 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5266 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5267 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5268 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5269 check_added_monitors!(nodes[4], 0);
5270 expect_pending_htlcs_forwardable!(nodes[4]);
5271 check_added_monitors!(nodes[4], 1);
5273 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5274 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5275 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5276 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5277 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5278 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5280 // Fail 3rd below-dust and 7th above-dust HTLCs
5281 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5282 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5283 check_added_monitors!(nodes[5], 0);
5284 expect_pending_htlcs_forwardable!(nodes[5]);
5285 check_added_monitors!(nodes[5], 1);
5287 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5288 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5289 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5290 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5292 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5294 expect_pending_htlcs_forwardable!(nodes[3]);
5295 check_added_monitors!(nodes[3], 1);
5296 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5297 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5298 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5299 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5300 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5301 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5302 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5303 if deliver_last_raa {
5304 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5306 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5309 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5310 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5311 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5312 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5314 // We now broadcast the latest commitment transaction, which *should* result in failures for
5315 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5316 // the non-broadcast above-dust HTLCs.
5318 // Alternatively, we may broadcast the previous commitment transaction, which should only
5319 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5320 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5322 if announce_latest {
5323 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5325 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5327 let events = nodes[2].node.get_and_clear_pending_events();
5328 let close_event = if deliver_last_raa {
5329 assert_eq!(events.len(), 2);
5332 assert_eq!(events.len(), 1);
5336 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5337 _ => panic!("Unexpected event"),
5340 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5341 check_closed_broadcast!(nodes[2], true);
5342 if deliver_last_raa {
5343 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5345 expect_pending_htlcs_forwardable!(nodes[2]);
5347 check_added_monitors!(nodes[2], 3);
5349 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5350 assert_eq!(cs_msgs.len(), 2);
5351 let mut a_done = false;
5352 for msg in cs_msgs {
5354 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5355 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5356 // should be failed-backwards here.
5357 let target = if *node_id == nodes[0].node.get_our_node_id() {
5358 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5359 for htlc in &updates.update_fail_htlcs {
5360 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 });
5362 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5367 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5368 for htlc in &updates.update_fail_htlcs {
5369 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5371 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5372 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5375 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5376 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5377 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5378 if announce_latest {
5379 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5380 if *node_id == nodes[0].node.get_our_node_id() {
5381 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5384 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5386 _ => panic!("Unexpected event"),
5390 let as_events = nodes[0].node.get_and_clear_pending_events();
5391 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5392 let mut as_failds = HashSet::new();
5393 let mut as_updates = 0;
5394 for event in as_events.iter() {
5395 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5396 assert!(as_failds.insert(*payment_hash));
5397 if *payment_hash != payment_hash_2 {
5398 assert_eq!(*rejected_by_dest, deliver_last_raa);
5400 assert!(!rejected_by_dest);
5402 if network_update.is_some() {
5405 } else { panic!("Unexpected event"); }
5407 assert!(as_failds.contains(&payment_hash_1));
5408 assert!(as_failds.contains(&payment_hash_2));
5409 if announce_latest {
5410 assert!(as_failds.contains(&payment_hash_3));
5411 assert!(as_failds.contains(&payment_hash_5));
5413 assert!(as_failds.contains(&payment_hash_6));
5415 let bs_events = nodes[1].node.get_and_clear_pending_events();
5416 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5417 let mut bs_failds = HashSet::new();
5418 let mut bs_updates = 0;
5419 for event in bs_events.iter() {
5420 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5421 assert!(bs_failds.insert(*payment_hash));
5422 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5423 assert_eq!(*rejected_by_dest, deliver_last_raa);
5425 assert!(!rejected_by_dest);
5427 if network_update.is_some() {
5430 } else { panic!("Unexpected event"); }
5432 assert!(bs_failds.contains(&payment_hash_1));
5433 assert!(bs_failds.contains(&payment_hash_2));
5434 if announce_latest {
5435 assert!(bs_failds.contains(&payment_hash_4));
5437 assert!(bs_failds.contains(&payment_hash_5));
5439 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5440 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5441 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5442 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5443 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5444 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5448 fn test_fail_backwards_latest_remote_announce_a() {
5449 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5453 fn test_fail_backwards_latest_remote_announce_b() {
5454 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5458 fn test_fail_backwards_previous_remote_announce() {
5459 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5460 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5461 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5465 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5466 let chanmon_cfgs = create_chanmon_cfgs(2);
5467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5471 // Create some initial channels
5472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5474 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5475 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5476 assert_eq!(local_txn[0].input.len(), 1);
5477 check_spends!(local_txn[0], chan_1.3);
5479 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5480 mine_transaction(&nodes[0], &local_txn[0]);
5481 check_closed_broadcast!(nodes[0], true);
5482 check_added_monitors!(nodes[0], 1);
5483 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5484 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5486 let htlc_timeout = {
5487 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5488 assert_eq!(node_txn.len(), 2);
5489 check_spends!(node_txn[0], chan_1.3);
5490 assert_eq!(node_txn[1].input.len(), 1);
5491 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5492 check_spends!(node_txn[1], local_txn[0]);
5496 mine_transaction(&nodes[0], &htlc_timeout);
5497 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5498 expect_payment_failed!(nodes[0], our_payment_hash, true);
5500 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5501 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5502 assert_eq!(spend_txn.len(), 3);
5503 check_spends!(spend_txn[0], local_txn[0]);
5504 assert_eq!(spend_txn[1].input.len(), 1);
5505 check_spends!(spend_txn[1], htlc_timeout);
5506 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5507 assert_eq!(spend_txn[2].input.len(), 2);
5508 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5509 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5510 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5514 fn test_key_derivation_params() {
5515 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5516 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5517 // let us re-derive the channel key set to then derive a delayed_payment_key.
5519 let chanmon_cfgs = create_chanmon_cfgs(3);
5521 // We manually create the node configuration to backup the seed.
5522 let seed = [42; 32];
5523 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5524 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);
5525 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, network_graph: &chanmon_cfgs[0].network_graph, node_seed: seed, features: InitFeatures::known() };
5526 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5527 node_cfgs.remove(0);
5528 node_cfgs.insert(0, node);
5530 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5531 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5533 // Create some initial channels
5534 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5536 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5537 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5538 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5540 // Ensure all nodes are at the same height
5541 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5542 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5543 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5544 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5546 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5547 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5548 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5549 assert_eq!(local_txn_1[0].input.len(), 1);
5550 check_spends!(local_txn_1[0], chan_1.3);
5552 // We check funding pubkey are unique
5553 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]));
5554 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]));
5555 if from_0_funding_key_0 == from_1_funding_key_0
5556 || from_0_funding_key_0 == from_1_funding_key_1
5557 || from_0_funding_key_1 == from_1_funding_key_0
5558 || from_0_funding_key_1 == from_1_funding_key_1 {
5559 panic!("Funding pubkeys aren't unique");
5562 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5563 mine_transaction(&nodes[0], &local_txn_1[0]);
5564 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5565 check_closed_broadcast!(nodes[0], true);
5566 check_added_monitors!(nodes[0], 1);
5567 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5569 let htlc_timeout = {
5570 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5571 assert_eq!(node_txn[1].input.len(), 1);
5572 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5573 check_spends!(node_txn[1], local_txn_1[0]);
5577 mine_transaction(&nodes[0], &htlc_timeout);
5578 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5579 expect_payment_failed!(nodes[0], our_payment_hash, true);
5581 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5582 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5583 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5584 assert_eq!(spend_txn.len(), 3);
5585 check_spends!(spend_txn[0], local_txn_1[0]);
5586 assert_eq!(spend_txn[1].input.len(), 1);
5587 check_spends!(spend_txn[1], htlc_timeout);
5588 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5589 assert_eq!(spend_txn[2].input.len(), 2);
5590 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5591 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5592 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5596 fn test_static_output_closing_tx() {
5597 let chanmon_cfgs = create_chanmon_cfgs(2);
5598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5600 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5602 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5604 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5605 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5607 mine_transaction(&nodes[0], &closing_tx);
5608 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5609 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5611 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5612 assert_eq!(spend_txn.len(), 1);
5613 check_spends!(spend_txn[0], closing_tx);
5615 mine_transaction(&nodes[1], &closing_tx);
5616 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5617 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5619 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5620 assert_eq!(spend_txn.len(), 1);
5621 check_spends!(spend_txn[0], closing_tx);
5624 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5625 let chanmon_cfgs = create_chanmon_cfgs(2);
5626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5629 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5631 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5633 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5634 // present in B's local commitment transaction, but none of A's commitment transactions.
5635 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5636 check_added_monitors!(nodes[1], 1);
5638 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5639 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5640 let events = nodes[0].node.get_and_clear_pending_events();
5641 assert_eq!(events.len(), 1);
5643 Event::PaymentSent { payment_preimage, payment_hash, .. } => {
5644 assert_eq!(payment_preimage, our_payment_preimage);
5645 assert_eq!(payment_hash, our_payment_hash);
5647 _ => panic!("Unexpected event"),
5650 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5651 check_added_monitors!(nodes[0], 1);
5652 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5653 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5654 check_added_monitors!(nodes[1], 1);
5656 let starting_block = nodes[1].best_block_info();
5657 let mut block = Block {
5658 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5661 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5662 connect_block(&nodes[1], &block);
5663 block.header.prev_blockhash = block.block_hash();
5665 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5666 check_closed_broadcast!(nodes[1], true);
5667 check_added_monitors!(nodes[1], 1);
5668 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5671 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5672 let chanmon_cfgs = create_chanmon_cfgs(2);
5673 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5674 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5675 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5676 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5678 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5679 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5680 check_added_monitors!(nodes[0], 1);
5682 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5684 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5685 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5686 // to "time out" the HTLC.
5688 let starting_block = nodes[1].best_block_info();
5689 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5691 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5692 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5693 header.prev_blockhash = header.block_hash();
5695 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5696 check_closed_broadcast!(nodes[0], true);
5697 check_added_monitors!(nodes[0], 1);
5698 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5701 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5702 let chanmon_cfgs = create_chanmon_cfgs(3);
5703 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5704 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5705 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5706 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5708 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5709 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5710 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5711 // actually revoked.
5712 let htlc_value = if use_dust { 50000 } else { 3000000 };
5713 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5714 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5715 expect_pending_htlcs_forwardable!(nodes[1]);
5716 check_added_monitors!(nodes[1], 1);
5718 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5719 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5720 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5721 check_added_monitors!(nodes[0], 1);
5722 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5723 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5724 check_added_monitors!(nodes[1], 1);
5725 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5726 check_added_monitors!(nodes[1], 1);
5727 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5729 if check_revoke_no_close {
5730 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5731 check_added_monitors!(nodes[0], 1);
5734 let starting_block = nodes[1].best_block_info();
5735 let mut block = Block {
5736 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5739 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5740 connect_block(&nodes[0], &block);
5741 block.header.prev_blockhash = block.block_hash();
5743 if !check_revoke_no_close {
5744 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5745 check_closed_broadcast!(nodes[0], true);
5746 check_added_monitors!(nodes[0], 1);
5747 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5749 expect_payment_failed!(nodes[0], our_payment_hash, true);
5753 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5754 // There are only a few cases to test here:
5755 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5756 // broadcastable commitment transactions result in channel closure,
5757 // * its included in an unrevoked-but-previous remote commitment transaction,
5758 // * its included in the latest remote or local commitment transactions.
5759 // We test each of the three possible commitment transactions individually and use both dust and
5761 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5762 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5763 // tested for at least one of the cases in other tests.
5765 fn htlc_claim_single_commitment_only_a() {
5766 do_htlc_claim_local_commitment_only(true);
5767 do_htlc_claim_local_commitment_only(false);
5769 do_htlc_claim_current_remote_commitment_only(true);
5770 do_htlc_claim_current_remote_commitment_only(false);
5774 fn htlc_claim_single_commitment_only_b() {
5775 do_htlc_claim_previous_remote_commitment_only(true, false);
5776 do_htlc_claim_previous_remote_commitment_only(false, false);
5777 do_htlc_claim_previous_remote_commitment_only(true, true);
5778 do_htlc_claim_previous_remote_commitment_only(false, true);
5783 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5784 let chanmon_cfgs = create_chanmon_cfgs(2);
5785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5788 //Force duplicate channel ids
5789 for node in nodes.iter() {
5790 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5793 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5794 let channel_value_satoshis=10000;
5795 let push_msat=10001;
5796 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5797 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5798 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5800 //Create a second channel with a channel_id collision
5801 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5805 fn bolt2_open_channel_sending_node_checks_part2() {
5806 let chanmon_cfgs = create_chanmon_cfgs(2);
5807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5809 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5811 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5812 let channel_value_satoshis=2^24;
5813 let push_msat=10001;
5814 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5816 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5817 let channel_value_satoshis=10000;
5818 // Test when push_msat is equal to 1000 * funding_satoshis.
5819 let push_msat=1000*channel_value_satoshis+1;
5820 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5822 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5823 let channel_value_satoshis=10000;
5824 let push_msat=10001;
5825 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
5826 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5827 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5829 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5830 // 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
5831 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5833 // 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.
5834 assert!(BREAKDOWN_TIMEOUT>0);
5835 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5837 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5838 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5839 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5841 // 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.
5842 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5843 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5844 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5845 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5846 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5850 fn bolt2_open_channel_sane_dust_limit() {
5851 let chanmon_cfgs = create_chanmon_cfgs(2);
5852 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5853 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5854 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5856 let channel_value_satoshis=1000000;
5857 let push_msat=10001;
5858 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5859 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5860 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5861 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5863 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5864 let events = nodes[1].node.get_and_clear_pending_msg_events();
5865 let err_msg = match events[0] {
5866 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5869 _ => panic!("Unexpected event"),
5871 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5874 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5875 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5876 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5877 // is no longer affordable once it's freed.
5879 fn test_fail_holding_cell_htlc_upon_free() {
5880 let chanmon_cfgs = create_chanmon_cfgs(2);
5881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5883 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5884 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5886 // First nodes[0] generates an update_fee, setting the channel's
5887 // pending_update_fee.
5889 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5890 *feerate_lock += 20;
5892 nodes[0].node.timer_tick_occurred();
5893 check_added_monitors!(nodes[0], 1);
5895 let events = nodes[0].node.get_and_clear_pending_msg_events();
5896 assert_eq!(events.len(), 1);
5897 let (update_msg, commitment_signed) = match events[0] {
5898 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5899 (update_fee.as_ref(), commitment_signed)
5901 _ => panic!("Unexpected event"),
5904 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5906 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5907 let channel_reserve = chan_stat.channel_reserve_msat;
5908 let feerate = get_feerate!(nodes[0], chan.2);
5910 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5911 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5912 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5914 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5915 let our_payment_id = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5916 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5917 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5919 // Flush the pending fee update.
5920 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5921 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5922 check_added_monitors!(nodes[1], 1);
5923 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5924 check_added_monitors!(nodes[0], 1);
5926 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5927 // HTLC, but now that the fee has been raised the payment will now fail, causing
5928 // us to surface its failure to the user.
5929 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5930 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5931 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);
5932 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 {}",
5933 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5934 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5936 // Check that the payment failed to be sent out.
5937 let events = nodes[0].node.get_and_clear_pending_events();
5938 assert_eq!(events.len(), 1);
5940 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
5941 assert_eq!(our_payment_id, *payment_id.as_ref().unwrap());
5942 assert_eq!(our_payment_hash.clone(), *payment_hash);
5943 assert_eq!(*rejected_by_dest, false);
5944 assert_eq!(*all_paths_failed, true);
5945 assert_eq!(*network_update, None);
5946 assert_eq!(*short_channel_id, None);
5947 assert_eq!(*error_code, None);
5948 assert_eq!(*error_data, None);
5950 _ => panic!("Unexpected event"),
5954 // Test that if multiple HTLCs are released from the holding cell and one is
5955 // valid but the other is no longer valid upon release, the valid HTLC can be
5956 // successfully completed while the other one fails as expected.
5958 fn test_free_and_fail_holding_cell_htlcs() {
5959 let chanmon_cfgs = create_chanmon_cfgs(2);
5960 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5961 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5962 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5963 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5965 // First nodes[0] generates an update_fee, setting the channel's
5966 // pending_update_fee.
5968 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5969 *feerate_lock += 200;
5971 nodes[0].node.timer_tick_occurred();
5972 check_added_monitors!(nodes[0], 1);
5974 let events = nodes[0].node.get_and_clear_pending_msg_events();
5975 assert_eq!(events.len(), 1);
5976 let (update_msg, commitment_signed) = match events[0] {
5977 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5978 (update_fee.as_ref(), commitment_signed)
5980 _ => panic!("Unexpected event"),
5983 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5985 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5986 let channel_reserve = chan_stat.channel_reserve_msat;
5987 let feerate = get_feerate!(nodes[0], chan.2);
5989 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5991 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
5992 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5993 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5995 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
5996 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
5997 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5998 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
5999 let payment_id_2 = nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6000 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6001 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6003 // Flush the pending fee update.
6004 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6005 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6006 check_added_monitors!(nodes[1], 1);
6007 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6008 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6009 check_added_monitors!(nodes[0], 2);
6011 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6012 // but now that the fee has been raised the second payment will now fail, causing us
6013 // to surface its failure to the user. The first payment should succeed.
6014 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6015 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6016 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);
6017 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 {}",
6018 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6019 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6021 // Check that the second payment failed to be sent out.
6022 let events = nodes[0].node.get_and_clear_pending_events();
6023 assert_eq!(events.len(), 1);
6025 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, ref short_channel_id, ref error_code, ref error_data, .. } => {
6026 assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6027 assert_eq!(payment_hash_2.clone(), *payment_hash);
6028 assert_eq!(*rejected_by_dest, false);
6029 assert_eq!(*all_paths_failed, true);
6030 assert_eq!(*network_update, None);
6031 assert_eq!(*short_channel_id, None);
6032 assert_eq!(*error_code, None);
6033 assert_eq!(*error_data, None);
6035 _ => panic!("Unexpected event"),
6038 // Complete the first payment and the RAA from the fee update.
6039 let (payment_event, send_raa_event) = {
6040 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6041 assert_eq!(msgs.len(), 2);
6042 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6044 let raa = match send_raa_event {
6045 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6046 _ => panic!("Unexpected event"),
6048 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6049 check_added_monitors!(nodes[1], 1);
6050 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6051 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6052 let events = nodes[1].node.get_and_clear_pending_events();
6053 assert_eq!(events.len(), 1);
6055 Event::PendingHTLCsForwardable { .. } => {},
6056 _ => panic!("Unexpected event"),
6058 nodes[1].node.process_pending_htlc_forwards();
6059 let events = nodes[1].node.get_and_clear_pending_events();
6060 assert_eq!(events.len(), 1);
6062 Event::PaymentReceived { .. } => {},
6063 _ => panic!("Unexpected event"),
6065 nodes[1].node.claim_funds(payment_preimage_1);
6066 check_added_monitors!(nodes[1], 1);
6067 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6068 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6069 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6070 let events = nodes[0].node.get_and_clear_pending_events();
6071 assert_eq!(events.len(), 1);
6073 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
6074 assert_eq!(*payment_preimage, payment_preimage_1);
6075 assert_eq!(*payment_hash, payment_hash_1);
6077 _ => panic!("Unexpected event"),
6081 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6082 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6083 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6086 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6087 let chanmon_cfgs = create_chanmon_cfgs(3);
6088 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6089 // When this test was written, the default base fee floated based on the HTLC count.
6090 // It is now fixed, so we simply set the fee to the expected value here.
6091 let mut config = test_default_channel_config();
6092 config.channel_options.forwarding_fee_base_msat = 196;
6093 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6094 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6095 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6096 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6098 // First nodes[1] generates an update_fee, setting the channel's
6099 // pending_update_fee.
6101 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6102 *feerate_lock += 20;
6104 nodes[1].node.timer_tick_occurred();
6105 check_added_monitors!(nodes[1], 1);
6107 let events = nodes[1].node.get_and_clear_pending_msg_events();
6108 assert_eq!(events.len(), 1);
6109 let (update_msg, commitment_signed) = match events[0] {
6110 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6111 (update_fee.as_ref(), commitment_signed)
6113 _ => panic!("Unexpected event"),
6116 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6118 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6119 let channel_reserve = chan_stat.channel_reserve_msat;
6120 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6122 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6124 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6125 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6126 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6127 let payment_event = {
6128 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6129 check_added_monitors!(nodes[0], 1);
6131 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6132 assert_eq!(events.len(), 1);
6134 SendEvent::from_event(events.remove(0))
6136 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6137 check_added_monitors!(nodes[1], 0);
6138 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6139 expect_pending_htlcs_forwardable!(nodes[1]);
6141 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6142 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6144 // Flush the pending fee update.
6145 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6146 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6147 check_added_monitors!(nodes[2], 1);
6148 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6149 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6150 check_added_monitors!(nodes[1], 2);
6152 // A final RAA message is generated to finalize the fee update.
6153 let events = nodes[1].node.get_and_clear_pending_msg_events();
6154 assert_eq!(events.len(), 1);
6156 let raa_msg = match &events[0] {
6157 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6160 _ => panic!("Unexpected event"),
6163 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6164 check_added_monitors!(nodes[2], 1);
6165 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6167 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6168 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6169 assert_eq!(process_htlc_forwards_event.len(), 1);
6170 match &process_htlc_forwards_event[0] {
6171 &Event::PendingHTLCsForwardable { .. } => {},
6172 _ => panic!("Unexpected event"),
6175 // In response, we call ChannelManager's process_pending_htlc_forwards
6176 nodes[1].node.process_pending_htlc_forwards();
6177 check_added_monitors!(nodes[1], 1);
6179 // This causes the HTLC to be failed backwards.
6180 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6181 assert_eq!(fail_event.len(), 1);
6182 let (fail_msg, commitment_signed) = match &fail_event[0] {
6183 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6184 assert_eq!(updates.update_add_htlcs.len(), 0);
6185 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6186 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6187 assert_eq!(updates.update_fail_htlcs.len(), 1);
6188 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6190 _ => panic!("Unexpected event"),
6193 // Pass the failure messages back to nodes[0].
6194 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6195 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6197 // Complete the HTLC failure+removal process.
6198 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6199 check_added_monitors!(nodes[0], 1);
6200 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6201 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6202 check_added_monitors!(nodes[1], 2);
6203 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6204 assert_eq!(final_raa_event.len(), 1);
6205 let raa = match &final_raa_event[0] {
6206 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6207 _ => panic!("Unexpected event"),
6209 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6210 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6211 check_added_monitors!(nodes[0], 1);
6214 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6215 // 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.
6216 //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.
6219 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6220 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6221 let chanmon_cfgs = create_chanmon_cfgs(2);
6222 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6223 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6224 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6225 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6227 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6228 route.paths[0][0].fee_msat = 100;
6230 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6231 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6232 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6233 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6237 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6238 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6239 let chanmon_cfgs = create_chanmon_cfgs(2);
6240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6242 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6243 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6245 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6246 route.paths[0][0].fee_msat = 0;
6247 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6248 assert_eq!(err, "Cannot send 0-msat HTLC"));
6250 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6251 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6255 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6256 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6257 let chanmon_cfgs = create_chanmon_cfgs(2);
6258 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6259 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6260 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6261 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6263 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6264 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6265 check_added_monitors!(nodes[0], 1);
6266 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6267 updates.update_add_htlcs[0].amount_msat = 0;
6269 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6270 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6271 check_closed_broadcast!(nodes[1], true).unwrap();
6272 check_added_monitors!(nodes[1], 1);
6273 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6277 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6278 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6279 //It is enforced when constructing a route.
6280 let chanmon_cfgs = create_chanmon_cfgs(2);
6281 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6282 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6283 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6284 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6286 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6287 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6288 assert_eq!(err, &"Channel CLTV overflowed?"));
6292 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6293 //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.
6294 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6295 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6296 let chanmon_cfgs = create_chanmon_cfgs(2);
6297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6299 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6300 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6301 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6303 for i in 0..max_accepted_htlcs {
6304 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6305 let payment_event = {
6306 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6307 check_added_monitors!(nodes[0], 1);
6309 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6310 assert_eq!(events.len(), 1);
6311 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6312 assert_eq!(htlcs[0].htlc_id, i);
6316 SendEvent::from_event(events.remove(0))
6318 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6319 check_added_monitors!(nodes[1], 0);
6320 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6322 expect_pending_htlcs_forwardable!(nodes[1]);
6323 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6325 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6326 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6327 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6329 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6330 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6334 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6335 //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.
6336 let chanmon_cfgs = create_chanmon_cfgs(2);
6337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6339 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6340 let channel_value = 100000;
6341 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6342 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6344 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6346 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6347 // Manually create a route over our max in flight (which our router normally automatically
6349 route.paths[0][0].fee_msat = max_in_flight + 1;
6350 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6351 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)));
6353 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6354 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);
6356 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6359 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6361 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6362 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6363 let chanmon_cfgs = create_chanmon_cfgs(2);
6364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6368 let htlc_minimum_msat: u64;
6370 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6371 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6372 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6375 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6376 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6377 check_added_monitors!(nodes[0], 1);
6378 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6379 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6380 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6381 assert!(nodes[1].node.list_channels().is_empty());
6382 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6383 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()));
6384 check_added_monitors!(nodes[1], 1);
6385 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6389 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6390 //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
6391 let chanmon_cfgs = create_chanmon_cfgs(2);
6392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6394 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6395 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6397 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6398 let channel_reserve = chan_stat.channel_reserve_msat;
6399 let feerate = get_feerate!(nodes[0], chan.2);
6400 // The 2* and +1 are for the fee spike reserve.
6401 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6403 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6404 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6405 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6406 check_added_monitors!(nodes[0], 1);
6407 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6409 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6410 // at this time channel-initiatee receivers are not required to enforce that senders
6411 // respect the fee_spike_reserve.
6412 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6413 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6415 assert!(nodes[1].node.list_channels().is_empty());
6416 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6417 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6418 check_added_monitors!(nodes[1], 1);
6419 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6423 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6424 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6425 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6426 let chanmon_cfgs = create_chanmon_cfgs(2);
6427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6433 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6434 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6435 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6436 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6437 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6439 let mut msg = msgs::UpdateAddHTLC {
6443 payment_hash: our_payment_hash,
6444 cltv_expiry: htlc_cltv,
6445 onion_routing_packet: onion_packet.clone(),
6448 for i in 0..super::channel::OUR_MAX_HTLCS {
6449 msg.htlc_id = i as u64;
6450 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6452 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6455 assert!(nodes[1].node.list_channels().is_empty());
6456 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6457 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6458 check_added_monitors!(nodes[1], 1);
6459 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6463 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6464 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6465 let chanmon_cfgs = create_chanmon_cfgs(2);
6466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6468 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6469 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6471 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6472 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6473 check_added_monitors!(nodes[0], 1);
6474 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6475 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6476 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6478 assert!(nodes[1].node.list_channels().is_empty());
6479 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6480 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6481 check_added_monitors!(nodes[1], 1);
6482 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6486 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6487 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6488 let chanmon_cfgs = create_chanmon_cfgs(2);
6489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6491 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6493 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6494 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6495 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6496 check_added_monitors!(nodes[0], 1);
6497 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6498 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6499 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6501 assert!(nodes[1].node.list_channels().is_empty());
6502 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6503 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6504 check_added_monitors!(nodes[1], 1);
6505 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6509 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6510 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6511 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6512 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6513 let chanmon_cfgs = create_chanmon_cfgs(2);
6514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6516 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6518 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6519 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6520 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6521 check_added_monitors!(nodes[0], 1);
6522 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6523 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6525 //Disconnect and Reconnect
6526 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6527 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6528 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6529 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6530 assert_eq!(reestablish_1.len(), 1);
6531 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6532 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6533 assert_eq!(reestablish_2.len(), 1);
6534 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6535 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6536 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6537 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6540 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6541 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6542 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6543 check_added_monitors!(nodes[1], 1);
6544 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6546 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6548 assert!(nodes[1].node.list_channels().is_empty());
6549 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6550 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6551 check_added_monitors!(nodes[1], 1);
6552 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6556 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6557 //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.
6559 let chanmon_cfgs = create_chanmon_cfgs(2);
6560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6564 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6565 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6567 check_added_monitors!(nodes[0], 1);
6568 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6569 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6571 let update_msg = msgs::UpdateFulfillHTLC{
6574 payment_preimage: our_payment_preimage,
6577 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6579 assert!(nodes[0].node.list_channels().is_empty());
6580 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6581 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()));
6582 check_added_monitors!(nodes[0], 1);
6583 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6587 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6588 //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.
6590 let chanmon_cfgs = create_chanmon_cfgs(2);
6591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6593 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6594 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6596 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6597 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6598 check_added_monitors!(nodes[0], 1);
6599 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6600 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6602 let update_msg = msgs::UpdateFailHTLC{
6605 reason: msgs::OnionErrorPacket { data: Vec::new()},
6608 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6610 assert!(nodes[0].node.list_channels().is_empty());
6611 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6612 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()));
6613 check_added_monitors!(nodes[0], 1);
6614 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6618 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6619 //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.
6621 let chanmon_cfgs = create_chanmon_cfgs(2);
6622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6624 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6625 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6627 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6628 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6629 check_added_monitors!(nodes[0], 1);
6630 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6631 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6632 let update_msg = msgs::UpdateFailMalformedHTLC{
6635 sha256_of_onion: [1; 32],
6636 failure_code: 0x8000,
6639 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6641 assert!(nodes[0].node.list_channels().is_empty());
6642 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6643 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()));
6644 check_added_monitors!(nodes[0], 1);
6645 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6649 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6650 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6652 let chanmon_cfgs = create_chanmon_cfgs(2);
6653 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6654 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6655 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6656 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6658 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6660 nodes[1].node.claim_funds(our_payment_preimage);
6661 check_added_monitors!(nodes[1], 1);
6663 let events = nodes[1].node.get_and_clear_pending_msg_events();
6664 assert_eq!(events.len(), 1);
6665 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6667 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, .. } } => {
6668 assert!(update_add_htlcs.is_empty());
6669 assert_eq!(update_fulfill_htlcs.len(), 1);
6670 assert!(update_fail_htlcs.is_empty());
6671 assert!(update_fail_malformed_htlcs.is_empty());
6672 assert!(update_fee.is_none());
6673 update_fulfill_htlcs[0].clone()
6675 _ => panic!("Unexpected event"),
6679 update_fulfill_msg.htlc_id = 1;
6681 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6683 assert!(nodes[0].node.list_channels().is_empty());
6684 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6685 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6686 check_added_monitors!(nodes[0], 1);
6687 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6691 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6692 //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.
6694 let chanmon_cfgs = create_chanmon_cfgs(2);
6695 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6696 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6697 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6698 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6700 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6702 nodes[1].node.claim_funds(our_payment_preimage);
6703 check_added_monitors!(nodes[1], 1);
6705 let events = nodes[1].node.get_and_clear_pending_msg_events();
6706 assert_eq!(events.len(), 1);
6707 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6709 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, .. } } => {
6710 assert!(update_add_htlcs.is_empty());
6711 assert_eq!(update_fulfill_htlcs.len(), 1);
6712 assert!(update_fail_htlcs.is_empty());
6713 assert!(update_fail_malformed_htlcs.is_empty());
6714 assert!(update_fee.is_none());
6715 update_fulfill_htlcs[0].clone()
6717 _ => panic!("Unexpected event"),
6721 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6723 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6725 assert!(nodes[0].node.list_channels().is_empty());
6726 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6727 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6728 check_added_monitors!(nodes[0], 1);
6729 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6733 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6734 //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.
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 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6742 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6743 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6744 check_added_monitors!(nodes[0], 1);
6746 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6747 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6749 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6750 check_added_monitors!(nodes[1], 0);
6751 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6753 let events = nodes[1].node.get_and_clear_pending_msg_events();
6755 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6757 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, .. } } => {
6758 assert!(update_add_htlcs.is_empty());
6759 assert!(update_fulfill_htlcs.is_empty());
6760 assert!(update_fail_htlcs.is_empty());
6761 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6762 assert!(update_fee.is_none());
6763 update_fail_malformed_htlcs[0].clone()
6765 _ => panic!("Unexpected event"),
6768 update_msg.failure_code &= !0x8000;
6769 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6771 assert!(nodes[0].node.list_channels().is_empty());
6772 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6773 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6774 check_added_monitors!(nodes[0], 1);
6775 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6779 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6780 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6781 // * 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.
6783 let chanmon_cfgs = create_chanmon_cfgs(3);
6784 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6785 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6786 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6787 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6788 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6790 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6793 let mut payment_event = {
6794 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6795 check_added_monitors!(nodes[0], 1);
6796 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6797 assert_eq!(events.len(), 1);
6798 SendEvent::from_event(events.remove(0))
6800 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6801 check_added_monitors!(nodes[1], 0);
6802 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6803 expect_pending_htlcs_forwardable!(nodes[1]);
6804 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6805 assert_eq!(events_2.len(), 1);
6806 check_added_monitors!(nodes[1], 1);
6807 payment_event = SendEvent::from_event(events_2.remove(0));
6808 assert_eq!(payment_event.msgs.len(), 1);
6811 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6812 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6813 check_added_monitors!(nodes[2], 0);
6814 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6816 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6817 assert_eq!(events_3.len(), 1);
6818 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6820 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 } } => {
6821 assert!(update_add_htlcs.is_empty());
6822 assert!(update_fulfill_htlcs.is_empty());
6823 assert!(update_fail_htlcs.is_empty());
6824 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6825 assert!(update_fee.is_none());
6826 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6828 _ => panic!("Unexpected event"),
6832 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6834 check_added_monitors!(nodes[1], 0);
6835 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6836 expect_pending_htlcs_forwardable!(nodes[1]);
6837 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6838 assert_eq!(events_4.len(), 1);
6840 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6842 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, .. } } => {
6843 assert!(update_add_htlcs.is_empty());
6844 assert!(update_fulfill_htlcs.is_empty());
6845 assert_eq!(update_fail_htlcs.len(), 1);
6846 assert!(update_fail_malformed_htlcs.is_empty());
6847 assert!(update_fee.is_none());
6849 _ => panic!("Unexpected event"),
6852 check_added_monitors!(nodes[1], 1);
6855 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6856 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6857 // 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
6858 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6860 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6861 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6864 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6865 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6867 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6869 // We route 2 dust-HTLCs between A and B
6870 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6871 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6872 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6874 // Cache one local commitment tx as previous
6875 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6877 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6878 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6879 check_added_monitors!(nodes[1], 0);
6880 expect_pending_htlcs_forwardable!(nodes[1]);
6881 check_added_monitors!(nodes[1], 1);
6883 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6884 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6885 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6886 check_added_monitors!(nodes[0], 1);
6888 // Cache one local commitment tx as lastest
6889 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6891 let events = nodes[0].node.get_and_clear_pending_msg_events();
6893 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6894 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6896 _ => panic!("Unexpected event"),
6899 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6900 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6902 _ => panic!("Unexpected event"),
6905 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6906 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6907 if announce_latest {
6908 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6910 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6913 check_closed_broadcast!(nodes[0], true);
6914 check_added_monitors!(nodes[0], 1);
6915 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6917 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6918 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6919 let events = nodes[0].node.get_and_clear_pending_events();
6920 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6921 assert_eq!(events.len(), 2);
6922 let mut first_failed = false;
6923 for event in events {
6925 Event::PaymentPathFailed { payment_hash, .. } => {
6926 if payment_hash == payment_hash_1 {
6927 assert!(!first_failed);
6928 first_failed = true;
6930 assert_eq!(payment_hash, payment_hash_2);
6933 _ => panic!("Unexpected event"),
6939 fn test_failure_delay_dust_htlc_local_commitment() {
6940 do_test_failure_delay_dust_htlc_local_commitment(true);
6941 do_test_failure_delay_dust_htlc_local_commitment(false);
6944 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6945 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6946 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6947 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6948 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6949 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6950 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6952 let chanmon_cfgs = create_chanmon_cfgs(3);
6953 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6954 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6955 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6956 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6958 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6960 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6961 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6963 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6964 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6966 // We revoked bs_commitment_tx
6968 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6969 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
6972 let mut timeout_tx = Vec::new();
6974 // We fail dust-HTLC 1 by broadcast of local commitment tx
6975 mine_transaction(&nodes[0], &as_commitment_tx[0]);
6976 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6977 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6978 expect_payment_failed!(nodes[0], dust_hash, true);
6980 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
6981 check_closed_broadcast!(nodes[0], true);
6982 check_added_monitors!(nodes[0], 1);
6983 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6984 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
6985 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6986 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6987 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6988 mine_transaction(&nodes[0], &timeout_tx[0]);
6989 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6990 expect_payment_failed!(nodes[0], non_dust_hash, true);
6992 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6993 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
6994 check_closed_broadcast!(nodes[0], true);
6995 check_added_monitors!(nodes[0], 1);
6996 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6997 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6998 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
6999 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7001 expect_payment_failed!(nodes[0], dust_hash, true);
7002 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7003 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7004 mine_transaction(&nodes[0], &timeout_tx[0]);
7005 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7006 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7007 expect_payment_failed!(nodes[0], non_dust_hash, true);
7009 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7011 let events = nodes[0].node.get_and_clear_pending_events();
7012 assert_eq!(events.len(), 2);
7015 Event::PaymentPathFailed { payment_hash, .. } => {
7016 if payment_hash == dust_hash { first = true; }
7017 else { first = false; }
7019 _ => panic!("Unexpected event"),
7022 Event::PaymentPathFailed { payment_hash, .. } => {
7023 if first { assert_eq!(payment_hash, non_dust_hash); }
7024 else { assert_eq!(payment_hash, dust_hash); }
7026 _ => panic!("Unexpected event"),
7033 fn test_sweep_outbound_htlc_failure_update() {
7034 do_test_sweep_outbound_htlc_failure_update(false, true);
7035 do_test_sweep_outbound_htlc_failure_update(false, false);
7036 do_test_sweep_outbound_htlc_failure_update(true, false);
7040 fn test_user_configurable_csv_delay() {
7041 // We test our channel constructors yield errors when we pass them absurd csv delay
7043 let mut low_our_to_self_config = UserConfig::default();
7044 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7045 let mut high_their_to_self_config = UserConfig::default();
7046 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7047 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7048 let chanmon_cfgs = create_chanmon_cfgs(2);
7049 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7050 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7051 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7053 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7054 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, 0) {
7056 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())); },
7057 _ => panic!("Unexpected event"),
7059 } else { assert!(false) }
7061 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7062 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7063 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7064 open_channel.to_self_delay = 200;
7065 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, 0) {
7067 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())); },
7068 _ => panic!("Unexpected event"),
7070 } else { assert!(false); }
7072 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7073 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7074 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()));
7075 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7076 accept_channel.to_self_delay = 200;
7077 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7079 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7081 &ErrorAction::SendErrorMessage { ref msg } => {
7082 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()));
7083 reason_msg = msg.data.clone();
7087 } else { panic!(); }
7088 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7090 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7091 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7092 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7093 open_channel.to_self_delay = 200;
7094 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, 0) {
7096 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())); },
7097 _ => panic!("Unexpected event"),
7099 } else { assert!(false); }
7103 fn test_data_loss_protect() {
7104 // We want to be sure that :
7105 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7106 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7107 // * we close channel in case of detecting other being fallen behind
7108 // * we are able to claim our own outputs thanks to to_remote being static
7109 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7115 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7116 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7117 // during signing due to revoked tx
7118 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7119 let keys_manager = &chanmon_cfgs[0].keys_manager;
7122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7124 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7126 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7128 // Cache node A state before any channel update
7129 let previous_node_state = nodes[0].node.encode();
7130 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7131 get_monitor!(nodes[0], chan.2).write(&mut previous_chain_monitor_state).unwrap();
7133 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7134 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7136 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7137 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7139 // Restore node A from previous state
7140 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7141 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7142 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7143 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7144 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7145 persister = test_utils::TestPersister::new();
7146 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7148 let mut channel_monitors = HashMap::new();
7149 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7150 <(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 {
7151 keys_manager: keys_manager,
7152 fee_estimator: &fee_estimator,
7153 chain_monitor: &monitor,
7155 tx_broadcaster: &tx_broadcaster,
7156 default_config: UserConfig::default(),
7160 nodes[0].node = &node_state_0;
7161 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7162 nodes[0].chain_monitor = &monitor;
7163 nodes[0].chain_source = &chain_source;
7165 check_added_monitors!(nodes[0], 1);
7167 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7168 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7170 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7172 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7173 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7174 check_added_monitors!(nodes[0], 1);
7177 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7178 assert_eq!(node_txn.len(), 0);
7181 let mut reestablish_1 = Vec::with_capacity(1);
7182 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7183 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7184 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7185 reestablish_1.push(msg.clone());
7186 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7187 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7189 &ErrorAction::SendErrorMessage { ref msg } => {
7190 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");
7192 _ => panic!("Unexpected event!"),
7195 panic!("Unexpected event")
7199 // Check we close channel detecting A is fallen-behind
7200 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7201 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7202 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7203 check_added_monitors!(nodes[1], 1);
7205 // Check A is able to claim to_remote output
7206 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7207 assert_eq!(node_txn.len(), 1);
7208 check_spends!(node_txn[0], chan.3);
7209 assert_eq!(node_txn[0].output.len(), 2);
7210 mine_transaction(&nodes[0], &node_txn[0]);
7211 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7212 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() });
7213 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7214 assert_eq!(spend_txn.len(), 1);
7215 check_spends!(spend_txn[0], node_txn[0]);
7219 fn test_check_htlc_underpaying() {
7220 // Send payment through A -> B but A is maliciously
7221 // sending a probe payment (i.e less than expected value0
7222 // to B, B should refuse payment.
7224 let chanmon_cfgs = create_chanmon_cfgs(2);
7225 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7226 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7227 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7229 // Create some initial channels
7230 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7232 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7233 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7234 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, nodes[0].network_graph, None, 10_000, TEST_FINAL_CLTV, nodes[0].logger, &scorer).unwrap();
7235 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7236 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200).unwrap();
7237 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7238 check_added_monitors!(nodes[0], 1);
7240 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7241 assert_eq!(events.len(), 1);
7242 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7243 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7244 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7246 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7247 // and then will wait a second random delay before failing the HTLC back:
7248 expect_pending_htlcs_forwardable!(nodes[1]);
7249 expect_pending_htlcs_forwardable!(nodes[1]);
7251 // Node 3 is expecting payment of 100_000 but received 10_000,
7252 // it should fail htlc like we didn't know the preimage.
7253 nodes[1].node.process_pending_htlc_forwards();
7255 let events = nodes[1].node.get_and_clear_pending_msg_events();
7256 assert_eq!(events.len(), 1);
7257 let (update_fail_htlc, commitment_signed) = match events[0] {
7258 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 } } => {
7259 assert!(update_add_htlcs.is_empty());
7260 assert!(update_fulfill_htlcs.is_empty());
7261 assert_eq!(update_fail_htlcs.len(), 1);
7262 assert!(update_fail_malformed_htlcs.is_empty());
7263 assert!(update_fee.is_none());
7264 (update_fail_htlcs[0].clone(), commitment_signed)
7266 _ => panic!("Unexpected event"),
7268 check_added_monitors!(nodes[1], 1);
7270 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7271 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7273 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7274 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7275 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7276 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7280 fn test_announce_disable_channels() {
7281 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7282 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7284 let chanmon_cfgs = create_chanmon_cfgs(2);
7285 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7286 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7287 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7289 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7290 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7291 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7294 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7295 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7297 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7298 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7299 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7300 assert_eq!(msg_events.len(), 3);
7301 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7302 for e in msg_events {
7304 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7305 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7306 // Check that each channel gets updated exactly once
7307 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7308 panic!("Generated ChannelUpdate for wrong chan!");
7311 _ => panic!("Unexpected event"),
7315 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7316 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7317 assert_eq!(reestablish_1.len(), 3);
7318 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7319 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7320 assert_eq!(reestablish_2.len(), 3);
7322 // Reestablish chan_1
7323 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7324 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7325 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7326 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7327 // Reestablish chan_2
7328 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7329 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7330 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7331 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7332 // Reestablish chan_3
7333 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7334 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7335 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7336 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7338 nodes[0].node.timer_tick_occurred();
7339 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7340 nodes[0].node.timer_tick_occurred();
7341 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7342 assert_eq!(msg_events.len(), 3);
7343 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7344 for e in msg_events {
7346 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7347 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7348 // Check that each channel gets updated exactly once
7349 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7350 panic!("Generated ChannelUpdate for wrong chan!");
7353 _ => panic!("Unexpected event"),
7359 fn test_priv_forwarding_rejection() {
7360 // If we have a private channel with outbound liquidity, and
7361 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7362 // to forward through that channel.
7363 let chanmon_cfgs = create_chanmon_cfgs(3);
7364 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7365 let mut no_announce_cfg = test_default_channel_config();
7366 no_announce_cfg.channel_options.announced_channel = false;
7367 no_announce_cfg.accept_forwards_to_priv_channels = false;
7368 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7369 let persister: test_utils::TestPersister;
7370 let new_chain_monitor: test_utils::TestChainMonitor;
7371 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7372 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7374 let chan_id_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known()).2;
7376 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7377 // not send for private channels.
7378 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7379 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7380 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7381 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7382 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7384 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7385 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7386 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()));
7387 check_added_monitors!(nodes[2], 1);
7389 let cs_funding_signed = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id());
7390 nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &cs_funding_signed);
7391 check_added_monitors!(nodes[1], 1);
7393 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7394 confirm_transaction_at(&nodes[1], &tx, conf_height);
7395 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7396 confirm_transaction_at(&nodes[2], &tx, conf_height);
7397 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7398 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7399 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()));
7400 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7401 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7402 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7404 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7405 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7406 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7408 // We should always be able to forward through nodes[1] as long as its out through a public
7410 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7412 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7413 // to nodes[2], which should be rejected:
7414 let route_hint = RouteHint(vec![RouteHintHop {
7415 src_node_id: nodes[1].node.get_our_node_id(),
7416 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7417 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7418 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7419 htlc_minimum_msat: None,
7420 htlc_maximum_msat: None,
7422 let last_hops = vec![route_hint];
7423 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], last_hops, 10_000, TEST_FINAL_CLTV);
7425 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7426 check_added_monitors!(nodes[0], 1);
7427 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7428 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7429 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7431 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7432 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7433 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7434 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7435 assert!(htlc_fail_updates.update_fee.is_none());
7437 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7438 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7439 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7441 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7442 // to true. Sadly there is currently no way to change it at runtime.
7444 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7445 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7447 let nodes_1_serialized = nodes[1].node.encode();
7448 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7449 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7450 get_monitor!(nodes[1], chan_id_1).write(&mut monitor_a_serialized).unwrap();
7451 get_monitor!(nodes[1], cs_funding_signed.channel_id).write(&mut monitor_b_serialized).unwrap();
7453 persister = test_utils::TestPersister::new();
7454 let keys_manager = &chanmon_cfgs[1].keys_manager;
7455 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);
7456 nodes[1].chain_monitor = &new_chain_monitor;
7458 let mut monitor_a_read = &monitor_a_serialized.0[..];
7459 let mut monitor_b_read = &monitor_b_serialized.0[..];
7460 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7461 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7462 assert!(monitor_a_read.is_empty());
7463 assert!(monitor_b_read.is_empty());
7465 no_announce_cfg.accept_forwards_to_priv_channels = true;
7467 let mut nodes_1_read = &nodes_1_serialized[..];
7468 let (_, nodes_1_deserialized_tmp) = {
7469 let mut channel_monitors = HashMap::new();
7470 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7471 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7472 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7473 default_config: no_announce_cfg,
7475 fee_estimator: node_cfgs[1].fee_estimator,
7476 chain_monitor: nodes[1].chain_monitor,
7477 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7478 logger: nodes[1].logger,
7482 assert!(nodes_1_read.is_empty());
7483 nodes_1_deserialized = nodes_1_deserialized_tmp;
7485 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7486 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7487 check_added_monitors!(nodes[1], 2);
7488 nodes[1].node = &nodes_1_deserialized;
7490 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7491 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7492 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7493 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7494 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7495 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7496 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7497 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7499 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7500 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7501 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7502 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7503 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7504 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7505 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7506 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7508 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7509 check_added_monitors!(nodes[0], 1);
7510 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7511 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7515 fn test_bump_penalty_txn_on_revoked_commitment() {
7516 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7517 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7519 let chanmon_cfgs = create_chanmon_cfgs(2);
7520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7524 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7526 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7527 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7528 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7530 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7531 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7532 assert_eq!(revoked_txn[0].output.len(), 4);
7533 assert_eq!(revoked_txn[0].input.len(), 1);
7534 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7535 let revoked_txid = revoked_txn[0].txid();
7537 let mut penalty_sum = 0;
7538 for outp in revoked_txn[0].output.iter() {
7539 if outp.script_pubkey.is_v0_p2wsh() {
7540 penalty_sum += outp.value;
7544 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7545 let header_114 = connect_blocks(&nodes[1], 14);
7547 // Actually revoke tx by claiming a HTLC
7548 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7549 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7550 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7551 check_added_monitors!(nodes[1], 1);
7553 // One or more justice tx should have been broadcast, check it
7557 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7558 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7559 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7560 assert_eq!(node_txn[0].output.len(), 1);
7561 check_spends!(node_txn[0], revoked_txn[0]);
7562 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7563 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7564 penalty_1 = node_txn[0].txid();
7568 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7569 connect_blocks(&nodes[1], 15);
7570 let mut penalty_2 = penalty_1;
7571 let mut feerate_2 = 0;
7573 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7574 assert_eq!(node_txn.len(), 1);
7575 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7576 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7577 assert_eq!(node_txn[0].output.len(), 1);
7578 check_spends!(node_txn[0], revoked_txn[0]);
7579 penalty_2 = node_txn[0].txid();
7580 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7581 assert_ne!(penalty_2, penalty_1);
7582 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7583 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7584 // Verify 25% bump heuristic
7585 assert!(feerate_2 * 100 >= feerate_1 * 125);
7589 assert_ne!(feerate_2, 0);
7591 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7592 connect_blocks(&nodes[1], 1);
7594 let mut feerate_3 = 0;
7596 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7597 assert_eq!(node_txn.len(), 1);
7598 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7599 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7600 assert_eq!(node_txn[0].output.len(), 1);
7601 check_spends!(node_txn[0], revoked_txn[0]);
7602 penalty_3 = node_txn[0].txid();
7603 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7604 assert_ne!(penalty_3, penalty_2);
7605 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7606 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7607 // Verify 25% bump heuristic
7608 assert!(feerate_3 * 100 >= feerate_2 * 125);
7612 assert_ne!(feerate_3, 0);
7614 nodes[1].node.get_and_clear_pending_events();
7615 nodes[1].node.get_and_clear_pending_msg_events();
7619 fn test_bump_penalty_txn_on_revoked_htlcs() {
7620 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7621 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7623 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7624 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7627 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7629 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7630 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7631 let payee = Payee::from_node_id(nodes[1].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7632 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
7633 let route = get_route(&nodes[0].node.get_our_node_id(), &payee, &nodes[0].network_graph, None,
7634 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7635 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7636 let payee = Payee::from_node_id(nodes[0].node.get_our_node_id()).with_features(InvoiceFeatures::known());
7637 let route = get_route(&nodes[1].node.get_our_node_id(), &payee, nodes[1].network_graph, None,
7638 3_000_000, 50, nodes[0].logger, &scorer).unwrap();
7639 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7641 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7642 assert_eq!(revoked_local_txn[0].input.len(), 1);
7643 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7645 // Revoke local commitment tx
7646 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7648 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7649 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7650 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7651 check_closed_broadcast!(nodes[1], true);
7652 check_added_monitors!(nodes[1], 1);
7653 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7654 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7656 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7657 assert_eq!(revoked_htlc_txn.len(), 3);
7658 check_spends!(revoked_htlc_txn[1], chan.3);
7660 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7661 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7662 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7664 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7665 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7666 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7667 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7669 // Broadcast set of revoked txn on A
7670 let hash_128 = connect_blocks(&nodes[0], 40);
7671 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7672 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7673 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7674 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7675 let events = nodes[0].node.get_and_clear_pending_events();
7676 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7678 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7679 _ => panic!("Unexpected event"),
7685 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7686 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7687 // Verify claim tx are spending revoked HTLC txn
7689 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7690 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7691 // which are included in the same block (they are broadcasted because we scan the
7692 // transactions linearly and generate claims as we go, they likely should be removed in the
7694 assert_eq!(node_txn[0].input.len(), 1);
7695 check_spends!(node_txn[0], revoked_local_txn[0]);
7696 assert_eq!(node_txn[1].input.len(), 1);
7697 check_spends!(node_txn[1], revoked_local_txn[0]);
7698 assert_eq!(node_txn[2].input.len(), 1);
7699 check_spends!(node_txn[2], revoked_local_txn[0]);
7701 // Each of the three justice transactions claim a separate (single) output of the three
7702 // available, which we check here:
7703 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7704 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7705 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7707 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7708 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7710 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7711 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7712 // a remote commitment tx has already been confirmed).
7713 check_spends!(node_txn[3], chan.3);
7715 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7716 // output, checked above).
7717 assert_eq!(node_txn[4].input.len(), 2);
7718 assert_eq!(node_txn[4].output.len(), 1);
7719 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7721 first = node_txn[4].txid();
7722 // Store both feerates for later comparison
7723 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7724 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7725 penalty_txn = vec![node_txn[2].clone()];
7729 // Connect one more block to see if bumped penalty are issued for HTLC txn
7730 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7731 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7732 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7733 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7735 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7736 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7738 check_spends!(node_txn[0], revoked_local_txn[0]);
7739 check_spends!(node_txn[1], revoked_local_txn[0]);
7740 // Note that these are both bogus - they spend outputs already claimed in block 129:
7741 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7742 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7744 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7745 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7751 // Few more blocks to confirm penalty txn
7752 connect_blocks(&nodes[0], 4);
7753 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7754 let header_144 = connect_blocks(&nodes[0], 9);
7756 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7757 assert_eq!(node_txn.len(), 1);
7759 assert_eq!(node_txn[0].input.len(), 2);
7760 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7761 // Verify bumped tx is different and 25% bump heuristic
7762 assert_ne!(first, node_txn[0].txid());
7763 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7764 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7765 assert!(feerate_2 * 100 > feerate_1 * 125);
7766 let txn = vec![node_txn[0].clone()];
7770 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7771 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7772 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7773 connect_blocks(&nodes[0], 20);
7775 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7776 // We verify than no new transaction has been broadcast because previously
7777 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7778 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7779 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7780 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7781 // up bumped justice generation.
7782 assert_eq!(node_txn.len(), 0);
7785 check_closed_broadcast!(nodes[0], true);
7786 check_added_monitors!(nodes[0], 1);
7790 fn test_bump_penalty_txn_on_remote_commitment() {
7791 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7792 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7795 // Provide preimage for one
7796 // Check aggregation
7798 let chanmon_cfgs = create_chanmon_cfgs(2);
7799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7801 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7803 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7804 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7805 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7807 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7808 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7809 assert_eq!(remote_txn[0].output.len(), 4);
7810 assert_eq!(remote_txn[0].input.len(), 1);
7811 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7813 // Claim a HTLC without revocation (provide B monitor with preimage)
7814 nodes[1].node.claim_funds(payment_preimage);
7815 mine_transaction(&nodes[1], &remote_txn[0]);
7816 check_added_monitors!(nodes[1], 2);
7817 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7819 // One or more claim tx should have been broadcast, check it
7823 let feerate_timeout;
7824 let feerate_preimage;
7826 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7827 // 9 transactions including:
7828 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7829 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7830 // 2 * HTLC-Success (one RBF bump we'll check later)
7832 assert_eq!(node_txn.len(), 8);
7833 assert_eq!(node_txn[0].input.len(), 1);
7834 assert_eq!(node_txn[6].input.len(), 1);
7835 check_spends!(node_txn[0], remote_txn[0]);
7836 check_spends!(node_txn[6], remote_txn[0]);
7837 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7838 preimage_bump = node_txn[3].clone();
7840 check_spends!(node_txn[1], chan.3);
7841 check_spends!(node_txn[2], node_txn[1]);
7842 assert_eq!(node_txn[1], node_txn[4]);
7843 assert_eq!(node_txn[2], node_txn[5]);
7845 timeout = node_txn[6].txid();
7846 let index = node_txn[6].input[0].previous_output.vout;
7847 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7848 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7850 preimage = node_txn[0].txid();
7851 let index = node_txn[0].input[0].previous_output.vout;
7852 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7853 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7857 assert_ne!(feerate_timeout, 0);
7858 assert_ne!(feerate_preimage, 0);
7860 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7861 connect_blocks(&nodes[1], 15);
7863 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7864 assert_eq!(node_txn.len(), 1);
7865 assert_eq!(node_txn[0].input.len(), 1);
7866 assert_eq!(preimage_bump.input.len(), 1);
7867 check_spends!(node_txn[0], remote_txn[0]);
7868 check_spends!(preimage_bump, remote_txn[0]);
7870 let index = preimage_bump.input[0].previous_output.vout;
7871 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7872 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7873 assert!(new_feerate * 100 > feerate_timeout * 125);
7874 assert_ne!(timeout, preimage_bump.txid());
7876 let index = node_txn[0].input[0].previous_output.vout;
7877 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7878 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7879 assert!(new_feerate * 100 > feerate_preimage * 125);
7880 assert_ne!(preimage, node_txn[0].txid());
7885 nodes[1].node.get_and_clear_pending_events();
7886 nodes[1].node.get_and_clear_pending_msg_events();
7890 fn test_counterparty_raa_skip_no_crash() {
7891 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7892 // commitment transaction, we would have happily carried on and provided them the next
7893 // commitment transaction based on one RAA forward. This would probably eventually have led to
7894 // channel closure, but it would not have resulted in funds loss. Still, our
7895 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7896 // check simply that the channel is closed in response to such an RAA, but don't check whether
7897 // we decide to punish our counterparty for revoking their funds (as we don't currently
7899 let chanmon_cfgs = create_chanmon_cfgs(2);
7900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7903 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7905 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7906 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7908 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7910 // Make signer believe we got a counterparty signature, so that it allows the revocation
7911 keys.get_enforcement_state().last_holder_commitment -= 1;
7912 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7914 // Must revoke without gaps
7915 keys.get_enforcement_state().last_holder_commitment -= 1;
7916 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7918 keys.get_enforcement_state().last_holder_commitment -= 1;
7919 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7920 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7922 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7923 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7924 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7925 check_added_monitors!(nodes[1], 1);
7926 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7930 fn test_bump_txn_sanitize_tracking_maps() {
7931 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7932 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7934 let chanmon_cfgs = create_chanmon_cfgs(2);
7935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7939 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7940 // Lock HTLC in both directions
7941 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7942 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7944 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7945 assert_eq!(revoked_local_txn[0].input.len(), 1);
7946 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7948 // Revoke local commitment tx
7949 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7951 // Broadcast set of revoked txn on A
7952 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7953 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7954 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7956 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7957 check_closed_broadcast!(nodes[0], true);
7958 check_added_monitors!(nodes[0], 1);
7959 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7961 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7962 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7963 check_spends!(node_txn[0], revoked_local_txn[0]);
7964 check_spends!(node_txn[1], revoked_local_txn[0]);
7965 check_spends!(node_txn[2], revoked_local_txn[0]);
7966 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7970 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7971 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7972 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7974 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7975 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7976 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7981 fn test_channel_conf_timeout() {
7982 // Tests that, for inbound channels, we give up on them if the funding transaction does not
7983 // confirm within 2016 blocks, as recommended by BOLT 2.
7984 let chanmon_cfgs = create_chanmon_cfgs(2);
7985 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7986 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7987 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7989 let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000, InitFeatures::known(), InitFeatures::known());
7991 // The outbound node should wait forever for confirmation:
7992 // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7993 // copied here instead of directly referencing the constant.
7994 connect_blocks(&nodes[0], 2016);
7995 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7997 // The inbound node should fail the channel after exactly 2016 blocks
7998 connect_blocks(&nodes[1], 2015);
7999 check_added_monitors!(nodes[1], 0);
8000 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
8002 connect_blocks(&nodes[1], 1);
8003 check_added_monitors!(nodes[1], 1);
8004 check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut);
8005 let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
8006 assert_eq!(close_ev.len(), 1);
8008 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, ref node_id } => {
8009 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8010 assert_eq!(msg.data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
8012 _ => panic!("Unexpected event"),
8017 fn test_override_channel_config() {
8018 let chanmon_cfgs = create_chanmon_cfgs(2);
8019 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8020 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8021 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8023 // Node0 initiates a channel to node1 using the override config.
8024 let mut override_config = UserConfig::default();
8025 override_config.own_channel_config.our_to_self_delay = 200;
8027 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8029 // Assert the channel created by node0 is using the override config.
8030 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8031 assert_eq!(res.channel_flags, 0);
8032 assert_eq!(res.to_self_delay, 200);
8036 fn test_override_0msat_htlc_minimum() {
8037 let mut zero_config = UserConfig::default();
8038 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8039 let chanmon_cfgs = create_chanmon_cfgs(2);
8040 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8041 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8042 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8044 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8045 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8046 assert_eq!(res.htlc_minimum_msat, 1);
8048 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8049 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8050 assert_eq!(res.htlc_minimum_msat, 1);
8054 fn test_simple_mpp() {
8055 // Simple test of sending a multi-path payment.
8056 let chanmon_cfgs = create_chanmon_cfgs(4);
8057 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8058 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8059 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8061 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8062 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8063 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8064 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8066 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8067 let path = route.paths[0].clone();
8068 route.paths.push(path);
8069 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8070 route.paths[0][0].short_channel_id = chan_1_id;
8071 route.paths[0][1].short_channel_id = chan_3_id;
8072 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8073 route.paths[1][0].short_channel_id = chan_2_id;
8074 route.paths[1][1].short_channel_id = chan_4_id;
8075 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8076 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8080 fn test_preimage_storage() {
8081 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8082 let chanmon_cfgs = create_chanmon_cfgs(2);
8083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8087 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8090 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200);
8091 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8092 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8093 check_added_monitors!(nodes[0], 1);
8094 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8095 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8096 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8097 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8099 // Note that after leaving the above scope we have no knowledge of any arguments or return
8100 // values from previous calls.
8101 expect_pending_htlcs_forwardable!(nodes[1]);
8102 let events = nodes[1].node.get_and_clear_pending_events();
8103 assert_eq!(events.len(), 1);
8105 Event::PaymentReceived { ref purpose, .. } => {
8107 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8108 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8110 _ => panic!("expected PaymentPurpose::InvoicePayment")
8113 _ => panic!("Unexpected event"),
8118 fn test_secret_timeout() {
8119 // Simple test of payment secret storage time outs
8120 let chanmon_cfgs = create_chanmon_cfgs(2);
8121 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8122 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8123 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8125 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8127 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2);
8129 // We should fail to register the same payment hash twice, at least until we've connected a
8130 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8131 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2) {
8132 assert_eq!(err, "Duplicate payment hash");
8133 } else { panic!(); }
8135 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8137 header: BlockHeader {
8139 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8140 merkle_root: Default::default(),
8141 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8145 connect_block(&nodes[1], &block);
8146 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2) {
8147 assert_eq!(err, "Duplicate payment hash");
8148 } else { panic!(); }
8150 // If we then connect the second block, we should be able to register the same payment hash
8151 // again (this time getting a new payment secret).
8152 block.header.prev_blockhash = block.header.block_hash();
8153 block.header.time += 1;
8154 connect_block(&nodes[1], &block);
8155 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2).unwrap();
8156 assert_ne!(payment_secret_1, our_payment_secret);
8159 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8160 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8161 check_added_monitors!(nodes[0], 1);
8162 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8163 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8164 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8165 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8167 // Note that after leaving the above scope we have no knowledge of any arguments or return
8168 // values from previous calls.
8169 expect_pending_htlcs_forwardable!(nodes[1]);
8170 let events = nodes[1].node.get_and_clear_pending_events();
8171 assert_eq!(events.len(), 1);
8173 Event::PaymentReceived { purpose: PaymentPurpose::InvoicePayment { payment_preimage, payment_secret }, .. } => {
8174 assert!(payment_preimage.is_none());
8175 assert_eq!(payment_secret, our_payment_secret);
8176 // We don't actually have the payment preimage with which to claim this payment!
8178 _ => panic!("Unexpected event"),
8183 fn test_bad_secret_hash() {
8184 // Simple test of unregistered payment hash/invalid payment secret handling
8185 let chanmon_cfgs = create_chanmon_cfgs(2);
8186 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8187 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8188 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8190 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8192 let random_payment_hash = PaymentHash([42; 32]);
8193 let random_payment_secret = PaymentSecret([43; 32]);
8194 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2);
8195 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8197 // All the below cases should end up being handled exactly identically, so we macro the
8198 // resulting events.
8199 macro_rules! handle_unknown_invalid_payment_data {
8201 check_added_monitors!(nodes[0], 1);
8202 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8203 let payment_event = SendEvent::from_event(events.pop().unwrap());
8204 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8205 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8207 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8208 // again to process the pending backwards-failure of the HTLC
8209 expect_pending_htlcs_forwardable!(nodes[1]);
8210 expect_pending_htlcs_forwardable!(nodes[1]);
8211 check_added_monitors!(nodes[1], 1);
8213 // We should fail the payment back
8214 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8215 match events.pop().unwrap() {
8216 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8217 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8218 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8220 _ => panic!("Unexpected event"),
8225 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8226 // Error data is the HTLC value (100,000) and current block height
8227 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8229 // Send a payment with the right payment hash but the wrong payment secret
8230 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8231 handle_unknown_invalid_payment_data!();
8232 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8234 // Send a payment with a random payment hash, but the right payment secret
8235 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8236 handle_unknown_invalid_payment_data!();
8237 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8239 // Send a payment with a random payment hash and random payment secret
8240 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8241 handle_unknown_invalid_payment_data!();
8242 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8246 fn test_update_err_monitor_lockdown() {
8247 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8248 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8249 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8251 // This scenario may happen in a watchtower setup, where watchtower process a block height
8252 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8253 // commitment at same time.
8255 let chanmon_cfgs = create_chanmon_cfgs(2);
8256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8258 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8260 // Create some initial channel
8261 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8262 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8264 // Rebalance the network to generate htlc in the two directions
8265 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8267 // Route a HTLC from node 0 to node 1 (but don't settle)
8268 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8270 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8271 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8272 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8273 let persister = test_utils::TestPersister::new();
8275 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8276 let mut w = test_utils::TestVecWriter(Vec::new());
8277 monitor.write(&mut w).unwrap();
8278 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8279 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8280 assert!(new_monitor == *monitor);
8281 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);
8282 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8285 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8286 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8287 // transaction lock time requirements here.
8288 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8289 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8291 // Try to update ChannelMonitor
8292 assert!(nodes[1].node.claim_funds(preimage));
8293 check_added_monitors!(nodes[1], 1);
8294 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8295 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8296 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8297 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8298 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8299 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8300 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8301 } else { assert!(false); }
8302 } else { assert!(false); };
8303 // Our local monitor is in-sync and hasn't processed yet timeout
8304 check_added_monitors!(nodes[0], 1);
8305 let events = nodes[0].node.get_and_clear_pending_events();
8306 assert_eq!(events.len(), 1);
8310 fn test_concurrent_monitor_claim() {
8311 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8312 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8313 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8314 // state N+1 confirms. Alice claims output from state N+1.
8316 let chanmon_cfgs = create_chanmon_cfgs(2);
8317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8319 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8321 // Create some initial channel
8322 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8323 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8325 // Rebalance the network to generate htlc in the two directions
8326 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8328 // Route a HTLC from node 0 to node 1 (but don't settle)
8329 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8331 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8332 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8333 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8334 let persister = test_utils::TestPersister::new();
8335 let watchtower_alice = {
8336 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8337 let mut w = test_utils::TestVecWriter(Vec::new());
8338 monitor.write(&mut w).unwrap();
8339 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8340 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8341 assert!(new_monitor == *monitor);
8342 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);
8343 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8346 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8347 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8348 // transaction lock time requirements here.
8349 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8350 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8352 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8354 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8355 assert_eq!(txn.len(), 2);
8359 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8360 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8361 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8362 let persister = test_utils::TestPersister::new();
8363 let watchtower_bob = {
8364 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8365 let mut w = test_utils::TestVecWriter(Vec::new());
8366 monitor.write(&mut w).unwrap();
8367 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8368 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8369 assert!(new_monitor == *monitor);
8370 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);
8371 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8374 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8375 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8377 // Route another payment to generate another update with still previous HTLC pending
8378 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8380 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8382 check_added_monitors!(nodes[1], 1);
8384 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8385 assert_eq!(updates.update_add_htlcs.len(), 1);
8386 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8387 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8388 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8389 // Watchtower Alice should already have seen the block and reject the update
8390 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8391 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8392 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8393 } else { assert!(false); }
8394 } else { assert!(false); };
8395 // Our local monitor is in-sync and hasn't processed yet timeout
8396 check_added_monitors!(nodes[0], 1);
8398 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8399 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8400 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8402 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8405 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8406 assert_eq!(txn.len(), 2);
8407 bob_state_y = txn[0].clone();
8411 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8412 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8413 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);
8415 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8416 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8417 // the onchain detection of the HTLC output
8418 assert_eq!(htlc_txn.len(), 2);
8419 check_spends!(htlc_txn[0], bob_state_y);
8420 check_spends!(htlc_txn[1], bob_state_y);
8425 fn test_pre_lockin_no_chan_closed_update() {
8426 // Test that if a peer closes a channel in response to a funding_created message we don't
8427 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8430 // Doing so would imply a channel monitor update before the initial channel monitor
8431 // registration, violating our API guarantees.
8433 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8434 // then opening a second channel with the same funding output as the first (which is not
8435 // rejected because the first channel does not exist in the ChannelManager) and closing it
8436 // before receiving funding_signed.
8437 let chanmon_cfgs = create_chanmon_cfgs(2);
8438 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8439 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8440 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8442 // Create an initial channel
8443 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8444 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8445 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8446 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8447 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8449 // Move the first channel through the funding flow...
8450 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8452 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8453 check_added_monitors!(nodes[0], 0);
8455 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8456 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8457 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8458 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8459 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8463 fn test_htlc_no_detection() {
8464 // This test is a mutation to underscore the detection logic bug we had
8465 // before #653. HTLC value routed is above the remaining balance, thus
8466 // inverting HTLC and `to_remote` output. HTLC will come second and
8467 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8468 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8469 // outputs order detection for correct spending children filtring.
8471 let chanmon_cfgs = create_chanmon_cfgs(2);
8472 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8473 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8474 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8476 // Create some initial channels
8477 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8479 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8480 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8481 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8482 assert_eq!(local_txn[0].input.len(), 1);
8483 assert_eq!(local_txn[0].output.len(), 3);
8484 check_spends!(local_txn[0], chan_1.3);
8486 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8487 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8488 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8489 // We deliberately connect the local tx twice as this should provoke a failure calling
8490 // this test before #653 fix.
8491 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);
8492 check_closed_broadcast!(nodes[0], true);
8493 check_added_monitors!(nodes[0], 1);
8494 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8495 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8497 let htlc_timeout = {
8498 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8499 assert_eq!(node_txn[1].input.len(), 1);
8500 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8501 check_spends!(node_txn[1], local_txn[0]);
8505 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8506 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8507 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8508 expect_payment_failed!(nodes[0], our_payment_hash, true);
8511 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8512 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8513 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8514 // Carol, Alice would be the upstream node, and Carol the downstream.)
8516 // Steps of the test:
8517 // 1) Alice sends a HTLC to Carol through Bob.
8518 // 2) Carol doesn't settle the HTLC.
8519 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8520 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8521 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8522 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8523 // 5) Carol release the preimage to Bob off-chain.
8524 // 6) Bob claims the offered output on the broadcasted commitment.
8525 let chanmon_cfgs = create_chanmon_cfgs(3);
8526 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8527 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8528 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8530 // Create some initial channels
8531 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8532 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8534 // Steps (1) and (2):
8535 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8536 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8538 // Check that Alice's commitment transaction now contains an output for this HTLC.
8539 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8540 check_spends!(alice_txn[0], chan_ab.3);
8541 assert_eq!(alice_txn[0].output.len(), 2);
8542 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8543 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8544 assert_eq!(alice_txn.len(), 2);
8546 // Steps (3) and (4):
8547 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8548 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8549 let mut force_closing_node = 0; // Alice force-closes
8550 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8551 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8552 check_closed_broadcast!(nodes[force_closing_node], true);
8553 check_added_monitors!(nodes[force_closing_node], 1);
8554 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8555 if go_onchain_before_fulfill {
8556 let txn_to_broadcast = match broadcast_alice {
8557 true => alice_txn.clone(),
8558 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8560 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8561 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8562 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8563 if broadcast_alice {
8564 check_closed_broadcast!(nodes[1], true);
8565 check_added_monitors!(nodes[1], 1);
8566 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8568 assert_eq!(bob_txn.len(), 1);
8569 check_spends!(bob_txn[0], chan_ab.3);
8573 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8574 // process of removing the HTLC from their commitment transactions.
8575 assert!(nodes[2].node.claim_funds(payment_preimage));
8576 check_added_monitors!(nodes[2], 1);
8577 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8578 assert!(carol_updates.update_add_htlcs.is_empty());
8579 assert!(carol_updates.update_fail_htlcs.is_empty());
8580 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8581 assert!(carol_updates.update_fee.is_none());
8582 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8584 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8585 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8586 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8587 if !go_onchain_before_fulfill && broadcast_alice {
8588 let events = nodes[1].node.get_and_clear_pending_msg_events();
8589 assert_eq!(events.len(), 1);
8591 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8592 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8594 _ => panic!("Unexpected event"),
8597 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8598 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8599 // Carol<->Bob's updated commitment transaction info.
8600 check_added_monitors!(nodes[1], 2);
8602 let events = nodes[1].node.get_and_clear_pending_msg_events();
8603 assert_eq!(events.len(), 2);
8604 let bob_revocation = match events[0] {
8605 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8606 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8609 _ => panic!("Unexpected event"),
8611 let bob_updates = match events[1] {
8612 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8613 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8616 _ => panic!("Unexpected event"),
8619 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8620 check_added_monitors!(nodes[2], 1);
8621 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8622 check_added_monitors!(nodes[2], 1);
8624 let events = nodes[2].node.get_and_clear_pending_msg_events();
8625 assert_eq!(events.len(), 1);
8626 let carol_revocation = match events[0] {
8627 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8628 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8631 _ => panic!("Unexpected event"),
8633 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8634 check_added_monitors!(nodes[1], 1);
8636 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8637 // here's where we put said channel's commitment tx on-chain.
8638 let mut txn_to_broadcast = alice_txn.clone();
8639 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8640 if !go_onchain_before_fulfill {
8641 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8642 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8643 // If Bob was the one to force-close, he will have already passed these checks earlier.
8644 if broadcast_alice {
8645 check_closed_broadcast!(nodes[1], true);
8646 check_added_monitors!(nodes[1], 1);
8647 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8649 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8650 if broadcast_alice {
8651 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8652 // new block being connected. The ChannelManager being notified triggers a monitor update,
8653 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8654 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8656 assert_eq!(bob_txn.len(), 3);
8657 check_spends!(bob_txn[1], chan_ab.3);
8659 assert_eq!(bob_txn.len(), 2);
8660 check_spends!(bob_txn[0], chan_ab.3);
8665 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8666 // broadcasted commitment transaction.
8668 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8669 if go_onchain_before_fulfill {
8670 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8671 assert_eq!(bob_txn.len(), 2);
8673 let script_weight = match broadcast_alice {
8674 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8675 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8677 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8678 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8679 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8680 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8681 if broadcast_alice && !go_onchain_before_fulfill {
8682 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8683 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8685 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8686 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8692 fn test_onchain_htlc_settlement_after_close() {
8693 do_test_onchain_htlc_settlement_after_close(true, true);
8694 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8695 do_test_onchain_htlc_settlement_after_close(true, false);
8696 do_test_onchain_htlc_settlement_after_close(false, false);
8700 fn test_duplicate_chan_id() {
8701 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8702 // already open we reject it and keep the old channel.
8704 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8705 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8706 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8707 // updating logic for the existing channel.
8708 let chanmon_cfgs = create_chanmon_cfgs(2);
8709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8711 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8713 // Create an initial channel
8714 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8715 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8716 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8717 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()));
8719 // Try to create a second channel with the same temporary_channel_id as the first and check
8720 // that it is rejected.
8721 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8723 let events = nodes[1].node.get_and_clear_pending_msg_events();
8724 assert_eq!(events.len(), 1);
8726 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8727 // Technically, at this point, nodes[1] would be justified in thinking both the
8728 // first (valid) and second (invalid) channels are closed, given they both have
8729 // the same non-temporary channel_id. However, currently we do not, so we just
8730 // move forward with it.
8731 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8732 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8734 _ => panic!("Unexpected event"),
8738 // Move the first channel through the funding flow...
8739 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8741 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8742 check_added_monitors!(nodes[0], 0);
8744 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8745 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8747 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8748 assert_eq!(added_monitors.len(), 1);
8749 assert_eq!(added_monitors[0].0, funding_output);
8750 added_monitors.clear();
8752 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8754 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8755 let channel_id = funding_outpoint.to_channel_id();
8757 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8760 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8761 // Technically this is allowed by the spec, but we don't support it and there's little reason
8762 // to. Still, it shouldn't cause any other issues.
8763 open_chan_msg.temporary_channel_id = channel_id;
8764 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8766 let events = nodes[1].node.get_and_clear_pending_msg_events();
8767 assert_eq!(events.len(), 1);
8769 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8770 // Technically, at this point, nodes[1] would be justified in thinking both
8771 // channels are closed, but currently we do not, so we just move forward with it.
8772 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8773 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8775 _ => panic!("Unexpected event"),
8779 // Now try to create a second channel which has a duplicate funding output.
8780 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8781 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8782 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8783 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()));
8784 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8786 let funding_created = {
8787 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8788 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8789 let logger = test_utils::TestLogger::new();
8790 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8792 check_added_monitors!(nodes[0], 0);
8793 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8794 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8795 // still needs to be cleared here.
8796 check_added_monitors!(nodes[1], 1);
8798 // ...still, nodes[1] will reject the duplicate channel.
8800 let events = nodes[1].node.get_and_clear_pending_msg_events();
8801 assert_eq!(events.len(), 1);
8803 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8804 // Technically, at this point, nodes[1] would be justified in thinking both
8805 // channels are closed, but currently we do not, so we just move forward with it.
8806 assert_eq!(msg.channel_id, channel_id);
8807 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8809 _ => panic!("Unexpected event"),
8813 // finally, finish creating the original channel and send a payment over it to make sure
8814 // everything is functional.
8815 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8817 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8818 assert_eq!(added_monitors.len(), 1);
8819 assert_eq!(added_monitors[0].0, funding_output);
8820 added_monitors.clear();
8823 let events_4 = nodes[0].node.get_and_clear_pending_events();
8824 assert_eq!(events_4.len(), 0);
8825 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8826 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8828 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8829 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8830 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8831 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8835 fn test_error_chans_closed() {
8836 // Test that we properly handle error messages, closing appropriate channels.
8838 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8839 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8840 // we can test various edge cases around it to ensure we don't regress.
8841 let chanmon_cfgs = create_chanmon_cfgs(3);
8842 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8843 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8844 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8846 // Create some initial channels
8847 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8848 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8849 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8851 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8852 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8853 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8855 // Closing a channel from a different peer has no effect
8856 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8857 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8859 // Closing one channel doesn't impact others
8860 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8861 check_added_monitors!(nodes[0], 1);
8862 check_closed_broadcast!(nodes[0], false);
8863 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8864 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8865 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8866 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);
8867 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);
8869 // A null channel ID should close all channels
8870 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8871 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8872 check_added_monitors!(nodes[0], 2);
8873 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8874 let events = nodes[0].node.get_and_clear_pending_msg_events();
8875 assert_eq!(events.len(), 2);
8877 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8878 assert_eq!(msg.contents.flags & 2, 2);
8880 _ => panic!("Unexpected event"),
8883 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8884 assert_eq!(msg.contents.flags & 2, 2);
8886 _ => panic!("Unexpected event"),
8888 // Note that at this point users of a standard PeerHandler will end up calling
8889 // peer_disconnected with no_connection_possible set to false, duplicating the
8890 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8891 // users with their own peer handling logic. We duplicate the call here, however.
8892 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8893 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8895 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8896 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8897 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8901 fn test_invalid_funding_tx() {
8902 // Test that we properly handle invalid funding transactions sent to us from a peer.
8904 // Previously, all other major lightning implementations had failed to properly sanitize
8905 // funding transactions from their counterparties, leading to a multi-implementation critical
8906 // security vulnerability (though we always sanitized properly, we've previously had
8907 // un-released crashes in the sanitization process).
8908 let chanmon_cfgs = create_chanmon_cfgs(2);
8909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8911 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8913 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8914 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()));
8915 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()));
8917 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8918 for output in tx.output.iter_mut() {
8919 // Make the confirmed funding transaction have a bogus script_pubkey
8920 output.script_pubkey = bitcoin::Script::new();
8923 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8924 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()));
8925 check_added_monitors!(nodes[1], 1);
8927 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()));
8928 check_added_monitors!(nodes[0], 1);
8930 let events_1 = nodes[0].node.get_and_clear_pending_events();
8931 assert_eq!(events_1.len(), 0);
8933 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8934 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8935 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8937 let expected_err = "funding tx had wrong script/value or output index";
8938 confirm_transaction_at(&nodes[1], &tx, 1);
8939 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() });
8940 check_added_monitors!(nodes[1], 1);
8941 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8942 assert_eq!(events_2.len(), 1);
8943 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8944 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8945 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8946 assert_eq!(msg.data, "Channel closed because of an exception: ".to_owned() + expected_err);
8947 } else { panic!(); }
8948 } else { panic!(); }
8949 assert_eq!(nodes[1].node.list_channels().len(), 0);
8952 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8953 // In the first version of the chain::Confirm interface, after a refactor was made to not
8954 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8955 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8956 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8957 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8958 // spending transaction until height N+1 (or greater). This was due to the way
8959 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8960 // spending transaction at the height the input transaction was confirmed at, not whether we
8961 // should broadcast a spending transaction at the current height.
8962 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8963 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8964 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8965 // until we learned about an additional block.
8967 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8968 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8969 let chanmon_cfgs = create_chanmon_cfgs(3);
8970 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8971 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8972 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8973 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8975 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8976 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8977 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8978 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8979 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8981 nodes[1].node.force_close_channel(&channel_id).unwrap();
8982 check_closed_broadcast!(nodes[1], true);
8983 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8984 check_added_monitors!(nodes[1], 1);
8985 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8986 assert_eq!(node_txn.len(), 1);
8988 let conf_height = nodes[1].best_block_info().1;
8989 if !test_height_before_timelock {
8990 connect_blocks(&nodes[1], 24 * 6);
8992 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8993 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8994 if test_height_before_timelock {
8995 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8996 // generate any events or broadcast any transactions
8997 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8998 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9000 // We should broadcast an HTLC transaction spending our funding transaction first
9001 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9002 assert_eq!(spending_txn.len(), 2);
9003 assert_eq!(spending_txn[0], node_txn[0]);
9004 check_spends!(spending_txn[1], node_txn[0]);
9005 // We should also generate a SpendableOutputs event with the to_self output (as its
9007 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9008 assert_eq!(descriptor_spend_txn.len(), 1);
9010 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9011 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9012 // additional block built on top of the current chain.
9013 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9014 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9015 expect_pending_htlcs_forwardable!(nodes[1]);
9016 check_added_monitors!(nodes[1], 1);
9018 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9019 assert!(updates.update_add_htlcs.is_empty());
9020 assert!(updates.update_fulfill_htlcs.is_empty());
9021 assert_eq!(updates.update_fail_htlcs.len(), 1);
9022 assert!(updates.update_fail_malformed_htlcs.is_empty());
9023 assert!(updates.update_fee.is_none());
9024 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9025 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9026 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9031 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9032 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9033 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9037 fn test_forwardable_regen() {
9038 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9039 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9041 // We test it for both payment receipt and payment forwarding.
9043 let chanmon_cfgs = create_chanmon_cfgs(3);
9044 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9045 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9046 let persister: test_utils::TestPersister;
9047 let new_chain_monitor: test_utils::TestChainMonitor;
9048 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9049 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9050 let chan_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
9051 let chan_id_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known()).2;
9053 // First send a payment to nodes[1]
9054 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9055 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9056 check_added_monitors!(nodes[0], 1);
9058 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9059 assert_eq!(events.len(), 1);
9060 let payment_event = SendEvent::from_event(events.pop().unwrap());
9061 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9062 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9064 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9066 // Next send a payment which is forwarded by nodes[1]
9067 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9068 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9069 check_added_monitors!(nodes[0], 1);
9071 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9072 assert_eq!(events.len(), 1);
9073 let payment_event = SendEvent::from_event(events.pop().unwrap());
9074 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9075 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9077 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9079 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9081 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9082 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9083 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9085 let nodes_1_serialized = nodes[1].node.encode();
9086 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9087 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9088 get_monitor!(nodes[1], chan_id_1).write(&mut chan_0_monitor_serialized).unwrap();
9089 get_monitor!(nodes[1], chan_id_2).write(&mut chan_1_monitor_serialized).unwrap();
9091 persister = test_utils::TestPersister::new();
9092 let keys_manager = &chanmon_cfgs[1].keys_manager;
9093 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);
9094 nodes[1].chain_monitor = &new_chain_monitor;
9096 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9097 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9098 &mut chan_0_monitor_read, keys_manager).unwrap();
9099 assert!(chan_0_monitor_read.is_empty());
9100 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9101 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9102 &mut chan_1_monitor_read, keys_manager).unwrap();
9103 assert!(chan_1_monitor_read.is_empty());
9105 let mut nodes_1_read = &nodes_1_serialized[..];
9106 let (_, nodes_1_deserialized_tmp) = {
9107 let mut channel_monitors = HashMap::new();
9108 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9109 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9110 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9111 default_config: UserConfig::default(),
9113 fee_estimator: node_cfgs[1].fee_estimator,
9114 chain_monitor: nodes[1].chain_monitor,
9115 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9116 logger: nodes[1].logger,
9120 nodes_1_deserialized = nodes_1_deserialized_tmp;
9121 assert!(nodes_1_read.is_empty());
9123 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9124 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9125 nodes[1].node = &nodes_1_deserialized;
9126 check_added_monitors!(nodes[1], 2);
9128 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9129 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9130 // the commitment state.
9131 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9133 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9135 expect_pending_htlcs_forwardable!(nodes[1]);
9136 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9137 check_added_monitors!(nodes[1], 1);
9139 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9140 assert_eq!(events.len(), 1);
9141 let payment_event = SendEvent::from_event(events.pop().unwrap());
9142 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9143 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9144 expect_pending_htlcs_forwardable!(nodes[2]);
9145 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9147 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9148 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9152 fn test_keysend_payments_to_public_node() {
9153 let chanmon_cfgs = create_chanmon_cfgs(2);
9154 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9155 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9156 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9158 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9159 let network_graph = nodes[0].network_graph;
9160 let payer_pubkey = nodes[0].node.get_our_node_id();
9161 let payee_pubkey = nodes[1].node.get_our_node_id();
9162 let params = RouteParameters {
9163 payee: Payee::for_keysend(payee_pubkey),
9164 final_value_msat: 10000,
9165 final_cltv_expiry_delta: 40,
9167 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9168 let route = find_route(&payer_pubkey, ¶ms, network_graph, None, nodes[0].logger, &scorer).unwrap();
9170 let test_preimage = PaymentPreimage([42; 32]);
9171 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9172 check_added_monitors!(nodes[0], 1);
9173 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9174 assert_eq!(events.len(), 1);
9175 let event = events.pop().unwrap();
9176 let path = vec![&nodes[1]];
9177 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9178 claim_payment(&nodes[0], &path, test_preimage);
9182 fn test_keysend_payments_to_private_node() {
9183 let chanmon_cfgs = create_chanmon_cfgs(2);
9184 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9185 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9186 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9188 let payer_pubkey = nodes[0].node.get_our_node_id();
9189 let payee_pubkey = nodes[1].node.get_our_node_id();
9190 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9191 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9193 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9194 let params = RouteParameters {
9195 payee: Payee::for_keysend(payee_pubkey),
9196 final_value_msat: 10000,
9197 final_cltv_expiry_delta: 40,
9199 let network_graph = nodes[0].network_graph;
9200 let first_hops = nodes[0].node.list_usable_channels();
9201 let scorer = test_utils::TestScorer::with_fixed_penalty(0);
9202 let route = find_route(
9203 &payer_pubkey, ¶ms, network_graph, Some(&first_hops.iter().collect::<Vec<_>>()),
9204 nodes[0].logger, &scorer
9207 let test_preimage = PaymentPreimage([42; 32]);
9208 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9209 check_added_monitors!(nodes[0], 1);
9210 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9211 assert_eq!(events.len(), 1);
9212 let event = events.pop().unwrap();
9213 let path = vec![&nodes[1]];
9214 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9215 claim_payment(&nodes[0], &path, test_preimage);
9218 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9219 #[derive(Clone, Copy, PartialEq)]
9220 enum ExposureEvent {
9221 /// Breach occurs at HTLC forwarding (see `send_htlc`)
9223 /// Breach occurs at HTLC reception (see `update_add_htlc`)
9225 /// Breach occurs at outbound update_fee (see `send_update_fee`)
9226 AtUpdateFeeOutbound,
9229 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool) {
9230 // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9233 // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9234 // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9235 // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9236 // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9237 // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9238 // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9239 // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9240 // might be available again for HTLC processing once the dust bandwidth has cleared up.
9242 let chanmon_cfgs = create_chanmon_cfgs(2);
9243 let mut config = test_default_channel_config();
9244 config.channel_options.max_dust_htlc_exposure_msat = 5_000_000; // default setting value
9245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9247 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9249 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
9250 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9251 open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9252 open_channel.max_accepted_htlcs = 60;
9254 open_channel.dust_limit_satoshis = 546;
9256 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
9257 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9258 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
9260 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 1_000_000, 42);
9263 if let Some(mut chan) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&temporary_channel_id) {
9264 chan.holder_dust_limit_satoshis = 546;
9268 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9269 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()));
9270 check_added_monitors!(nodes[1], 1);
9272 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()));
9273 check_added_monitors!(nodes[0], 1);
9275 let (funding_locked, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9276 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9277 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9279 let dust_buffer_feerate = {
9280 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
9281 let chan = chan_lock.by_id.get(&channel_id).unwrap();
9282 chan.get_dust_buffer_feerate(None) as u64
9284 let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_TIMEOUT_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9285 let dust_outbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9287 let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * HTLC_SUCCESS_TX_WEIGHT / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9288 let dust_inbound_htlc_on_holder_tx: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9290 let dust_htlc_on_counterparty_tx: u64 = 25;
9291 let dust_htlc_on_counterparty_tx_msat: u64 = config.channel_options.max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9294 if dust_outbound_balance {
9295 // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9296 // Outbound dust balance: 4372 sats
9297 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9298 for i in 0..dust_outbound_htlc_on_holder_tx {
9299 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9300 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9303 // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9304 // Inbound dust balance: 4372 sats
9305 // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9306 for _ in 0..dust_inbound_htlc_on_holder_tx {
9307 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9311 if dust_outbound_balance {
9312 // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9313 // Outbound dust balance: 5000 sats
9314 for i in 0..dust_htlc_on_counterparty_tx {
9315 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9316 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at dust HTLC {}", i); }
9319 // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9320 // Inbound dust balance: 5000 sats
9321 for _ in 0..dust_htlc_on_counterparty_tx {
9322 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9327 let dust_overflow = dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx + 1);
9328 if exposure_breach_event == ExposureEvent::AtHTLCForward {
9329 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9330 let mut config = UserConfig::default();
9331 // With default dust exposure: 5000 sats
9333 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * (dust_outbound_htlc_on_holder_tx + 1);
9334 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * dust_inbound_htlc_on_holder_tx + dust_outbound_htlc_on_holder_tx_msat;
9335 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat)));
9337 unwrap_send_err!(nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable { ref err }, assert_eq!(err, &format!("Cannot send value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat)));
9339 } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9340 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat });
9341 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9342 check_added_monitors!(nodes[1], 1);
9343 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9344 assert_eq!(events.len(), 1);
9345 let payment_event = SendEvent::from_event(events.remove(0));
9346 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9347 // With default dust exposure: 5000 sats
9349 // Outbound dust balance: 6399 sats
9350 let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9351 let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9352 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, config.channel_options.max_dust_htlc_exposure_msat), 1);
9354 // Outbound dust balance: 5200 sats
9355 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx", dust_overflow, config.channel_options.max_dust_htlc_exposure_msat), 1);
9357 } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9358 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 2_500_000);
9359 if let Err(_) = nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)) { panic!("Unexpected event at update_fee-swallowed HTLC", ); }
9361 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9362 *feerate_lock = *feerate_lock * 10;
9364 nodes[0].node.timer_tick_occurred();
9365 check_added_monitors!(nodes[0], 1);
9366 nodes[0].logger.assert_log_contains("lightning::ln::channel".to_string(), "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure".to_string(), 1);
9369 let _ = nodes[0].node.get_and_clear_pending_msg_events();
9370 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9371 added_monitors.clear();
9375 fn test_max_dust_htlc_exposure() {
9376 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true);
9377 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true);
9378 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true);
9379 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false);
9380 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false);
9381 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false);
9382 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true);
9383 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false);
9384 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true);
9385 do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false);
9386 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false);
9387 do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true);