1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::{Confirm, Listen, Watch};
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::BaseSign;
20 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
21 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
22 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, PaymentId, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
23 use ln::channel::{Channel, ChannelError};
24 use ln::{chan_utils, onion_utils};
25 use ln::chan_utils::HTLC_SUCCESS_TX_WEIGHT;
26 use routing::network_graph::{NetworkUpdate, RoutingFees};
27 use routing::router::{Route, RouteHop, RouteHint, RouteHintHop, get_route, get_keysend_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::{Txid, BlockHash};
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::script::Builder;
41 use bitcoin::blockdata::opcodes;
42 use bitcoin::blockdata::constants::genesis_block;
43 use bitcoin::network::constants::Network;
45 use bitcoin::hashes::sha256::Hash as Sha256;
46 use bitcoin::hashes::Hash;
48 use bitcoin::secp256k1::Secp256k1;
49 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
55 use alloc::collections::BTreeSet;
56 use core::default::Default;
57 use sync::{Arc, Mutex};
59 use ln::functional_test_utils::*;
60 use ln::chan_utils::CommitmentTransaction;
63 fn test_insane_channel_opens() {
64 // Stand up a network of 2 nodes
65 let chanmon_cfgs = create_chanmon_cfgs(2);
66 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
67 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
68 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
70 // Instantiate channel parameters where we push the maximum msats given our
72 let channel_value_sat = 31337; // same as funding satoshis
73 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
74 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
76 // Have node0 initiate a channel to node1 with aforementioned parameters
77 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
79 // Extract the channel open message from node0 to node1
80 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
82 // Test helper that asserts we get the correct error string given a mutator
83 // that supposedly makes the channel open message insane
84 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
85 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
86 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
87 assert_eq!(msg_events.len(), 1);
88 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
89 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
91 &ErrorAction::SendErrorMessage { .. } => {
92 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
94 _ => panic!("unexpected event!"),
96 } else { assert!(false); }
99 use ln::channel::MAX_FUNDING_SATOSHIS;
100 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
102 // Test all mutations that would make the channel open message insane
103 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
105 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
107 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
109 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
111 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
113 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
115 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
117 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
119 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
123 fn test_async_inbound_update_fee() {
124 let chanmon_cfgs = create_chanmon_cfgs(2);
125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
127 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
128 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
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 = 1888;
588 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
589 let channel_id = chan.2;
593 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
594 *feerate_lock = feerate;
596 nodes[0].node.timer_tick_occurred();
597 check_added_monitors!(nodes[0], 1);
598 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
600 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
602 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
604 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
605 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
607 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
609 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
610 let num_htlcs = commitment_tx.output.len() - 2;
611 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
612 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
613 actual_fee = channel_value - actual_fee;
614 assert_eq!(total_fee, actual_fee);
617 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
618 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
620 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
621 *feerate_lock = feerate + 2;
623 nodes[0].node.timer_tick_occurred();
624 check_added_monitors!(nodes[0], 1);
626 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
628 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
630 //While producing the commitment_signed response after handling a received update_fee request the
631 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
632 //Should produce and error.
633 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
634 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
635 check_added_monitors!(nodes[1], 1);
636 check_closed_broadcast!(nodes[1], true);
637 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") });
641 fn test_update_fee_with_fundee_update_add_htlc() {
642 let chanmon_cfgs = create_chanmon_cfgs(2);
643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
645 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
646 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
649 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
652 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
655 nodes[0].node.timer_tick_occurred();
656 check_added_monitors!(nodes[0], 1);
658 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
659 assert_eq!(events_0.len(), 1);
660 let (update_msg, commitment_signed) = match events_0[0] {
661 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 } } => {
662 (update_fee.as_ref(), commitment_signed)
664 _ => panic!("Unexpected event"),
666 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
667 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
668 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
669 check_added_monitors!(nodes[1], 1);
671 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
673 // nothing happens since node[1] is in AwaitingRemoteRevoke
674 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
676 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
677 assert_eq!(added_monitors.len(), 0);
678 added_monitors.clear();
680 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
681 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
682 // node[1] has nothing to do
684 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
685 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
686 check_added_monitors!(nodes[0], 1);
688 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
689 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
690 // No commitment_signed so get_event_msg's assert(len == 1) passes
691 check_added_monitors!(nodes[0], 1);
692 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
693 check_added_monitors!(nodes[1], 1);
694 // AwaitingRemoteRevoke ends here
696 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
697 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
698 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
699 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
700 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
701 assert_eq!(commitment_update.update_fee.is_none(), true);
703 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
704 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
705 check_added_monitors!(nodes[0], 1);
706 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
708 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
709 check_added_monitors!(nodes[1], 1);
710 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
712 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
713 check_added_monitors!(nodes[1], 1);
714 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
715 // No commitment_signed so get_event_msg's assert(len == 1) passes
717 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
718 check_added_monitors!(nodes[0], 1);
719 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
721 expect_pending_htlcs_forwardable!(nodes[0]);
723 let events = nodes[0].node.get_and_clear_pending_events();
724 assert_eq!(events.len(), 1);
726 Event::PaymentReceived { .. } => { },
727 _ => panic!("Unexpected event"),
730 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
732 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
733 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
734 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
735 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
736 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
740 fn test_update_fee() {
741 let chanmon_cfgs = create_chanmon_cfgs(2);
742 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
743 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
744 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
745 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
746 let channel_id = chan.2;
749 // (1) update_fee/commitment_signed ->
750 // <- (2) revoke_and_ack
751 // .- send (3) commitment_signed
752 // (4) update_fee/commitment_signed ->
753 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
754 // <- (3) commitment_signed delivered
755 // send (6) revoke_and_ack -.
756 // <- (5) deliver revoke_and_ack
757 // (6) deliver revoke_and_ack ->
758 // .- send (7) commitment_signed in response to (4)
759 // <- (7) deliver commitment_signed
762 // Create and deliver (1)...
765 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
766 feerate = *feerate_lock;
767 *feerate_lock = feerate + 20;
769 nodes[0].node.timer_tick_occurred();
770 check_added_monitors!(nodes[0], 1);
772 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
773 assert_eq!(events_0.len(), 1);
774 let (update_msg, commitment_signed) = match events_0[0] {
775 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 } } => {
776 (update_fee.as_ref(), commitment_signed)
778 _ => panic!("Unexpected event"),
780 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
782 // Generate (2) and (3):
783 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
785 check_added_monitors!(nodes[1], 1);
788 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
789 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
790 check_added_monitors!(nodes[0], 1);
792 // Create and deliver (4)...
794 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
795 *feerate_lock = feerate + 30;
797 nodes[0].node.timer_tick_occurred();
798 check_added_monitors!(nodes[0], 1);
799 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
800 assert_eq!(events_0.len(), 1);
801 let (update_msg, commitment_signed) = match events_0[0] {
802 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 } } => {
803 (update_fee.as_ref(), commitment_signed)
805 _ => panic!("Unexpected event"),
808 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
809 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
810 check_added_monitors!(nodes[1], 1);
812 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
813 // No commitment_signed so get_event_msg's assert(len == 1) passes
815 // Handle (3), creating (6):
816 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
817 check_added_monitors!(nodes[0], 1);
818 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
819 // No commitment_signed so get_event_msg's assert(len == 1) passes
822 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
823 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
824 check_added_monitors!(nodes[0], 1);
826 // Deliver (6), creating (7):
827 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
828 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
829 assert!(commitment_update.update_add_htlcs.is_empty());
830 assert!(commitment_update.update_fulfill_htlcs.is_empty());
831 assert!(commitment_update.update_fail_htlcs.is_empty());
832 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
833 assert!(commitment_update.update_fee.is_none());
834 check_added_monitors!(nodes[1], 1);
837 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
838 check_added_monitors!(nodes[0], 1);
839 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
840 // No commitment_signed so get_event_msg's assert(len == 1) passes
842 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
843 check_added_monitors!(nodes[1], 1);
844 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
846 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
847 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
848 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
849 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
850 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
854 fn fake_network_test() {
855 // Simple test which builds a network of ChannelManagers, connects them to each other, and
856 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
857 let chanmon_cfgs = create_chanmon_cfgs(4);
858 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
859 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
860 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
862 // Create some initial channels
863 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
864 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
865 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
867 // Rebalance the network a bit by relaying one payment through all the channels...
868 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
869 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
870 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
871 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
873 // Send some more payments
874 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
875 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
876 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
878 // Test failure packets
879 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
880 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
882 // Add a new channel that skips 3
883 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
885 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
886 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
887 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
888 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
889 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
890 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
891 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
893 // Do some rebalance loop payments, simultaneously
894 let mut hops = Vec::with_capacity(3);
896 pubkey: nodes[2].node.get_our_node_id(),
897 node_features: NodeFeatures::empty(),
898 short_channel_id: chan_2.0.contents.short_channel_id,
899 channel_features: ChannelFeatures::empty(),
901 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
904 pubkey: nodes[3].node.get_our_node_id(),
905 node_features: NodeFeatures::empty(),
906 short_channel_id: chan_3.0.contents.short_channel_id,
907 channel_features: ChannelFeatures::empty(),
909 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
912 pubkey: nodes[1].node.get_our_node_id(),
913 node_features: NodeFeatures::known(),
914 short_channel_id: chan_4.0.contents.short_channel_id,
915 channel_features: ChannelFeatures::known(),
917 cltv_expiry_delta: TEST_FINAL_CLTV,
919 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;
920 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;
921 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
923 let mut hops = Vec::with_capacity(3);
925 pubkey: nodes[3].node.get_our_node_id(),
926 node_features: NodeFeatures::empty(),
927 short_channel_id: chan_4.0.contents.short_channel_id,
928 channel_features: ChannelFeatures::empty(),
930 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
933 pubkey: nodes[2].node.get_our_node_id(),
934 node_features: NodeFeatures::empty(),
935 short_channel_id: chan_3.0.contents.short_channel_id,
936 channel_features: ChannelFeatures::empty(),
938 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
941 pubkey: nodes[1].node.get_our_node_id(),
942 node_features: NodeFeatures::known(),
943 short_channel_id: chan_2.0.contents.short_channel_id,
944 channel_features: ChannelFeatures::known(),
946 cltv_expiry_delta: TEST_FINAL_CLTV,
948 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;
949 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;
950 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
952 // Claim the rebalances...
953 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
954 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
956 // Add a duplicate new channel from 2 to 4
957 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
959 // Send some payments across both channels
960 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
961 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
962 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
965 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
966 let events = nodes[0].node.get_and_clear_pending_msg_events();
967 assert_eq!(events.len(), 0);
968 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);
970 //TODO: Test that routes work again here as we've been notified that the channel is full
972 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
973 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
974 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
976 // Close down the channels...
977 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
978 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
979 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
980 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
981 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
982 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
983 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
984 check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure);
985 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
986 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
987 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
988 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
989 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
990 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
991 check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure);
995 fn holding_cell_htlc_counting() {
996 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
997 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
998 // commitment dance rounds.
999 let chanmon_cfgs = create_chanmon_cfgs(3);
1000 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1001 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1002 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1003 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1004 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1006 let mut payments = Vec::new();
1007 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1008 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1009 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1010 payments.push((payment_preimage, payment_hash));
1012 check_added_monitors!(nodes[1], 1);
1014 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1015 assert_eq!(events.len(), 1);
1016 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1017 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1019 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1020 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1022 let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1024 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1025 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1026 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1027 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1030 // This should also be true if we try to forward a payment.
1031 let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1033 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1034 check_added_monitors!(nodes[0], 1);
1037 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1038 assert_eq!(events.len(), 1);
1039 let payment_event = SendEvent::from_event(events.pop().unwrap());
1040 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1042 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1043 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1044 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1045 // fails), the second will process the resulting failure and fail the HTLC backward.
1046 expect_pending_htlcs_forwardable!(nodes[1]);
1047 expect_pending_htlcs_forwardable!(nodes[1]);
1048 check_added_monitors!(nodes[1], 1);
1050 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1051 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1052 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1054 expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1056 // Now forward all the pending HTLCs and claim them back
1057 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1058 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1059 check_added_monitors!(nodes[2], 1);
1061 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1062 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1063 check_added_monitors!(nodes[1], 1);
1064 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1066 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1067 check_added_monitors!(nodes[1], 1);
1068 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1070 for ref update in as_updates.update_add_htlcs.iter() {
1071 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1073 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1074 check_added_monitors!(nodes[2], 1);
1075 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1076 check_added_monitors!(nodes[2], 1);
1077 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1079 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1080 check_added_monitors!(nodes[1], 1);
1081 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1082 check_added_monitors!(nodes[1], 1);
1083 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1085 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1086 check_added_monitors!(nodes[2], 1);
1088 expect_pending_htlcs_forwardable!(nodes[2]);
1090 let events = nodes[2].node.get_and_clear_pending_events();
1091 assert_eq!(events.len(), payments.len());
1092 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1094 &Event::PaymentReceived { ref payment_hash, .. } => {
1095 assert_eq!(*payment_hash, *hash);
1097 _ => panic!("Unexpected event"),
1101 for (preimage, _) in payments.drain(..) {
1102 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1105 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1109 fn duplicate_htlc_test() {
1110 // Test that we accept duplicate payment_hash HTLCs across the network and that
1111 // claiming/failing them are all separate and don't affect each other
1112 let chanmon_cfgs = create_chanmon_cfgs(6);
1113 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1114 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1115 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1117 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1118 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1119 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1120 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1121 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1122 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1124 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1126 *nodes[0].network_payment_count.borrow_mut() -= 1;
1127 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1129 *nodes[0].network_payment_count.borrow_mut() -= 1;
1130 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1132 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1133 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1134 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1138 fn test_duplicate_htlc_different_direction_onchain() {
1139 // Test that ChannelMonitor doesn't generate 2 preimage txn
1140 // when we have 2 HTLCs with same preimage that go across a node
1141 // in opposite directions, even with the same payment secret.
1142 let chanmon_cfgs = create_chanmon_cfgs(2);
1143 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1144 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1145 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1147 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1150 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1152 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1154 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1155 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1156 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1158 // Provide preimage to node 0 by claiming payment
1159 nodes[0].node.claim_funds(payment_preimage);
1160 check_added_monitors!(nodes[0], 1);
1162 // Broadcast node 1 commitment txn
1163 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1165 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1166 let mut has_both_htlcs = 0; // check htlcs match ones committed
1167 for outp in remote_txn[0].output.iter() {
1168 if outp.value == 800_000 / 1000 {
1169 has_both_htlcs += 1;
1170 } else if outp.value == 900_000 / 1000 {
1171 has_both_htlcs += 1;
1174 assert_eq!(has_both_htlcs, 2);
1176 mine_transaction(&nodes[0], &remote_txn[0]);
1177 check_added_monitors!(nodes[0], 1);
1178 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
1179 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1181 // Check we only broadcast 1 timeout tx
1182 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1183 assert_eq!(claim_txn.len(), 8);
1184 assert_eq!(claim_txn[1], claim_txn[4]);
1185 assert_eq!(claim_txn[2], claim_txn[5]);
1186 check_spends!(claim_txn[1], chan_1.3);
1187 check_spends!(claim_txn[2], claim_txn[1]);
1188 check_spends!(claim_txn[7], claim_txn[1]);
1190 assert_eq!(claim_txn[0].input.len(), 1);
1191 assert_eq!(claim_txn[3].input.len(), 1);
1192 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1194 assert_eq!(claim_txn[0].input.len(), 1);
1195 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1196 check_spends!(claim_txn[0], remote_txn[0]);
1197 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1198 assert_eq!(claim_txn[6].input.len(), 1);
1199 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1200 check_spends!(claim_txn[6], remote_txn[0]);
1201 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1203 let events = nodes[0].node.get_and_clear_pending_msg_events();
1204 assert_eq!(events.len(), 3);
1207 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1208 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1209 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1210 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1212 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, .. } } => {
1213 assert!(update_add_htlcs.is_empty());
1214 assert!(update_fail_htlcs.is_empty());
1215 assert_eq!(update_fulfill_htlcs.len(), 1);
1216 assert!(update_fail_malformed_htlcs.is_empty());
1217 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1219 _ => panic!("Unexpected event"),
1225 fn test_basic_channel_reserve() {
1226 let chanmon_cfgs = create_chanmon_cfgs(2);
1227 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1228 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1229 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1230 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1232 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1233 let channel_reserve = chan_stat.channel_reserve_msat;
1235 // The 2* and +1 are for the fee spike reserve.
1236 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1237 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1238 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send + 1);
1239 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1241 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1243 &APIError::ChannelUnavailable{ref err} =>
1244 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1245 _ => panic!("Unexpected error variant"),
1248 _ => panic!("Unexpected error variant"),
1250 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1251 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);
1253 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1257 fn test_fee_spike_violation_fails_htlc() {
1258 let chanmon_cfgs = create_chanmon_cfgs(2);
1259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1261 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1262 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1264 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1265 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1266 let secp_ctx = Secp256k1::new();
1267 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1269 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1271 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1272 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height, &None).unwrap();
1273 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1274 let msg = msgs::UpdateAddHTLC {
1277 amount_msat: htlc_msat,
1278 payment_hash: payment_hash,
1279 cltv_expiry: htlc_cltv,
1280 onion_routing_packet: onion_packet,
1283 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1285 // Now manually create the commitment_signed message corresponding to the update_add
1286 // nodes[0] just sent. In the code for construction of this message, "local" refers
1287 // to the sender of the message, and "remote" refers to the receiver.
1289 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1291 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1293 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1294 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1295 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1296 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1297 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1298 let chan_signer = local_chan.get_signer();
1299 // Make the signer believe we validated another commitment, so we can release the secret
1300 chan_signer.get_enforcement_state().last_holder_commitment -= 1;
1302 let pubkeys = chan_signer.pubkeys();
1303 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1304 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1305 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1306 chan_signer.pubkeys().funding_pubkey)
1308 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1309 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1310 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1311 let chan_signer = remote_chan.get_signer();
1312 let pubkeys = chan_signer.pubkeys();
1313 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1314 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1315 chan_signer.pubkeys().funding_pubkey)
1318 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1319 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1320 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1322 // Build the remote commitment transaction so we can sign it, and then later use the
1323 // signature for the commitment_signed message.
1324 let local_chan_balance = 1313;
1326 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1328 amount_msat: 3460001,
1329 cltv_expiry: htlc_cltv,
1331 transaction_output_index: Some(1),
1334 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1337 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1338 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1339 let local_chan_signer = local_chan.get_signer();
1340 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1344 false, local_funding, remote_funding,
1345 commit_tx_keys.clone(),
1347 &mut vec![(accepted_htlc_info, ())],
1348 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1350 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1353 let commit_signed_msg = msgs::CommitmentSigned {
1356 htlc_signatures: res.1
1359 // Send the commitment_signed message to the nodes[1].
1360 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1361 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1363 // Send the RAA to nodes[1].
1364 let raa_msg = msgs::RevokeAndACK {
1366 per_commitment_secret: local_secret,
1367 next_per_commitment_point: next_local_point
1369 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1371 let events = nodes[1].node.get_and_clear_pending_msg_events();
1372 assert_eq!(events.len(), 1);
1373 // Make sure the HTLC failed in the way we expect.
1375 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1376 assert_eq!(update_fail_htlcs.len(), 1);
1377 update_fail_htlcs[0].clone()
1379 _ => panic!("Unexpected event"),
1381 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1382 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1384 check_added_monitors!(nodes[1], 2);
1388 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1389 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1390 // Set the fee rate for the channel very high, to the point where the fundee
1391 // sending any above-dust amount would result in a channel reserve violation.
1392 // In this test we check that we would be prevented from sending an HTLC in
1394 let feerate_per_kw = 253;
1395 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1396 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1397 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1398 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1399 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1401 let mut push_amt = 100_000_000;
1402 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT + COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
1403 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1405 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt, InitFeatures::known(), InitFeatures::known());
1407 // Sending exactly enough to hit the reserve amount should be accepted
1408 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1410 // However one more HTLC should be significantly over the reserve amount and fail.
1411 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1412 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1413 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1414 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1415 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);
1419 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1420 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1421 // Set the fee rate for the channel very high, to the point where the funder
1422 // receiving 1 update_add_htlc would result in them closing the channel due
1423 // to channel reserve violation. This close could also happen if the fee went
1424 // up a more realistic amount, but many HTLCs were outstanding at the time of
1425 // the update_add_htlc.
1426 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1427 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(6000) };
1428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1430 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1431 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1433 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1434 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1435 let secp_ctx = Secp256k1::new();
1436 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1437 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1438 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1439 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height, &None).unwrap();
1440 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1441 let msg = msgs::UpdateAddHTLC {
1444 amount_msat: htlc_msat + 1,
1445 payment_hash: payment_hash,
1446 cltv_expiry: htlc_cltv,
1447 onion_routing_packet: onion_packet,
1450 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1451 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1452 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);
1453 assert_eq!(nodes[0].node.list_channels().len(), 0);
1454 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1455 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1456 check_added_monitors!(nodes[0], 1);
1457 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() });
1461 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1462 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1463 // calculating our commitment transaction fee (this was previously broken).
1464 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1465 let feerate_per_kw = 253;
1466 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1467 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(feerate_per_kw) };
1469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1471 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1473 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1474 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1475 // transaction fee with 0 HTLCs (183 sats)).
1476 let mut push_amt = 100_000_000;
1477 push_amt -= feerate_per_kw as u64 * (COMMITMENT_TX_BASE_WEIGHT) / 1000 * 1000;
1478 push_amt -= Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100_000) * 1000;
1479 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt, InitFeatures::known(), InitFeatures::known());
1481 let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1482 + feerate_per_kw as u64 * HTLC_SUCCESS_TX_WEIGHT / 1000 * 1000 - 1;
1483 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1484 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1485 // commitment transaction fee.
1486 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1488 // One more than the dust amt should fail, however.
1489 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt + 1);
1490 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1491 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1495 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1496 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1497 // calculating our counterparty's commitment transaction fee (this was previously broken).
1498 let chanmon_cfgs = create_chanmon_cfgs(2);
1499 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1500 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1501 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1502 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1504 let payment_amt = 46000; // Dust amount
1505 // In the previous code, these first four payments would succeed.
1506 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1507 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1508 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1509 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1511 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1512 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1513 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1514 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1515 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1516 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1518 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1519 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1520 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1521 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1525 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1526 let chanmon_cfgs = create_chanmon_cfgs(3);
1527 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1531 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1534 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1535 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1536 let feerate = get_feerate!(nodes[0], chan.2);
1538 // Add a 2* and +1 for the fee spike reserve.
1539 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1540 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;
1541 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1543 // Add a pending HTLC.
1544 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1545 let payment_event_1 = {
1546 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1547 check_added_monitors!(nodes[0], 1);
1549 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1550 assert_eq!(events.len(), 1);
1551 SendEvent::from_event(events.remove(0))
1553 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1555 // Attempt to trigger a channel reserve violation --> payment failure.
1556 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1557 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;
1558 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1559 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1561 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1562 let secp_ctx = Secp256k1::new();
1563 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1564 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1565 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1566 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height, &None).unwrap();
1567 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1568 let msg = msgs::UpdateAddHTLC {
1571 amount_msat: htlc_msat + 1,
1572 payment_hash: our_payment_hash_1,
1573 cltv_expiry: htlc_cltv,
1574 onion_routing_packet: onion_packet,
1577 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1578 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1579 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1580 assert_eq!(nodes[1].node.list_channels().len(), 1);
1581 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1582 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1583 check_added_monitors!(nodes[1], 1);
1584 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() });
1588 fn test_inbound_outbound_capacity_is_not_zero() {
1589 let chanmon_cfgs = create_chanmon_cfgs(2);
1590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1592 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1593 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1594 let channels0 = node_chanmgrs[0].list_channels();
1595 let channels1 = node_chanmgrs[1].list_channels();
1596 assert_eq!(channels0.len(), 1);
1597 assert_eq!(channels1.len(), 1);
1599 let reserve = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(100000);
1600 assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1601 assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1603 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1604 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1607 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1608 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1612 fn test_channel_reserve_holding_cell_htlcs() {
1613 let chanmon_cfgs = create_chanmon_cfgs(3);
1614 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1615 // When this test was written, the default base fee floated based on the HTLC count.
1616 // It is now fixed, so we simply set the fee to the expected value here.
1617 let mut config = test_default_channel_config();
1618 config.channel_options.forwarding_fee_base_msat = 239;
1619 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1620 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1621 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1622 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1624 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1625 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1627 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1628 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1630 macro_rules! expect_forward {
1632 let mut events = $node.node.get_and_clear_pending_msg_events();
1633 assert_eq!(events.len(), 1);
1634 check_added_monitors!($node, 1);
1635 let payment_event = SendEvent::from_event(events.remove(0));
1640 let feemsat = 239; // set above
1641 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1642 let feerate = get_feerate!(nodes[0], chan_1.2);
1644 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1646 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1648 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1649 route.paths[0].last_mut().unwrap().fee_msat += 1;
1650 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1651 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1652 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)));
1653 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1654 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);
1657 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1658 // nodes[0]'s wealth
1660 let amt_msat = recv_value_0 + total_fee_msat;
1661 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1662 // Also, ensure that each payment has enough to be over the dust limit to
1663 // ensure it'll be included in each commit tx fee calculation.
1664 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1665 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1666 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1669 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1671 let (stat01_, stat11_, stat12_, stat22_) = (
1672 get_channel_value_stat!(nodes[0], chan_1.2),
1673 get_channel_value_stat!(nodes[1], chan_1.2),
1674 get_channel_value_stat!(nodes[1], chan_2.2),
1675 get_channel_value_stat!(nodes[2], chan_2.2),
1678 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1679 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1680 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1681 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1682 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1685 // adding pending output.
1686 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1687 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1688 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1689 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1690 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1691 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1692 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1693 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1694 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1696 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1697 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1698 let amt_msat_1 = recv_value_1 + total_fee_msat;
1700 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);
1701 let payment_event_1 = {
1702 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1703 check_added_monitors!(nodes[0], 1);
1705 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1706 assert_eq!(events.len(), 1);
1707 SendEvent::from_event(events.remove(0))
1709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1711 // channel reserve test with htlc pending output > 0
1712 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1714 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
1715 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1716 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1717 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1720 // split the rest to test holding cell
1721 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1722 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1723 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1724 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1726 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1727 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);
1730 // now see if they go through on both sides
1731 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);
1732 // but this will stuck in the holding cell
1733 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
1734 check_added_monitors!(nodes[0], 0);
1735 let events = nodes[0].node.get_and_clear_pending_events();
1736 assert_eq!(events.len(), 0);
1738 // test with outbound holding cell amount > 0
1740 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
1741 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1742 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1743 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1744 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);
1747 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);
1748 // this will also stuck in the holding cell
1749 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
1750 check_added_monitors!(nodes[0], 0);
1751 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1752 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1754 // flush the pending htlc
1755 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1756 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1757 check_added_monitors!(nodes[1], 1);
1759 // the pending htlc should be promoted to committed
1760 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1761 check_added_monitors!(nodes[0], 1);
1762 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1764 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1765 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1766 // No commitment_signed so get_event_msg's assert(len == 1) passes
1767 check_added_monitors!(nodes[0], 1);
1769 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771 check_added_monitors!(nodes[1], 1);
1773 expect_pending_htlcs_forwardable!(nodes[1]);
1775 let ref payment_event_11 = expect_forward!(nodes[1]);
1776 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1777 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1779 expect_pending_htlcs_forwardable!(nodes[2]);
1780 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
1782 // flush the htlcs in the holding cell
1783 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1785 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1786 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1787 expect_pending_htlcs_forwardable!(nodes[1]);
1789 let ref payment_event_3 = expect_forward!(nodes[1]);
1790 assert_eq!(payment_event_3.msgs.len(), 2);
1791 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1792 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1794 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1795 expect_pending_htlcs_forwardable!(nodes[2]);
1797 let events = nodes[2].node.get_and_clear_pending_events();
1798 assert_eq!(events.len(), 2);
1800 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1801 assert_eq!(our_payment_hash_21, *payment_hash);
1802 assert_eq!(recv_value_21, amt);
1804 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1805 assert!(payment_preimage.is_none());
1806 assert_eq!(our_payment_secret_21, *payment_secret);
1808 _ => panic!("expected PaymentPurpose::InvoicePayment")
1811 _ => panic!("Unexpected event"),
1814 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
1815 assert_eq!(our_payment_hash_22, *payment_hash);
1816 assert_eq!(recv_value_22, amt);
1818 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
1819 assert!(payment_preimage.is_none());
1820 assert_eq!(our_payment_secret_22, *payment_secret);
1822 _ => panic!("expected PaymentPurpose::InvoicePayment")
1825 _ => panic!("Unexpected event"),
1828 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1829 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1830 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1832 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
1833 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
1834 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
1836 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
1837 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);
1838 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1839 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1840 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
1842 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1843 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
1847 fn channel_reserve_in_flight_removes() {
1848 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1849 // can send to its counterparty, but due to update ordering, the other side may not yet have
1850 // considered those HTLCs fully removed.
1851 // This tests that we don't count HTLCs which will not be included in the next remote
1852 // commitment transaction towards the reserve value (as it implies no commitment transaction
1853 // will be generated which violates the remote reserve value).
1854 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1856 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1857 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1858 // you only consider the value of the first HTLC, it may not),
1859 // * start routing a third HTLC from A to B,
1860 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1861 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1862 // * deliver the first fulfill from B
1863 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1865 // * deliver A's response CS and RAA.
1866 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1867 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1868 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1869 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1870 let chanmon_cfgs = create_chanmon_cfgs(2);
1871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1873 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1874 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1876 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1877 // Route the first two HTLCs.
1878 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1879 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1881 // Start routing the third HTLC (this is just used to get everyone in the right state).
1882 let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
1884 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
1885 check_added_monitors!(nodes[0], 1);
1886 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1887 assert_eq!(events.len(), 1);
1888 SendEvent::from_event(events.remove(0))
1891 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1892 // initial fulfill/CS.
1893 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1894 check_added_monitors!(nodes[1], 1);
1895 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1897 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1898 // remove the second HTLC when we send the HTLC back from B to A.
1899 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1900 check_added_monitors!(nodes[1], 1);
1901 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1903 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1904 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1905 check_added_monitors!(nodes[0], 1);
1906 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1907 expect_payment_sent!(nodes[0], payment_preimage_1);
1909 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1910 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1911 check_added_monitors!(nodes[1], 1);
1912 // B is already AwaitingRAA, so cant generate a CS here
1913 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1915 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1916 check_added_monitors!(nodes[1], 1);
1917 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1920 check_added_monitors!(nodes[0], 1);
1921 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1923 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1924 check_added_monitors!(nodes[1], 1);
1925 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1927 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1928 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1929 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1930 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1931 // on-chain as necessary).
1932 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1933 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1934 check_added_monitors!(nodes[0], 1);
1935 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1936 expect_payment_sent!(nodes[0], payment_preimage_2);
1938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1939 check_added_monitors!(nodes[1], 1);
1940 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1942 expect_pending_htlcs_forwardable!(nodes[1]);
1943 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
1945 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1946 // resolve the second HTLC from A's point of view.
1947 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1948 check_added_monitors!(nodes[0], 1);
1949 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1951 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1952 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1953 let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
1955 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
1956 check_added_monitors!(nodes[1], 1);
1957 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1958 assert_eq!(events.len(), 1);
1959 SendEvent::from_event(events.remove(0))
1962 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1963 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1964 check_added_monitors!(nodes[0], 1);
1965 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1967 // Now just resolve all the outstanding messages/HTLCs for completeness...
1969 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1970 check_added_monitors!(nodes[1], 1);
1971 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1973 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1974 check_added_monitors!(nodes[1], 1);
1976 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1977 check_added_monitors!(nodes[0], 1);
1978 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1980 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1981 check_added_monitors!(nodes[1], 1);
1982 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1984 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1985 check_added_monitors!(nodes[0], 1);
1987 expect_pending_htlcs_forwardable!(nodes[0]);
1988 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
1990 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1991 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1995 fn channel_monitor_network_test() {
1996 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1997 // tests that ChannelMonitor is able to recover from various states.
1998 let chanmon_cfgs = create_chanmon_cfgs(5);
1999 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2000 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2001 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2003 // Create some initial channels
2004 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2005 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2006 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2007 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2009 // Make sure all nodes are at the same starting height
2010 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2011 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2012 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2013 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2014 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2016 // Rebalance the network a bit by relaying one payment through all the channels...
2017 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2018 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2019 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2020 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2022 // Simple case with no pending HTLCs:
2023 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2024 check_added_monitors!(nodes[1], 1);
2025 check_closed_broadcast!(nodes[1], false);
2027 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2028 assert_eq!(node_txn.len(), 1);
2029 mine_transaction(&nodes[0], &node_txn[0]);
2030 check_added_monitors!(nodes[0], 1);
2031 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2033 check_closed_broadcast!(nodes[0], true);
2034 assert_eq!(nodes[0].node.list_channels().len(), 0);
2035 assert_eq!(nodes[1].node.list_channels().len(), 1);
2036 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2037 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2039 // One pending HTLC is discarded by the force-close:
2040 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2042 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2043 // broadcasted until we reach the timelock time).
2044 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2045 check_closed_broadcast!(nodes[1], false);
2046 check_added_monitors!(nodes[1], 1);
2048 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2049 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2050 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2051 mine_transaction(&nodes[2], &node_txn[0]);
2052 check_added_monitors!(nodes[2], 1);
2053 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2055 check_closed_broadcast!(nodes[2], true);
2056 assert_eq!(nodes[1].node.list_channels().len(), 0);
2057 assert_eq!(nodes[2].node.list_channels().len(), 1);
2058 check_closed_event!(nodes[1], 1, ClosureReason::DisconnectedPeer);
2059 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2061 macro_rules! claim_funds {
2062 ($node: expr, $prev_node: expr, $preimage: expr) => {
2064 assert!($node.node.claim_funds($preimage));
2065 check_added_monitors!($node, 1);
2067 let events = $node.node.get_and_clear_pending_msg_events();
2068 assert_eq!(events.len(), 1);
2070 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2071 assert!(update_add_htlcs.is_empty());
2072 assert!(update_fail_htlcs.is_empty());
2073 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2075 _ => panic!("Unexpected event"),
2081 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2082 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2083 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2084 check_added_monitors!(nodes[2], 1);
2085 check_closed_broadcast!(nodes[2], false);
2086 let node2_commitment_txid;
2088 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2089 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2090 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2091 node2_commitment_txid = node_txn[0].txid();
2093 // Claim the payment on nodes[3], giving it knowledge of the preimage
2094 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2095 mine_transaction(&nodes[3], &node_txn[0]);
2096 check_added_monitors!(nodes[3], 1);
2097 check_preimage_claim(&nodes[3], &node_txn);
2099 check_closed_broadcast!(nodes[3], true);
2100 assert_eq!(nodes[2].node.list_channels().len(), 0);
2101 assert_eq!(nodes[3].node.list_channels().len(), 1);
2102 check_closed_event!(nodes[2], 1, ClosureReason::DisconnectedPeer);
2103 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2105 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2106 // confusing us in the following tests.
2107 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2109 // One pending HTLC to time out:
2110 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2111 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2114 let (close_chan_update_1, close_chan_update_2) = {
2115 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2116 let events = nodes[3].node.get_and_clear_pending_msg_events();
2117 assert_eq!(events.len(), 2);
2118 let close_chan_update_1 = match events[0] {
2119 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2122 _ => panic!("Unexpected event"),
2125 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2126 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2128 _ => panic!("Unexpected event"),
2130 check_added_monitors!(nodes[3], 1);
2132 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2134 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2135 node_txn.retain(|tx| {
2136 if tx.input[0].previous_output.txid == node2_commitment_txid {
2142 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2144 // Claim the payment on nodes[4], giving it knowledge of the preimage
2145 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2147 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2148 let events = nodes[4].node.get_and_clear_pending_msg_events();
2149 assert_eq!(events.len(), 2);
2150 let close_chan_update_2 = match events[0] {
2151 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2154 _ => panic!("Unexpected event"),
2157 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2158 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2160 _ => panic!("Unexpected event"),
2162 check_added_monitors!(nodes[4], 1);
2163 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2165 mine_transaction(&nodes[4], &node_txn[0]);
2166 check_preimage_claim(&nodes[4], &node_txn);
2167 (close_chan_update_1, close_chan_update_2)
2169 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2170 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2171 assert_eq!(nodes[3].node.list_channels().len(), 0);
2172 assert_eq!(nodes[4].node.list_channels().len(), 0);
2174 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2175 check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed);
2176 check_closed_event!(nodes[4], 1, ClosureReason::CommitmentTxConfirmed);
2180 fn test_justice_tx() {
2181 // Test justice txn built on revoked HTLC-Success tx, against both sides
2182 let mut alice_config = UserConfig::default();
2183 alice_config.channel_options.announced_channel = true;
2184 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2185 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2186 let mut bob_config = UserConfig::default();
2187 bob_config.channel_options.announced_channel = true;
2188 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2189 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2190 let user_cfgs = [Some(alice_config), Some(bob_config)];
2191 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2192 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2193 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2194 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2195 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2196 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2197 // Create some new channels:
2198 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2200 // A pending HTLC which will be revoked:
2201 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2202 // Get the will-be-revoked local txn from nodes[0]
2203 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2204 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2205 assert_eq!(revoked_local_txn[0].input.len(), 1);
2206 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2207 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2208 assert_eq!(revoked_local_txn[1].input.len(), 1);
2209 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2210 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2211 // Revoke the old state
2212 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2215 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2217 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2218 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2219 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2221 check_spends!(node_txn[0], revoked_local_txn[0]);
2222 node_txn.swap_remove(0);
2223 node_txn.truncate(1);
2225 check_added_monitors!(nodes[1], 1);
2226 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2227 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2229 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2230 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2231 // Verify broadcast of revoked HTLC-timeout
2232 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2233 check_added_monitors!(nodes[0], 1);
2234 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2235 // Broadcast revoked HTLC-timeout on node 1
2236 mine_transaction(&nodes[1], &node_txn[1]);
2237 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2239 get_announce_close_broadcast_events(&nodes, 0, 1);
2241 assert_eq!(nodes[0].node.list_channels().len(), 0);
2242 assert_eq!(nodes[1].node.list_channels().len(), 0);
2244 // We test justice_tx build by A on B's revoked HTLC-Success tx
2245 // Create some new channels:
2246 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2248 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2252 // A pending HTLC which will be revoked:
2253 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2254 // Get the will-be-revoked local txn from B
2255 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2256 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2257 assert_eq!(revoked_local_txn[0].input.len(), 1);
2258 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2259 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2260 // Revoke the old state
2261 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2263 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2265 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2266 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2267 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2269 check_spends!(node_txn[0], revoked_local_txn[0]);
2270 node_txn.swap_remove(0);
2272 check_added_monitors!(nodes[0], 1);
2273 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2275 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2276 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2277 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2278 check_added_monitors!(nodes[1], 1);
2279 mine_transaction(&nodes[0], &node_txn[1]);
2280 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2281 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2283 get_announce_close_broadcast_events(&nodes, 0, 1);
2284 assert_eq!(nodes[0].node.list_channels().len(), 0);
2285 assert_eq!(nodes[1].node.list_channels().len(), 0);
2289 fn revoked_output_claim() {
2290 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2291 // transaction is broadcast by its counterparty
2292 let chanmon_cfgs = create_chanmon_cfgs(2);
2293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2295 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2296 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2297 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2298 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2299 assert_eq!(revoked_local_txn.len(), 1);
2300 // Only output is the full channel value back to nodes[0]:
2301 assert_eq!(revoked_local_txn[0].output.len(), 1);
2302 // Send a payment through, updating everyone's latest commitment txn
2303 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2305 // Inform nodes[1] that nodes[0] broadcast a stale tx
2306 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2307 check_added_monitors!(nodes[1], 1);
2308 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2309 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2310 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2312 check_spends!(node_txn[0], revoked_local_txn[0]);
2313 check_spends!(node_txn[1], chan_1.3);
2315 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2316 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2317 get_announce_close_broadcast_events(&nodes, 0, 1);
2318 check_added_monitors!(nodes[0], 1);
2319 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2323 fn claim_htlc_outputs_shared_tx() {
2324 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2325 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2326 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2327 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2328 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2329 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2331 // Create some new channel:
2332 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2334 // Rebalance the network to generate htlc in the two directions
2335 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2336 // 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
2337 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2338 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2340 // Get the will-be-revoked local txn from node[0]
2341 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2342 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2343 assert_eq!(revoked_local_txn[0].input.len(), 1);
2344 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2345 assert_eq!(revoked_local_txn[1].input.len(), 1);
2346 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2347 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2348 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2350 //Revoke the old state
2351 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2354 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2355 check_added_monitors!(nodes[0], 1);
2356 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2357 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2358 check_added_monitors!(nodes[1], 1);
2359 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2360 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2361 expect_payment_failed!(nodes[1], payment_hash_2, true);
2363 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2364 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2366 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2367 check_spends!(node_txn[0], revoked_local_txn[0]);
2369 let mut witness_lens = BTreeSet::new();
2370 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2371 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2372 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2373 assert_eq!(witness_lens.len(), 3);
2374 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2375 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2376 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2378 // Next nodes[1] broadcasts its current local tx state:
2379 assert_eq!(node_txn[1].input.len(), 1);
2380 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2382 get_announce_close_broadcast_events(&nodes, 0, 1);
2383 assert_eq!(nodes[0].node.list_channels().len(), 0);
2384 assert_eq!(nodes[1].node.list_channels().len(), 0);
2388 fn claim_htlc_outputs_single_tx() {
2389 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2390 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2391 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2394 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2396 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2398 // Rebalance the network to generate htlc in the two directions
2399 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2400 // 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
2401 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2402 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2403 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2405 // Get the will-be-revoked local txn from node[0]
2406 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2408 //Revoke the old state
2409 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2412 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2413 check_added_monitors!(nodes[0], 1);
2414 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2415 check_added_monitors!(nodes[1], 1);
2416 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2417 let mut events = nodes[0].node.get_and_clear_pending_events();
2418 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2420 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2421 _ => panic!("Unexpected event"),
2424 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2425 expect_payment_failed!(nodes[1], payment_hash_2, true);
2427 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2428 assert_eq!(node_txn.len(), 9);
2429 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2430 // ChannelManager: local commmitment + local HTLC-timeout (2)
2431 // 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)
2432 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2434 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2435 assert_eq!(node_txn[0].input.len(), 1);
2436 check_spends!(node_txn[0], chan_1.3);
2437 assert_eq!(node_txn[1].input.len(), 1);
2438 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2439 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2440 check_spends!(node_txn[1], node_txn[0]);
2442 // Justice transactions are indices 1-2-4
2443 assert_eq!(node_txn[2].input.len(), 1);
2444 assert_eq!(node_txn[3].input.len(), 1);
2445 assert_eq!(node_txn[4].input.len(), 1);
2447 check_spends!(node_txn[2], revoked_local_txn[0]);
2448 check_spends!(node_txn[3], revoked_local_txn[0]);
2449 check_spends!(node_txn[4], revoked_local_txn[0]);
2451 let mut witness_lens = BTreeSet::new();
2452 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2453 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2454 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2455 assert_eq!(witness_lens.len(), 3);
2456 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2457 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2458 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2460 get_announce_close_broadcast_events(&nodes, 0, 1);
2461 assert_eq!(nodes[0].node.list_channels().len(), 0);
2462 assert_eq!(nodes[1].node.list_channels().len(), 0);
2466 fn test_htlc_on_chain_success() {
2467 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2468 // the preimage backward accordingly. So here we test that ChannelManager is
2469 // broadcasting the right event to other nodes in payment path.
2470 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2471 // A --------------------> B ----------------------> C (preimage)
2472 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2473 // commitment transaction was broadcast.
2474 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2476 // B should be able to claim via preimage if A then broadcasts its local tx.
2477 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2478 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2479 // PaymentSent event).
2481 let chanmon_cfgs = create_chanmon_cfgs(3);
2482 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2483 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2484 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2486 // Create some initial channels
2487 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2488 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2490 // Ensure all nodes are at the same height
2491 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2492 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2493 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2494 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2496 // Rebalance the network a bit by relaying one payment through all the channels...
2497 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2498 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2500 let (our_payment_preimage, payment_hash_1, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2501 let (our_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2503 // Broadcast legit commitment tx from C on B's chain
2504 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2505 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2506 assert_eq!(commitment_tx.len(), 1);
2507 check_spends!(commitment_tx[0], chan_2.3);
2508 nodes[2].node.claim_funds(our_payment_preimage);
2509 nodes[2].node.claim_funds(our_payment_preimage_2);
2510 check_added_monitors!(nodes[2], 2);
2511 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2512 assert!(updates.update_add_htlcs.is_empty());
2513 assert!(updates.update_fail_htlcs.is_empty());
2514 assert!(updates.update_fail_malformed_htlcs.is_empty());
2515 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2517 mine_transaction(&nodes[2], &commitment_tx[0]);
2518 check_closed_broadcast!(nodes[2], true);
2519 check_added_monitors!(nodes[2], 1);
2520 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2521 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)
2522 assert_eq!(node_txn.len(), 5);
2523 assert_eq!(node_txn[0], node_txn[3]);
2524 assert_eq!(node_txn[1], node_txn[4]);
2525 assert_eq!(node_txn[2], commitment_tx[0]);
2526 check_spends!(node_txn[0], commitment_tx[0]);
2527 check_spends!(node_txn[1], commitment_tx[0]);
2528 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2529 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2530 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2531 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532 assert_eq!(node_txn[0].lock_time, 0);
2533 assert_eq!(node_txn[1].lock_time, 0);
2535 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2536 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2537 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2538 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2540 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2541 assert_eq!(added_monitors.len(), 1);
2542 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2543 added_monitors.clear();
2545 let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2546 assert_eq!(forwarded_events.len(), 3);
2547 match forwarded_events[0] {
2548 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2549 _ => panic!("Unexpected event"),
2551 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[1] {
2552 } else { panic!(); }
2553 if let Event::PaymentForwarded { fee_earned_msat: Some(1000), claim_from_onchain_tx: true } = forwarded_events[2] {
2554 } else { panic!(); }
2555 let events = nodes[1].node.get_and_clear_pending_msg_events();
2557 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2558 assert_eq!(added_monitors.len(), 2);
2559 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2560 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2561 added_monitors.clear();
2563 assert_eq!(events.len(), 3);
2565 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2566 _ => panic!("Unexpected event"),
2569 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2570 _ => panic!("Unexpected event"),
2574 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, .. } } => {
2575 assert!(update_add_htlcs.is_empty());
2576 assert!(update_fail_htlcs.is_empty());
2577 assert_eq!(update_fulfill_htlcs.len(), 1);
2578 assert!(update_fail_malformed_htlcs.is_empty());
2579 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2581 _ => panic!("Unexpected event"),
2583 macro_rules! check_tx_local_broadcast {
2584 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2585 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2586 assert_eq!(node_txn.len(), 3);
2587 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2588 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2589 check_spends!(node_txn[1], $commitment_tx);
2590 check_spends!(node_txn[2], $commitment_tx);
2591 assert_ne!(node_txn[1].lock_time, 0);
2592 assert_ne!(node_txn[2].lock_time, 0);
2594 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2595 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2596 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2597 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2599 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2600 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2601 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2602 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2604 check_spends!(node_txn[0], $chan_tx);
2605 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2609 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2610 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2611 // timeout-claim of the output that nodes[2] just claimed via success.
2612 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2614 // Broadcast legit commitment tx from A on B's chain
2615 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2616 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2617 check_spends!(node_a_commitment_tx[0], chan_1.3);
2618 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2619 check_closed_broadcast!(nodes[1], true);
2620 check_added_monitors!(nodes[1], 1);
2621 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2622 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2623 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2624 let commitment_spend =
2625 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2626 check_spends!(node_txn[1], commitment_tx[0]);
2627 check_spends!(node_txn[2], commitment_tx[0]);
2628 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2631 check_spends!(node_txn[0], commitment_tx[0]);
2632 check_spends!(node_txn[1], commitment_tx[0]);
2633 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2637 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2638 assert_eq!(commitment_spend.input.len(), 2);
2639 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2640 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2641 assert_eq!(commitment_spend.lock_time, 0);
2642 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2643 check_spends!(node_txn[3], chan_1.3);
2644 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2645 check_spends!(node_txn[4], node_txn[3]);
2646 check_spends!(node_txn[5], node_txn[3]);
2647 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2648 // we already checked the same situation with A.
2650 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2651 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2652 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2653 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2654 check_closed_broadcast!(nodes[0], true);
2655 check_added_monitors!(nodes[0], 1);
2656 let events = nodes[0].node.get_and_clear_pending_events();
2657 assert_eq!(events.len(), 3);
2658 let mut first_claimed = false;
2659 for event in events {
2661 Event::PaymentSent { payment_preimage, payment_hash } => {
2662 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
2663 assert!(!first_claimed);
2664 first_claimed = true;
2666 assert_eq!(payment_preimage, our_payment_preimage_2);
2667 assert_eq!(payment_hash, payment_hash_2);
2670 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
2671 _ => panic!("Unexpected event"),
2674 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2677 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2678 // Test that in case of a unilateral close onchain, we detect the state of output and
2679 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2680 // broadcasting the right event to other nodes in payment path.
2681 // A ------------------> B ----------------------> C (timeout)
2682 // B's commitment tx C's commitment tx
2684 // B's HTLC timeout tx B's timeout tx
2686 let chanmon_cfgs = create_chanmon_cfgs(3);
2687 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2688 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2689 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2690 *nodes[0].connect_style.borrow_mut() = connect_style;
2691 *nodes[1].connect_style.borrow_mut() = connect_style;
2692 *nodes[2].connect_style.borrow_mut() = connect_style;
2694 // Create some intial channels
2695 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2696 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2698 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2699 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2700 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2702 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2704 // Broadcast legit commitment tx from C on B's chain
2705 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2706 check_spends!(commitment_tx[0], chan_2.3);
2707 nodes[2].node.fail_htlc_backwards(&payment_hash);
2708 check_added_monitors!(nodes[2], 0);
2709 expect_pending_htlcs_forwardable!(nodes[2]);
2710 check_added_monitors!(nodes[2], 1);
2712 let events = nodes[2].node.get_and_clear_pending_msg_events();
2713 assert_eq!(events.len(), 1);
2715 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, .. } } => {
2716 assert!(update_add_htlcs.is_empty());
2717 assert!(!update_fail_htlcs.is_empty());
2718 assert!(update_fulfill_htlcs.is_empty());
2719 assert!(update_fail_malformed_htlcs.is_empty());
2720 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2722 _ => panic!("Unexpected event"),
2724 mine_transaction(&nodes[2], &commitment_tx[0]);
2725 check_closed_broadcast!(nodes[2], true);
2726 check_added_monitors!(nodes[2], 1);
2727 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
2728 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2729 assert_eq!(node_txn.len(), 1);
2730 check_spends!(node_txn[0], chan_2.3);
2731 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2733 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2734 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2735 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2736 mine_transaction(&nodes[1], &commitment_tx[0]);
2737 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2740 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2741 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2742 assert_eq!(node_txn[0], node_txn[3]);
2743 assert_eq!(node_txn[1], node_txn[4]);
2745 check_spends!(node_txn[2], commitment_tx[0]);
2746 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2748 check_spends!(node_txn[0], chan_2.3);
2749 check_spends!(node_txn[1], node_txn[0]);
2750 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2751 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2753 timeout_tx = node_txn[2].clone();
2757 mine_transaction(&nodes[1], &timeout_tx);
2758 check_added_monitors!(nodes[1], 1);
2759 check_closed_broadcast!(nodes[1], true);
2761 // B will rebroadcast a fee-bumped timeout transaction here.
2762 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2763 assert_eq!(node_txn.len(), 1);
2764 check_spends!(node_txn[0], commitment_tx[0]);
2767 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2769 // B may rebroadcast its own holder commitment transaction here, as a safeguard against
2770 // some incredibly unlikely partial-eclipse-attack scenarios. That said, because the
2771 // original commitment_tx[0] (also spending chan_2.3) has reached ANTI_REORG_DELAY B really
2772 // shouldn't broadcast anything here, and in some connect style scenarios we do not.
2773 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2774 if node_txn.len() == 1 {
2775 check_spends!(node_txn[0], chan_2.3);
2777 assert_eq!(node_txn.len(), 0);
2781 expect_pending_htlcs_forwardable!(nodes[1]);
2782 check_added_monitors!(nodes[1], 1);
2783 let events = nodes[1].node.get_and_clear_pending_msg_events();
2784 assert_eq!(events.len(), 1);
2786 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, .. } } => {
2787 assert!(update_add_htlcs.is_empty());
2788 assert!(!update_fail_htlcs.is_empty());
2789 assert!(update_fulfill_htlcs.is_empty());
2790 assert!(update_fail_malformed_htlcs.is_empty());
2791 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2793 _ => panic!("Unexpected event"),
2796 // Broadcast legit commitment tx from B on A's chain
2797 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2798 check_spends!(commitment_tx[0], chan_1.3);
2800 mine_transaction(&nodes[0], &commitment_tx[0]);
2801 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2803 check_closed_broadcast!(nodes[0], true);
2804 check_added_monitors!(nodes[0], 1);
2805 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
2806 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
2807 assert_eq!(node_txn.len(), 2);
2808 check_spends!(node_txn[0], chan_1.3);
2809 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2810 check_spends!(node_txn[1], commitment_tx[0]);
2811 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2815 fn test_htlc_on_chain_timeout() {
2816 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
2817 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
2818 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
2822 fn test_simple_commitment_revoked_fail_backward() {
2823 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2824 // and fail backward accordingly.
2826 let chanmon_cfgs = create_chanmon_cfgs(3);
2827 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2828 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2829 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2831 // Create some initial channels
2832 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2833 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2835 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2836 // Get the will-be-revoked local txn from nodes[2]
2837 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2838 // Revoke the old state
2839 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2841 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2843 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2844 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
2845 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2846 check_added_monitors!(nodes[1], 1);
2847 check_closed_broadcast!(nodes[1], true);
2849 expect_pending_htlcs_forwardable!(nodes[1]);
2850 check_added_monitors!(nodes[1], 1);
2851 let events = nodes[1].node.get_and_clear_pending_msg_events();
2852 assert_eq!(events.len(), 1);
2854 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, .. } } => {
2855 assert!(update_add_htlcs.is_empty());
2856 assert_eq!(update_fail_htlcs.len(), 1);
2857 assert!(update_fulfill_htlcs.is_empty());
2858 assert!(update_fail_malformed_htlcs.is_empty());
2859 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2861 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2862 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2863 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
2865 _ => panic!("Unexpected event"),
2869 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2870 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2871 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2872 // commitment transaction anymore.
2873 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2874 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2875 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2876 // technically disallowed and we should probably handle it reasonably.
2877 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2878 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2880 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2881 // commitment_signed (implying it will be in the latest remote commitment transaction).
2882 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2883 // and once they revoke the previous commitment transaction (allowing us to send a new
2884 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2885 let chanmon_cfgs = create_chanmon_cfgs(3);
2886 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2887 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2888 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2890 // Create some initial channels
2891 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2892 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2894 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 });
2895 // Get the will-be-revoked local txn from nodes[2]
2896 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2897 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2898 // Revoke the old state
2899 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2901 let value = if use_dust {
2902 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2903 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2904 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
2907 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2908 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2909 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2911 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2912 expect_pending_htlcs_forwardable!(nodes[2]);
2913 check_added_monitors!(nodes[2], 1);
2914 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2915 assert!(updates.update_add_htlcs.is_empty());
2916 assert!(updates.update_fulfill_htlcs.is_empty());
2917 assert!(updates.update_fail_malformed_htlcs.is_empty());
2918 assert_eq!(updates.update_fail_htlcs.len(), 1);
2919 assert!(updates.update_fee.is_none());
2920 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2921 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2922 // Drop the last RAA from 3 -> 2
2924 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2925 expect_pending_htlcs_forwardable!(nodes[2]);
2926 check_added_monitors!(nodes[2], 1);
2927 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2928 assert!(updates.update_add_htlcs.is_empty());
2929 assert!(updates.update_fulfill_htlcs.is_empty());
2930 assert!(updates.update_fail_malformed_htlcs.is_empty());
2931 assert_eq!(updates.update_fail_htlcs.len(), 1);
2932 assert!(updates.update_fee.is_none());
2933 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2934 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2935 check_added_monitors!(nodes[1], 1);
2936 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2937 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2938 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2939 check_added_monitors!(nodes[2], 1);
2941 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2942 expect_pending_htlcs_forwardable!(nodes[2]);
2943 check_added_monitors!(nodes[2], 1);
2944 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2945 assert!(updates.update_add_htlcs.is_empty());
2946 assert!(updates.update_fulfill_htlcs.is_empty());
2947 assert!(updates.update_fail_malformed_htlcs.is_empty());
2948 assert_eq!(updates.update_fail_htlcs.len(), 1);
2949 assert!(updates.update_fee.is_none());
2950 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2951 // At this point first_payment_hash has dropped out of the latest two commitment
2952 // transactions that nodes[1] is tracking...
2953 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2954 check_added_monitors!(nodes[1], 1);
2955 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2956 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2957 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2958 check_added_monitors!(nodes[2], 1);
2960 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2961 // on nodes[2]'s RAA.
2962 let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
2963 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
2964 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2965 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2966 check_added_monitors!(nodes[1], 0);
2969 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2970 // One monitor for the new revocation preimage, no second on as we won't generate a new
2971 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2972 check_added_monitors!(nodes[1], 1);
2973 let events = nodes[1].node.get_and_clear_pending_events();
2974 assert_eq!(events.len(), 1);
2976 Event::PendingHTLCsForwardable { .. } => { },
2977 _ => panic!("Unexpected event"),
2979 // Deliberately don't process the pending fail-back so they all fail back at once after
2980 // block connection just like the !deliver_bs_raa case
2983 let mut failed_htlcs = HashSet::new();
2984 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2986 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2987 check_added_monitors!(nodes[1], 1);
2988 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2990 let events = nodes[1].node.get_and_clear_pending_events();
2991 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2993 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => { },
2994 _ => panic!("Unexepected event"),
2997 Event::PaymentPathFailed { ref payment_hash, .. } => {
2998 assert_eq!(*payment_hash, fourth_payment_hash);
3000 _ => panic!("Unexpected event"),
3002 if !deliver_bs_raa {
3004 Event::PendingHTLCsForwardable { .. } => { },
3005 _ => panic!("Unexpected event"),
3008 nodes[1].node.process_pending_htlc_forwards();
3009 check_added_monitors!(nodes[1], 1);
3011 let events = nodes[1].node.get_and_clear_pending_msg_events();
3012 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3013 match events[if deliver_bs_raa { 1 } else { 0 }] {
3014 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3015 _ => panic!("Unexpected event"),
3017 match events[if deliver_bs_raa { 2 } else { 1 }] {
3018 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3019 assert_eq!(channel_id, chan_2.2);
3020 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3022 _ => panic!("Unexpected event"),
3026 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, .. } } => {
3027 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3028 assert_eq!(update_add_htlcs.len(), 1);
3029 assert!(update_fulfill_htlcs.is_empty());
3030 assert!(update_fail_htlcs.is_empty());
3031 assert!(update_fail_malformed_htlcs.is_empty());
3033 _ => panic!("Unexpected event"),
3036 match events[if deliver_bs_raa { 3 } else { 2 }] {
3037 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, .. } } => {
3038 assert!(update_add_htlcs.is_empty());
3039 assert_eq!(update_fail_htlcs.len(), 3);
3040 assert!(update_fulfill_htlcs.is_empty());
3041 assert!(update_fail_malformed_htlcs.is_empty());
3042 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3044 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3045 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3046 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3048 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3050 let events = nodes[0].node.get_and_clear_pending_events();
3051 assert_eq!(events.len(), 3);
3053 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3054 assert!(failed_htlcs.insert(payment_hash.0));
3055 // If we delivered B's RAA we got an unknown preimage error, not something
3056 // that we should update our routing table for.
3057 if !deliver_bs_raa {
3058 assert!(network_update.is_some());
3061 _ => panic!("Unexpected event"),
3064 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3065 assert!(failed_htlcs.insert(payment_hash.0));
3066 assert!(network_update.is_some());
3068 _ => panic!("Unexpected event"),
3071 Event::PaymentPathFailed { ref payment_hash, rejected_by_dest: _, ref network_update, .. } => {
3072 assert!(failed_htlcs.insert(payment_hash.0));
3073 assert!(network_update.is_some());
3075 _ => panic!("Unexpected event"),
3078 _ => panic!("Unexpected event"),
3081 assert!(failed_htlcs.contains(&first_payment_hash.0));
3082 assert!(failed_htlcs.contains(&second_payment_hash.0));
3083 assert!(failed_htlcs.contains(&third_payment_hash.0));
3087 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3088 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3089 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3090 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3091 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3095 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3096 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3097 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3098 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3099 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3103 fn fail_backward_pending_htlc_upon_channel_failure() {
3104 let chanmon_cfgs = create_chanmon_cfgs(2);
3105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3107 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3108 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3110 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3112 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3113 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3114 check_added_monitors!(nodes[0], 1);
3116 let payment_event = {
3117 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3118 assert_eq!(events.len(), 1);
3119 SendEvent::from_event(events.remove(0))
3121 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3122 assert_eq!(payment_event.msgs.len(), 1);
3125 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3126 let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3128 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3129 check_added_monitors!(nodes[0], 0);
3131 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3134 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3136 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3138 let secp_ctx = Secp256k1::new();
3139 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3140 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3141 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height, &None).unwrap();
3142 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3143 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3145 // Send a 0-msat update_add_htlc to fail the channel.
3146 let update_add_htlc = msgs::UpdateAddHTLC {
3152 onion_routing_packet,
3154 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3156 let events = nodes[0].node.get_and_clear_pending_events();
3157 assert_eq!(events.len(), 2);
3158 // Check that Alice fails backward the pending HTLC from the second payment.
3160 Event::PaymentPathFailed { payment_hash, .. } => {
3161 assert_eq!(payment_hash, failed_payment_hash);
3163 _ => panic!("Unexpected event"),
3166 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3167 assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3169 _ => panic!("Unexpected event {:?}", events[1]),
3171 check_closed_broadcast!(nodes[0], true);
3172 check_added_monitors!(nodes[0], 1);
3176 fn test_htlc_ignore_latest_remote_commitment() {
3177 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3178 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3179 let chanmon_cfgs = create_chanmon_cfgs(2);
3180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3182 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3183 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3185 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3186 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3187 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3188 check_closed_broadcast!(nodes[0], true);
3189 check_added_monitors!(nodes[0], 1);
3190 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
3192 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3193 assert_eq!(node_txn.len(), 3);
3194 assert_eq!(node_txn[0], node_txn[1]);
3196 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3197 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3198 check_closed_broadcast!(nodes[1], true);
3199 check_added_monitors!(nodes[1], 1);
3200 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3202 // Duplicate the connect_block call since this may happen due to other listeners
3203 // registering new transactions
3204 header.prev_blockhash = header.block_hash();
3205 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3209 fn test_force_close_fail_back() {
3210 // Check which HTLCs are failed-backwards on channel force-closure
3211 let chanmon_cfgs = create_chanmon_cfgs(3);
3212 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3213 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3214 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3215 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3216 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3218 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3220 let mut payment_event = {
3221 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3222 check_added_monitors!(nodes[0], 1);
3224 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3225 assert_eq!(events.len(), 1);
3226 SendEvent::from_event(events.remove(0))
3229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3230 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3232 expect_pending_htlcs_forwardable!(nodes[1]);
3234 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3235 assert_eq!(events_2.len(), 1);
3236 payment_event = SendEvent::from_event(events_2.remove(0));
3237 assert_eq!(payment_event.msgs.len(), 1);
3239 check_added_monitors!(nodes[1], 1);
3240 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3241 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3242 check_added_monitors!(nodes[2], 1);
3243 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3245 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3246 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3247 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3249 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3250 check_closed_broadcast!(nodes[2], true);
3251 check_added_monitors!(nodes[2], 1);
3252 check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed);
3254 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3255 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3256 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3257 // back to nodes[1] upon timeout otherwise.
3258 assert_eq!(node_txn.len(), 1);
3262 mine_transaction(&nodes[1], &tx);
3264 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3265 check_closed_broadcast!(nodes[1], true);
3266 check_added_monitors!(nodes[1], 1);
3267 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
3269 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3271 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3272 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3273 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &node_cfgs[2].logger);
3275 mine_transaction(&nodes[2], &tx);
3276 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3277 assert_eq!(node_txn.len(), 1);
3278 assert_eq!(node_txn[0].input.len(), 1);
3279 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3280 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3281 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3283 check_spends!(node_txn[0], tx);
3287 fn test_dup_events_on_peer_disconnect() {
3288 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3289 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3290 // as we used to generate the event immediately upon receipt of the payment preimage in the
3291 // update_fulfill_htlc message.
3293 let chanmon_cfgs = create_chanmon_cfgs(2);
3294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3296 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3297 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3299 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3301 assert!(nodes[1].node.claim_funds(payment_preimage));
3302 check_added_monitors!(nodes[1], 1);
3303 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3304 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3305 expect_payment_sent!(nodes[0], payment_preimage);
3307 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3308 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3310 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3311 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3315 fn test_simple_peer_disconnect() {
3316 // Test that we can reconnect when there are no lost messages
3317 let chanmon_cfgs = create_chanmon_cfgs(3);
3318 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3319 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3320 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3321 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3322 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3324 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3325 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3326 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3328 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3329 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3330 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3331 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3333 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3334 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3335 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3337 let (payment_preimage_3, payment_hash_3, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3338 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3339 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3340 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3342 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3343 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3345 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3346 fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3348 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3350 let events = nodes[0].node.get_and_clear_pending_events();
3351 assert_eq!(events.len(), 2);
3353 Event::PaymentSent { payment_preimage, payment_hash } => {
3354 assert_eq!(payment_preimage, payment_preimage_3);
3355 assert_eq!(payment_hash, payment_hash_3);
3357 _ => panic!("Unexpected event"),
3360 Event::PaymentPathFailed { payment_hash, rejected_by_dest, .. } => {
3361 assert_eq!(payment_hash, payment_hash_5);
3362 assert!(rejected_by_dest);
3364 _ => panic!("Unexpected event"),
3368 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3369 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3372 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3373 // Test that we can reconnect when in-flight HTLC updates get dropped
3374 let chanmon_cfgs = create_chanmon_cfgs(2);
3375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3377 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3379 let mut as_funding_locked = None;
3380 if messages_delivered == 0 {
3381 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3382 as_funding_locked = Some(funding_locked);
3383 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3384 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3385 // it before the channel_reestablish message.
3387 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3390 let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3392 let payment_event = {
3393 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3394 check_added_monitors!(nodes[0], 1);
3396 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3397 assert_eq!(events.len(), 1);
3398 SendEvent::from_event(events.remove(0))
3400 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3402 if messages_delivered < 2 {
3403 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3405 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3406 if messages_delivered >= 3 {
3407 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3408 check_added_monitors!(nodes[1], 1);
3409 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3411 if messages_delivered >= 4 {
3412 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3413 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3414 check_added_monitors!(nodes[0], 1);
3416 if messages_delivered >= 5 {
3417 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3418 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3419 // No commitment_signed so get_event_msg's assert(len == 1) passes
3420 check_added_monitors!(nodes[0], 1);
3422 if messages_delivered >= 6 {
3423 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3424 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3425 check_added_monitors!(nodes[1], 1);
3432 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3433 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3434 if messages_delivered < 3 {
3435 if simulate_broken_lnd {
3436 // lnd has a long-standing bug where they send a funding_locked prior to a
3437 // channel_reestablish if you reconnect prior to funding_locked time.
3439 // Here we simulate that behavior, delivering a funding_locked immediately on
3440 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3441 // in `reconnect_nodes` but we currently don't fail based on that.
3443 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3444 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3446 // Even if the funding_locked messages get exchanged, as long as nothing further was
3447 // received on either side, both sides will need to resend them.
3448 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3449 } else if messages_delivered == 3 {
3450 // nodes[0] still wants its RAA + commitment_signed
3451 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3452 } else if messages_delivered == 4 {
3453 // nodes[0] still wants its commitment_signed
3454 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3455 } else if messages_delivered == 5 {
3456 // nodes[1] still wants its final RAA
3457 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3458 } else if messages_delivered == 6 {
3459 // Everything was delivered...
3460 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3463 let events_1 = nodes[1].node.get_and_clear_pending_events();
3464 assert_eq!(events_1.len(), 1);
3466 Event::PendingHTLCsForwardable { .. } => { },
3467 _ => panic!("Unexpected event"),
3470 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3471 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3472 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3474 nodes[1].node.process_pending_htlc_forwards();
3476 let events_2 = nodes[1].node.get_and_clear_pending_events();
3477 assert_eq!(events_2.len(), 1);
3479 Event::PaymentReceived { ref payment_hash, ref purpose, amt } => {
3480 assert_eq!(payment_hash_1, *payment_hash);
3481 assert_eq!(amt, 1000000);
3483 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3484 assert!(payment_preimage.is_none());
3485 assert_eq!(payment_secret_1, *payment_secret);
3487 _ => panic!("expected PaymentPurpose::InvoicePayment")
3490 _ => panic!("Unexpected event"),
3493 nodes[1].node.claim_funds(payment_preimage_1);
3494 check_added_monitors!(nodes[1], 1);
3496 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3497 assert_eq!(events_3.len(), 1);
3498 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3499 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3500 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3501 assert!(updates.update_add_htlcs.is_empty());
3502 assert!(updates.update_fail_htlcs.is_empty());
3503 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3504 assert!(updates.update_fail_malformed_htlcs.is_empty());
3505 assert!(updates.update_fee.is_none());
3506 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3508 _ => panic!("Unexpected event"),
3511 if messages_delivered >= 1 {
3512 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3514 let events_4 = nodes[0].node.get_and_clear_pending_events();
3515 assert_eq!(events_4.len(), 1);
3517 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3518 assert_eq!(payment_preimage_1, *payment_preimage);
3519 assert_eq!(payment_hash_1, *payment_hash);
3521 _ => panic!("Unexpected event"),
3524 if messages_delivered >= 2 {
3525 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3526 check_added_monitors!(nodes[0], 1);
3527 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3529 if messages_delivered >= 3 {
3530 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3531 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3532 check_added_monitors!(nodes[1], 1);
3534 if messages_delivered >= 4 {
3535 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3536 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3537 // No commitment_signed so get_event_msg's assert(len == 1) passes
3538 check_added_monitors!(nodes[1], 1);
3540 if messages_delivered >= 5 {
3541 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3542 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3543 check_added_monitors!(nodes[0], 1);
3550 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3551 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3552 if messages_delivered < 2 {
3553 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3554 if messages_delivered < 1 {
3555 let events_4 = nodes[0].node.get_and_clear_pending_events();
3556 assert_eq!(events_4.len(), 1);
3558 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3559 assert_eq!(payment_preimage_1, *payment_preimage);
3560 assert_eq!(payment_hash_1, *payment_hash);
3562 _ => panic!("Unexpected event"),
3565 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3567 } else if messages_delivered == 2 {
3568 // nodes[0] still wants its RAA + commitment_signed
3569 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3570 } else if messages_delivered == 3 {
3571 // nodes[0] still wants its commitment_signed
3572 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3573 } else if messages_delivered == 4 {
3574 // nodes[1] still wants its final RAA
3575 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3576 } else if messages_delivered == 5 {
3577 // Everything was delivered...
3578 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3585 // Channel should still work fine...
3586 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3587 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3588 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3592 fn test_drop_messages_peer_disconnect_a() {
3593 do_test_drop_messages_peer_disconnect(0, true);
3594 do_test_drop_messages_peer_disconnect(0, false);
3595 do_test_drop_messages_peer_disconnect(1, false);
3596 do_test_drop_messages_peer_disconnect(2, false);
3600 fn test_drop_messages_peer_disconnect_b() {
3601 do_test_drop_messages_peer_disconnect(3, false);
3602 do_test_drop_messages_peer_disconnect(4, false);
3603 do_test_drop_messages_peer_disconnect(5, false);
3604 do_test_drop_messages_peer_disconnect(6, false);
3608 fn test_funding_peer_disconnect() {
3609 // Test that we can lock in our funding tx while disconnected
3610 let chanmon_cfgs = create_chanmon_cfgs(2);
3611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3613 let persister: test_utils::TestPersister;
3614 let new_chain_monitor: test_utils::TestChainMonitor;
3615 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3616 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3617 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3619 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3620 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3622 confirm_transaction(&nodes[0], &tx);
3623 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3624 assert_eq!(events_1.len(), 1);
3626 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3627 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3629 _ => panic!("Unexpected event"),
3632 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3634 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3635 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3637 confirm_transaction(&nodes[1], &tx);
3638 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3639 assert_eq!(events_2.len(), 2);
3640 let funding_locked = match events_2[0] {
3641 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3642 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3645 _ => panic!("Unexpected event"),
3647 let bs_announcement_sigs = match events_2[1] {
3648 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3649 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3652 _ => panic!("Unexpected event"),
3655 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3657 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3658 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3659 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3660 assert_eq!(events_3.len(), 2);
3661 let as_announcement_sigs = match events_3[0] {
3662 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3663 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3666 _ => panic!("Unexpected event"),
3668 let (as_announcement, as_update) = match events_3[1] {
3669 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3670 (msg.clone(), update_msg.clone())
3672 _ => panic!("Unexpected event"),
3675 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3676 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3677 assert_eq!(events_4.len(), 1);
3678 let (_, bs_update) = match events_4[0] {
3679 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3680 (msg.clone(), update_msg.clone())
3682 _ => panic!("Unexpected event"),
3685 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3686 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3687 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3689 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3690 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3691 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3693 // Check that after deserialization and reconnection we can still generate an identical
3694 // channel_announcement from the cached signatures.
3695 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3697 let nodes_0_serialized = nodes[0].node.encode();
3698 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3699 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3701 persister = test_utils::TestPersister::new();
3702 let keys_manager = &chanmon_cfgs[0].keys_manager;
3703 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);
3704 nodes[0].chain_monitor = &new_chain_monitor;
3705 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3706 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3707 &mut chan_0_monitor_read, keys_manager).unwrap();
3708 assert!(chan_0_monitor_read.is_empty());
3710 let mut nodes_0_read = &nodes_0_serialized[..];
3711 let (_, nodes_0_deserialized_tmp) = {
3712 let mut channel_monitors = HashMap::new();
3713 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3714 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3715 default_config: UserConfig::default(),
3717 fee_estimator: node_cfgs[0].fee_estimator,
3718 chain_monitor: nodes[0].chain_monitor,
3719 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3720 logger: nodes[0].logger,
3724 nodes_0_deserialized = nodes_0_deserialized_tmp;
3725 assert!(nodes_0_read.is_empty());
3727 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3728 nodes[0].node = &nodes_0_deserialized;
3729 check_added_monitors!(nodes[0], 1);
3731 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3733 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3734 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3735 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3736 let mut found_announcement = false;
3737 for event in msgs.iter() {
3739 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3740 if *msg == as_announcement { found_announcement = true; }
3742 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3743 _ => panic!("Unexpected event"),
3746 assert!(found_announcement);
3750 fn test_drop_messages_peer_disconnect_dual_htlc() {
3751 // Test that we can handle reconnecting when both sides of a channel have pending
3752 // commitment_updates when we disconnect.
3753 let chanmon_cfgs = create_chanmon_cfgs(2);
3754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3756 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3757 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3759 let (payment_preimage_1, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3761 // Now try to send a second payment which will fail to send
3762 let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
3763 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
3764 check_added_monitors!(nodes[0], 1);
3766 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3767 assert_eq!(events_1.len(), 1);
3769 MessageSendEvent::UpdateHTLCs { .. } => {},
3770 _ => panic!("Unexpected event"),
3773 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3774 check_added_monitors!(nodes[1], 1);
3776 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3777 assert_eq!(events_2.len(), 1);
3779 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 } } => {
3780 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3781 assert!(update_add_htlcs.is_empty());
3782 assert_eq!(update_fulfill_htlcs.len(), 1);
3783 assert!(update_fail_htlcs.is_empty());
3784 assert!(update_fail_malformed_htlcs.is_empty());
3785 assert!(update_fee.is_none());
3787 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3788 let events_3 = nodes[0].node.get_and_clear_pending_events();
3789 assert_eq!(events_3.len(), 1);
3791 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
3792 assert_eq!(*payment_preimage, payment_preimage_1);
3793 assert_eq!(*payment_hash, payment_hash_1);
3795 _ => panic!("Unexpected event"),
3798 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3799 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3800 // No commitment_signed so get_event_msg's assert(len == 1) passes
3801 check_added_monitors!(nodes[0], 1);
3803 _ => panic!("Unexpected event"),
3806 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3807 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3809 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3810 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3811 assert_eq!(reestablish_1.len(), 1);
3812 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3813 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3814 assert_eq!(reestablish_2.len(), 1);
3816 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3817 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3818 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3819 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3821 assert!(as_resp.0.is_none());
3822 assert!(bs_resp.0.is_none());
3824 assert!(bs_resp.1.is_none());
3825 assert!(bs_resp.2.is_none());
3827 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3829 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3830 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3831 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3832 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3833 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3834 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3835 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3836 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3837 // No commitment_signed so get_event_msg's assert(len == 1) passes
3838 check_added_monitors!(nodes[1], 1);
3840 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3841 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3842 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3843 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3844 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3845 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3846 assert!(bs_second_commitment_signed.update_fee.is_none());
3847 check_added_monitors!(nodes[1], 1);
3849 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3850 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3851 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3852 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3853 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3854 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3855 assert!(as_commitment_signed.update_fee.is_none());
3856 check_added_monitors!(nodes[0], 1);
3858 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3859 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3860 // No commitment_signed so get_event_msg's assert(len == 1) passes
3861 check_added_monitors!(nodes[0], 1);
3863 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3864 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3865 // No commitment_signed so get_event_msg's assert(len == 1) passes
3866 check_added_monitors!(nodes[1], 1);
3868 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3869 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3870 check_added_monitors!(nodes[1], 1);
3872 expect_pending_htlcs_forwardable!(nodes[1]);
3874 let events_5 = nodes[1].node.get_and_clear_pending_events();
3875 assert_eq!(events_5.len(), 1);
3877 Event::PaymentReceived { ref payment_hash, ref purpose, .. } => {
3878 assert_eq!(payment_hash_2, *payment_hash);
3880 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3881 assert!(payment_preimage.is_none());
3882 assert_eq!(payment_secret_2, *payment_secret);
3884 _ => panic!("expected PaymentPurpose::InvoicePayment")
3887 _ => panic!("Unexpected event"),
3890 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3891 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3892 check_added_monitors!(nodes[0], 1);
3894 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3897 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3898 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3899 // to avoid our counterparty failing the channel.
3900 let chanmon_cfgs = create_chanmon_cfgs(2);
3901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3903 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3905 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3907 let our_payment_hash = if send_partial_mpp {
3908 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
3909 // Use the utility function send_payment_along_path to send the payment with MPP data which
3910 // indicates there are more HTLCs coming.
3911 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.
3912 let payment_id = PaymentId([42; 32]);
3913 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height, payment_id, &None).unwrap();
3914 check_added_monitors!(nodes[0], 1);
3915 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3916 assert_eq!(events.len(), 1);
3917 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3918 // hop should *not* yet generate any PaymentReceived event(s).
3919 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
3922 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3925 let mut block = Block {
3926 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3929 connect_block(&nodes[0], &block);
3930 connect_block(&nodes[1], &block);
3931 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
3932 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
3933 block.header.prev_blockhash = block.block_hash();
3934 connect_block(&nodes[0], &block);
3935 connect_block(&nodes[1], &block);
3938 expect_pending_htlcs_forwardable!(nodes[1]);
3940 check_added_monitors!(nodes[1], 1);
3941 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3942 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3943 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3944 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3945 assert!(htlc_timeout_updates.update_fee.is_none());
3947 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3948 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3949 // 100_000 msat as u64, followed by the height at which we failed back above
3950 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3951 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
3952 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3956 fn test_htlc_timeout() {
3957 do_test_htlc_timeout(true);
3958 do_test_htlc_timeout(false);
3961 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3962 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3963 let chanmon_cfgs = create_chanmon_cfgs(3);
3964 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3965 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3966 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3967 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3968 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3970 // Make sure all nodes are at the same starting height
3971 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
3972 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
3973 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
3975 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3976 let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
3978 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
3980 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3981 check_added_monitors!(nodes[1], 1);
3983 // Now attempt to route a second payment, which should be placed in the holding cell
3984 let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
3985 let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
3986 sending_node.node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
3988 check_added_monitors!(nodes[0], 1);
3989 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3990 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3991 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3992 expect_pending_htlcs_forwardable!(nodes[1]);
3994 check_added_monitors!(nodes[1], 0);
3996 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
3997 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3998 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3999 connect_blocks(&nodes[1], 1);
4002 expect_pending_htlcs_forwardable!(nodes[1]);
4003 check_added_monitors!(nodes[1], 1);
4004 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4005 assert_eq!(fail_commit.len(), 1);
4006 match fail_commit[0] {
4007 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4008 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4009 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4011 _ => unreachable!(),
4013 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4015 expect_payment_failed!(nodes[1], second_payment_hash, true);
4020 fn test_holding_cell_htlc_add_timeouts() {
4021 do_test_holding_cell_htlc_add_timeouts(false);
4022 do_test_holding_cell_htlc_add_timeouts(true);
4026 fn test_no_txn_manager_serialize_deserialize() {
4027 let chanmon_cfgs = create_chanmon_cfgs(2);
4028 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4029 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4030 let logger: test_utils::TestLogger;
4031 let fee_estimator: test_utils::TestFeeEstimator;
4032 let persister: test_utils::TestPersister;
4033 let new_chain_monitor: test_utils::TestChainMonitor;
4034 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4035 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4037 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4039 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4041 let nodes_0_serialized = nodes[0].node.encode();
4042 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4043 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4045 logger = test_utils::TestLogger::new();
4046 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4047 persister = test_utils::TestPersister::new();
4048 let keys_manager = &chanmon_cfgs[0].keys_manager;
4049 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4050 nodes[0].chain_monitor = &new_chain_monitor;
4051 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4052 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4053 &mut chan_0_monitor_read, keys_manager).unwrap();
4054 assert!(chan_0_monitor_read.is_empty());
4056 let mut nodes_0_read = &nodes_0_serialized[..];
4057 let config = UserConfig::default();
4058 let (_, nodes_0_deserialized_tmp) = {
4059 let mut channel_monitors = HashMap::new();
4060 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4061 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4062 default_config: config,
4064 fee_estimator: &fee_estimator,
4065 chain_monitor: nodes[0].chain_monitor,
4066 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4071 nodes_0_deserialized = nodes_0_deserialized_tmp;
4072 assert!(nodes_0_read.is_empty());
4074 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4075 nodes[0].node = &nodes_0_deserialized;
4076 assert_eq!(nodes[0].node.list_channels().len(), 1);
4077 check_added_monitors!(nodes[0], 1);
4079 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4080 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4081 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4082 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4084 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4085 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4086 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4087 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4089 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4090 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4091 for node in nodes.iter() {
4092 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4093 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4094 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4097 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4101 fn test_dup_htlc_onchain_fails_on_reload() {
4102 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4103 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4104 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4105 // the ChannelMonitor tells it to.
4107 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4108 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4109 // PaymentPathFailed event appearing). However, because we may not serialize the relevant
4110 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4111 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4112 // and de-duplicates ChannelMonitor events.
4114 // This tests that explicit tracking behavior.
4115 let chanmon_cfgs = create_chanmon_cfgs(2);
4116 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4117 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4118 let persister: test_utils::TestPersister;
4119 let new_chain_monitor: test_utils::TestChainMonitor;
4120 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4121 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4123 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4125 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4127 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4128 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4129 check_closed_broadcast!(nodes[0], true);
4130 check_added_monitors!(nodes[0], 1);
4131 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4133 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4134 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4136 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4137 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4138 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4139 assert_eq!(node_txn.len(), 3);
4140 assert_eq!(node_txn[0], node_txn[1]);
4142 assert!(nodes[1].node.claim_funds(payment_preimage));
4143 check_added_monitors!(nodes[1], 1);
4145 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4146 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4147 check_closed_broadcast!(nodes[1], true);
4148 check_added_monitors!(nodes[1], 1);
4149 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4150 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4152 header.prev_blockhash = nodes[0].best_block_hash();
4153 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4155 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4156 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4157 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4158 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4159 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4161 header.prev_blockhash = nodes[0].best_block_hash();
4162 let claim_block = Block { header, txdata: claim_txn};
4163 connect_block(&nodes[0], &claim_block);
4164 expect_payment_sent!(nodes[0], payment_preimage);
4166 // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4167 // connected a highly-relevant block, it likely gets serialized out now.
4168 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4169 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4171 // Now reload nodes[0]...
4172 persister = test_utils::TestPersister::new();
4173 let keys_manager = &chanmon_cfgs[0].keys_manager;
4174 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);
4175 nodes[0].chain_monitor = &new_chain_monitor;
4176 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4177 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4178 &mut chan_0_monitor_read, keys_manager).unwrap();
4179 assert!(chan_0_monitor_read.is_empty());
4181 let (_, nodes_0_deserialized_tmp) = {
4182 let mut channel_monitors = HashMap::new();
4183 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4184 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4185 ::read(&mut io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4186 default_config: Default::default(),
4188 fee_estimator: node_cfgs[0].fee_estimator,
4189 chain_monitor: nodes[0].chain_monitor,
4190 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4191 logger: nodes[0].logger,
4195 nodes_0_deserialized = nodes_0_deserialized_tmp;
4197 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4198 check_added_monitors!(nodes[0], 1);
4199 nodes[0].node = &nodes_0_deserialized;
4201 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4202 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4203 // payment events should kick in, leaving us with no pending events here.
4204 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4205 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4206 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4210 fn test_manager_serialize_deserialize_events() {
4211 // This test makes sure the events field in ChannelManager survives de/serialization
4212 let chanmon_cfgs = create_chanmon_cfgs(2);
4213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4215 let fee_estimator: test_utils::TestFeeEstimator;
4216 let persister: test_utils::TestPersister;
4217 let logger: test_utils::TestLogger;
4218 let new_chain_monitor: test_utils::TestChainMonitor;
4219 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4220 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4222 // Start creating a channel, but stop right before broadcasting the funding transaction
4223 let channel_value = 100000;
4224 let push_msat = 10001;
4225 let a_flags = InitFeatures::known();
4226 let b_flags = InitFeatures::known();
4227 let node_a = nodes.remove(0);
4228 let node_b = nodes.remove(0);
4229 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4230 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()));
4231 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()));
4233 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4235 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4236 check_added_monitors!(node_a, 0);
4238 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()));
4240 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4241 assert_eq!(added_monitors.len(), 1);
4242 assert_eq!(added_monitors[0].0, funding_output);
4243 added_monitors.clear();
4246 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
4248 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4249 assert_eq!(added_monitors.len(), 1);
4250 assert_eq!(added_monitors[0].0, funding_output);
4251 added_monitors.clear();
4253 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4258 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4259 let nodes_0_serialized = nodes[0].node.encode();
4260 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4261 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4263 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4264 logger = test_utils::TestLogger::new();
4265 persister = test_utils::TestPersister::new();
4266 let keys_manager = &chanmon_cfgs[0].keys_manager;
4267 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4268 nodes[0].chain_monitor = &new_chain_monitor;
4269 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4270 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4271 &mut chan_0_monitor_read, keys_manager).unwrap();
4272 assert!(chan_0_monitor_read.is_empty());
4274 let mut nodes_0_read = &nodes_0_serialized[..];
4275 let config = UserConfig::default();
4276 let (_, nodes_0_deserialized_tmp) = {
4277 let mut channel_monitors = HashMap::new();
4278 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4279 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4280 default_config: config,
4282 fee_estimator: &fee_estimator,
4283 chain_monitor: nodes[0].chain_monitor,
4284 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4289 nodes_0_deserialized = nodes_0_deserialized_tmp;
4290 assert!(nodes_0_read.is_empty());
4292 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4294 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4295 nodes[0].node = &nodes_0_deserialized;
4297 // After deserializing, make sure the funding_transaction is still held by the channel manager
4298 let events_4 = nodes[0].node.get_and_clear_pending_events();
4299 assert_eq!(events_4.len(), 0);
4300 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4301 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4303 // Make sure the channel is functioning as though the de/serialization never happened
4304 assert_eq!(nodes[0].node.list_channels().len(), 1);
4305 check_added_monitors!(nodes[0], 1);
4307 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4308 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4309 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4310 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4312 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4313 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4314 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4315 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4317 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4318 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4319 for node in nodes.iter() {
4320 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4321 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4322 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4325 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4329 fn test_simple_manager_serialize_deserialize() {
4330 let chanmon_cfgs = create_chanmon_cfgs(2);
4331 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4332 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4333 let logger: test_utils::TestLogger;
4334 let fee_estimator: test_utils::TestFeeEstimator;
4335 let persister: test_utils::TestPersister;
4336 let new_chain_monitor: test_utils::TestChainMonitor;
4337 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4339 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4341 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4342 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4344 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4346 let nodes_0_serialized = nodes[0].node.encode();
4347 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4348 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4350 logger = test_utils::TestLogger::new();
4351 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4352 persister = test_utils::TestPersister::new();
4353 let keys_manager = &chanmon_cfgs[0].keys_manager;
4354 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4355 nodes[0].chain_monitor = &new_chain_monitor;
4356 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4357 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4358 &mut chan_0_monitor_read, keys_manager).unwrap();
4359 assert!(chan_0_monitor_read.is_empty());
4361 let mut nodes_0_read = &nodes_0_serialized[..];
4362 let (_, nodes_0_deserialized_tmp) = {
4363 let mut channel_monitors = HashMap::new();
4364 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4365 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4366 default_config: UserConfig::default(),
4368 fee_estimator: &fee_estimator,
4369 chain_monitor: nodes[0].chain_monitor,
4370 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4375 nodes_0_deserialized = nodes_0_deserialized_tmp;
4376 assert!(nodes_0_read.is_empty());
4378 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4379 nodes[0].node = &nodes_0_deserialized;
4380 check_added_monitors!(nodes[0], 1);
4382 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4384 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4385 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4389 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4390 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4391 let chanmon_cfgs = create_chanmon_cfgs(4);
4392 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4393 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4394 let logger: test_utils::TestLogger;
4395 let fee_estimator: test_utils::TestFeeEstimator;
4396 let persister: test_utils::TestPersister;
4397 let new_chain_monitor: test_utils::TestChainMonitor;
4398 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4399 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4400 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4401 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4402 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4404 let mut node_0_stale_monitors_serialized = Vec::new();
4405 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4406 let mut writer = test_utils::TestVecWriter(Vec::new());
4407 monitor.1.write(&mut writer).unwrap();
4408 node_0_stale_monitors_serialized.push(writer.0);
4411 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4413 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4414 let nodes_0_serialized = nodes[0].node.encode();
4416 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4417 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4418 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4419 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4421 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4423 let mut node_0_monitors_serialized = Vec::new();
4424 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4425 let mut writer = test_utils::TestVecWriter(Vec::new());
4426 monitor.1.write(&mut writer).unwrap();
4427 node_0_monitors_serialized.push(writer.0);
4430 logger = test_utils::TestLogger::new();
4431 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
4432 persister = test_utils::TestPersister::new();
4433 let keys_manager = &chanmon_cfgs[0].keys_manager;
4434 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4435 nodes[0].chain_monitor = &new_chain_monitor;
4438 let mut node_0_stale_monitors = Vec::new();
4439 for serialized in node_0_stale_monitors_serialized.iter() {
4440 let mut read = &serialized[..];
4441 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4442 assert!(read.is_empty());
4443 node_0_stale_monitors.push(monitor);
4446 let mut node_0_monitors = Vec::new();
4447 for serialized in node_0_monitors_serialized.iter() {
4448 let mut read = &serialized[..];
4449 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4450 assert!(read.is_empty());
4451 node_0_monitors.push(monitor);
4454 let mut nodes_0_read = &nodes_0_serialized[..];
4455 if let Err(msgs::DecodeError::InvalidValue) =
4456 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4457 default_config: UserConfig::default(),
4459 fee_estimator: &fee_estimator,
4460 chain_monitor: nodes[0].chain_monitor,
4461 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4463 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4465 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4468 let mut nodes_0_read = &nodes_0_serialized[..];
4469 let (_, nodes_0_deserialized_tmp) =
4470 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4471 default_config: UserConfig::default(),
4473 fee_estimator: &fee_estimator,
4474 chain_monitor: nodes[0].chain_monitor,
4475 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4477 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4479 nodes_0_deserialized = nodes_0_deserialized_tmp;
4480 assert!(nodes_0_read.is_empty());
4482 { // Channel close should result in a commitment tx
4483 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4484 assert_eq!(txn.len(), 1);
4485 check_spends!(txn[0], funding_tx);
4486 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4489 for monitor in node_0_monitors.drain(..) {
4490 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4491 check_added_monitors!(nodes[0], 1);
4493 nodes[0].node = &nodes_0_deserialized;
4494 check_closed_event!(nodes[0], 1, ClosureReason::OutdatedChannelManager);
4496 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4497 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4498 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4499 //... and we can even still claim the payment!
4500 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4502 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4503 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4504 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4505 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4506 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4507 assert_eq!(msg_events.len(), 1);
4508 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4510 &ErrorAction::SendErrorMessage { ref msg } => {
4511 assert_eq!(msg.channel_id, channel_id);
4513 _ => panic!("Unexpected event!"),
4518 macro_rules! check_spendable_outputs {
4519 ($node: expr, $keysinterface: expr) => {
4521 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4522 let mut txn = Vec::new();
4523 let mut all_outputs = Vec::new();
4524 let secp_ctx = Secp256k1::new();
4525 for event in events.drain(..) {
4527 Event::SpendableOutputs { mut outputs } => {
4528 for outp in outputs.drain(..) {
4529 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4530 all_outputs.push(outp);
4533 _ => panic!("Unexpected event"),
4536 if all_outputs.len() > 1 {
4537 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) {
4547 fn test_claim_sizeable_push_msat() {
4548 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4549 let chanmon_cfgs = create_chanmon_cfgs(2);
4550 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4551 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4552 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4554 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4555 nodes[1].node.force_close_channel(&chan.2).unwrap();
4556 check_closed_broadcast!(nodes[1], true);
4557 check_added_monitors!(nodes[1], 1);
4558 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
4559 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4560 assert_eq!(node_txn.len(), 1);
4561 check_spends!(node_txn[0], chan.3);
4562 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
4564 mine_transaction(&nodes[1], &node_txn[0]);
4565 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4567 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4568 assert_eq!(spend_txn.len(), 1);
4569 assert_eq!(spend_txn[0].input.len(), 1);
4570 check_spends!(spend_txn[0], node_txn[0]);
4571 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4575 fn test_claim_on_remote_sizeable_push_msat() {
4576 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4577 // to_remote output is encumbered by a P2WPKH
4578 let chanmon_cfgs = create_chanmon_cfgs(2);
4579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4583 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4584 nodes[0].node.force_close_channel(&chan.2).unwrap();
4585 check_closed_broadcast!(nodes[0], true);
4586 check_added_monitors!(nodes[0], 1);
4587 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed);
4589 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4590 assert_eq!(node_txn.len(), 1);
4591 check_spends!(node_txn[0], chan.3);
4592 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
4594 mine_transaction(&nodes[1], &node_txn[0]);
4595 check_closed_broadcast!(nodes[1], true);
4596 check_added_monitors!(nodes[1], 1);
4597 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4598 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4600 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4601 assert_eq!(spend_txn.len(), 1);
4602 check_spends!(spend_txn[0], node_txn[0]);
4606 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4607 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4608 // to_remote output is encumbered by a P2WPKH
4610 let chanmon_cfgs = create_chanmon_cfgs(2);
4611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4613 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4615 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4616 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4617 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4618 assert_eq!(revoked_local_txn[0].input.len(), 1);
4619 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4621 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4622 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4623 check_closed_broadcast!(nodes[1], true);
4624 check_added_monitors!(nodes[1], 1);
4625 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4627 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4628 mine_transaction(&nodes[1], &node_txn[0]);
4629 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4631 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4632 assert_eq!(spend_txn.len(), 3);
4633 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4634 check_spends!(spend_txn[1], node_txn[0]);
4635 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4639 fn test_static_spendable_outputs_preimage_tx() {
4640 let chanmon_cfgs = create_chanmon_cfgs(2);
4641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4643 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4645 // Create some initial channels
4646 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4648 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4650 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4651 assert_eq!(commitment_tx[0].input.len(), 1);
4652 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4654 // Settle A's commitment tx on B's chain
4655 assert!(nodes[1].node.claim_funds(payment_preimage));
4656 check_added_monitors!(nodes[1], 1);
4657 mine_transaction(&nodes[1], &commitment_tx[0]);
4658 check_added_monitors!(nodes[1], 1);
4659 let events = nodes[1].node.get_and_clear_pending_msg_events();
4661 MessageSendEvent::UpdateHTLCs { .. } => {},
4662 _ => panic!("Unexpected event"),
4665 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4666 _ => panic!("Unexepected event"),
4669 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4670 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4671 assert_eq!(node_txn.len(), 3);
4672 check_spends!(node_txn[0], commitment_tx[0]);
4673 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4674 check_spends!(node_txn[1], chan_1.3);
4675 check_spends!(node_txn[2], node_txn[1]);
4677 mine_transaction(&nodes[1], &node_txn[0]);
4678 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4679 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4681 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4682 assert_eq!(spend_txn.len(), 1);
4683 check_spends!(spend_txn[0], node_txn[0]);
4687 fn test_static_spendable_outputs_timeout_tx() {
4688 let chanmon_cfgs = create_chanmon_cfgs(2);
4689 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4690 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4691 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4693 // Create some initial channels
4694 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4696 // Rebalance the network a bit by relaying one payment through all the channels ...
4697 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4699 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4701 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4702 assert_eq!(commitment_tx[0].input.len(), 1);
4703 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4705 // Settle A's commitment tx on B' chain
4706 mine_transaction(&nodes[1], &commitment_tx[0]);
4707 check_added_monitors!(nodes[1], 1);
4708 let events = nodes[1].node.get_and_clear_pending_msg_events();
4710 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4711 _ => panic!("Unexpected event"),
4713 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4715 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4716 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4717 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
4718 check_spends!(node_txn[0], chan_1.3.clone());
4719 check_spends!(node_txn[1], commitment_tx[0].clone());
4720 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4722 mine_transaction(&nodes[1], &node_txn[1]);
4723 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4724 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4725 expect_payment_failed!(nodes[1], our_payment_hash, true);
4727 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4728 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4729 check_spends!(spend_txn[0], commitment_tx[0]);
4730 check_spends!(spend_txn[1], node_txn[1]);
4731 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
4735 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4736 let chanmon_cfgs = create_chanmon_cfgs(2);
4737 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4738 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4739 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4741 // Create some initial channels
4742 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4744 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4745 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4746 assert_eq!(revoked_local_txn[0].input.len(), 1);
4747 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4749 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4751 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4752 check_closed_broadcast!(nodes[1], true);
4753 check_added_monitors!(nodes[1], 1);
4754 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4756 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4757 assert_eq!(node_txn.len(), 2);
4758 assert_eq!(node_txn[0].input.len(), 2);
4759 check_spends!(node_txn[0], revoked_local_txn[0]);
4761 mine_transaction(&nodes[1], &node_txn[0]);
4762 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4764 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4765 assert_eq!(spend_txn.len(), 1);
4766 check_spends!(spend_txn[0], node_txn[0]);
4770 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4771 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4772 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4775 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4777 // Create some initial channels
4778 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4780 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4781 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4782 assert_eq!(revoked_local_txn[0].input.len(), 1);
4783 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4785 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4787 // A will generate HTLC-Timeout from revoked commitment tx
4788 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4789 check_closed_broadcast!(nodes[0], true);
4790 check_added_monitors!(nodes[0], 1);
4791 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4792 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
4794 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4795 assert_eq!(revoked_htlc_txn.len(), 2);
4796 check_spends!(revoked_htlc_txn[0], chan_1.3);
4797 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
4798 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4799 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
4800 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
4802 // B will generate justice tx from A's revoked commitment/HTLC tx
4803 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4804 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
4805 check_closed_broadcast!(nodes[1], true);
4806 check_added_monitors!(nodes[1], 1);
4807 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4809 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4810 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4811 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4812 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4813 // transactions next...
4814 assert_eq!(node_txn[0].input.len(), 3);
4815 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
4817 assert_eq!(node_txn[1].input.len(), 2);
4818 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
4819 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
4820 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4822 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
4823 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
4826 assert_eq!(node_txn[2].input.len(), 1);
4827 check_spends!(node_txn[2], chan_1.3);
4829 mine_transaction(&nodes[1], &node_txn[1]);
4830 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4832 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4833 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4834 assert_eq!(spend_txn.len(), 1);
4835 assert_eq!(spend_txn[0].input.len(), 1);
4836 check_spends!(spend_txn[0], node_txn[1]);
4840 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4841 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4842 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4847 // Create some initial channels
4848 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4850 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4851 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4852 assert_eq!(revoked_local_txn[0].input.len(), 1);
4853 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4855 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4856 assert_eq!(revoked_local_txn[0].output.len(), 2);
4858 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4860 // B will generate HTLC-Success from revoked commitment tx
4861 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4862 check_closed_broadcast!(nodes[1], true);
4863 check_added_monitors!(nodes[1], 1);
4864 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
4865 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4867 assert_eq!(revoked_htlc_txn.len(), 2);
4868 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4869 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4870 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4872 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4873 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4874 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4876 // A will generate justice tx from B's revoked commitment/HTLC tx
4877 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4878 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4879 check_closed_broadcast!(nodes[0], true);
4880 check_added_monitors!(nodes[0], 1);
4881 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
4883 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4884 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4886 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4887 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4888 // transactions next...
4889 assert_eq!(node_txn[0].input.len(), 2);
4890 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4891 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4892 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4894 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4895 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4898 assert_eq!(node_txn[1].input.len(), 1);
4899 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4901 check_spends!(node_txn[2], chan_1.3);
4903 mine_transaction(&nodes[0], &node_txn[1]);
4904 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4906 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4907 // didn't try to generate any new transactions.
4909 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4910 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4911 assert_eq!(spend_txn.len(), 3);
4912 assert_eq!(spend_txn[0].input.len(), 1);
4913 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4914 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4915 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4916 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4920 fn test_onchain_to_onchain_claim() {
4921 // Test that in case of channel closure, we detect the state of output and claim HTLC
4922 // on downstream peer's remote commitment tx.
4923 // First, have C claim an HTLC against its own latest commitment transaction.
4924 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4926 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4929 let chanmon_cfgs = create_chanmon_cfgs(3);
4930 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4931 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4932 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4934 // Create some initial channels
4935 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4936 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4938 // Ensure all nodes are at the same height
4939 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4940 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4941 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4942 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4944 // Rebalance the network a bit by relaying one payment through all the channels ...
4945 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4946 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4948 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4949 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4950 check_spends!(commitment_tx[0], chan_2.3);
4951 nodes[2].node.claim_funds(payment_preimage);
4952 check_added_monitors!(nodes[2], 1);
4953 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4954 assert!(updates.update_add_htlcs.is_empty());
4955 assert!(updates.update_fail_htlcs.is_empty());
4956 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4957 assert!(updates.update_fail_malformed_htlcs.is_empty());
4959 mine_transaction(&nodes[2], &commitment_tx[0]);
4960 check_closed_broadcast!(nodes[2], true);
4961 check_added_monitors!(nodes[2], 1);
4962 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
4964 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4965 assert_eq!(c_txn.len(), 3);
4966 assert_eq!(c_txn[0], c_txn[2]);
4967 assert_eq!(commitment_tx[0], c_txn[1]);
4968 check_spends!(c_txn[1], chan_2.3);
4969 check_spends!(c_txn[2], c_txn[1]);
4970 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4971 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4972 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4973 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4975 // 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
4976 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4977 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
4978 check_added_monitors!(nodes[1], 1);
4979 let events = nodes[1].node.get_and_clear_pending_events();
4980 assert_eq!(events.len(), 2);
4982 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4983 _ => panic!("Unexpected event"),
4986 Event::PaymentForwarded { fee_earned_msat, claim_from_onchain_tx } => {
4987 assert_eq!(fee_earned_msat, Some(1000));
4988 assert_eq!(claim_from_onchain_tx, true);
4990 _ => panic!("Unexpected event"),
4993 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4994 // ChannelMonitor: claim tx
4995 assert_eq!(b_txn.len(), 1);
4996 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
4999 check_added_monitors!(nodes[1], 1);
5000 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5001 assert_eq!(msg_events.len(), 3);
5002 match msg_events[0] {
5003 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5004 _ => panic!("Unexpected event"),
5006 match msg_events[1] {
5007 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5008 _ => panic!("Unexpected event"),
5010 match msg_events[2] {
5011 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, .. } } => {
5012 assert!(update_add_htlcs.is_empty());
5013 assert!(update_fail_htlcs.is_empty());
5014 assert_eq!(update_fulfill_htlcs.len(), 1);
5015 assert!(update_fail_malformed_htlcs.is_empty());
5016 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5018 _ => panic!("Unexpected event"),
5020 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5021 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5022 mine_transaction(&nodes[1], &commitment_tx[0]);
5023 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5024 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5025 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5026 assert_eq!(b_txn.len(), 3);
5027 check_spends!(b_txn[1], chan_1.3);
5028 check_spends!(b_txn[2], b_txn[1]);
5029 check_spends!(b_txn[0], commitment_tx[0]);
5030 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5031 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5032 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5034 check_closed_broadcast!(nodes[1], true);
5035 check_added_monitors!(nodes[1], 1);
5039 fn test_duplicate_payment_hash_one_failure_one_success() {
5040 // Topology : A --> B --> C --> D
5041 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5042 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5043 // we forward one of the payments onwards to D.
5044 let chanmon_cfgs = create_chanmon_cfgs(4);
5045 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5046 // When this test was written, the default base fee floated based on the HTLC count.
5047 // It is now fixed, so we simply set the fee to the expected value here.
5048 let mut config = test_default_channel_config();
5049 config.channel_options.forwarding_fee_base_msat = 196;
5050 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
5051 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5052 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5054 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5055 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5056 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5058 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5059 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5060 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5061 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5062 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5064 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5066 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5067 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5068 // script push size limit so that the below script length checks match
5069 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5070 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], vec![], 900000, TEST_FINAL_CLTV - 40);
5071 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5073 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5074 assert_eq!(commitment_txn[0].input.len(), 1);
5075 check_spends!(commitment_txn[0], chan_2.3);
5077 mine_transaction(&nodes[1], &commitment_txn[0]);
5078 check_closed_broadcast!(nodes[1], true);
5079 check_added_monitors!(nodes[1], 1);
5080 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5081 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5083 let htlc_timeout_tx;
5084 { // Extract one of the two HTLC-Timeout transaction
5085 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5086 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5087 assert_eq!(node_txn.len(), 4);
5088 check_spends!(node_txn[0], chan_2.3);
5090 check_spends!(node_txn[1], commitment_txn[0]);
5091 assert_eq!(node_txn[1].input.len(), 1);
5092 check_spends!(node_txn[2], commitment_txn[0]);
5093 assert_eq!(node_txn[2].input.len(), 1);
5094 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5095 check_spends!(node_txn[3], commitment_txn[0]);
5096 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5098 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5099 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5100 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5101 htlc_timeout_tx = node_txn[1].clone();
5104 nodes[2].node.claim_funds(our_payment_preimage);
5105 mine_transaction(&nodes[2], &commitment_txn[0]);
5106 check_added_monitors!(nodes[2], 2);
5107 check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed);
5108 let events = nodes[2].node.get_and_clear_pending_msg_events();
5110 MessageSendEvent::UpdateHTLCs { .. } => {},
5111 _ => panic!("Unexpected event"),
5114 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5115 _ => panic!("Unexepected event"),
5117 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5118 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)
5119 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5120 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5121 assert_eq!(htlc_success_txn[0].input.len(), 1);
5122 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5123 assert_eq!(htlc_success_txn[1].input.len(), 1);
5124 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5125 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5126 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5127 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5128 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5129 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5131 mine_transaction(&nodes[1], &htlc_timeout_tx);
5132 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5133 expect_pending_htlcs_forwardable!(nodes[1]);
5134 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5135 assert!(htlc_updates.update_add_htlcs.is_empty());
5136 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5137 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5138 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5139 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5140 check_added_monitors!(nodes[1], 1);
5142 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5143 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5145 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5147 expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5149 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5150 // Note that the fee paid is effectively double as the HTLC value (including the nodes[1] fee
5151 // and nodes[2] fee) is rounded down and then claimed in full.
5152 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5153 expect_payment_forwarded!(nodes[1], Some(196*2), true);
5154 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5155 assert!(updates.update_add_htlcs.is_empty());
5156 assert!(updates.update_fail_htlcs.is_empty());
5157 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5158 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5159 assert!(updates.update_fail_malformed_htlcs.is_empty());
5160 check_added_monitors!(nodes[1], 1);
5162 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5163 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5165 let events = nodes[0].node.get_and_clear_pending_events();
5167 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
5168 assert_eq!(*payment_preimage, our_payment_preimage);
5169 assert_eq!(*payment_hash, duplicate_payment_hash);
5171 _ => panic!("Unexpected event"),
5176 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5177 let chanmon_cfgs = create_chanmon_cfgs(2);
5178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5180 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5182 // Create some initial channels
5183 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5185 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5186 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5187 assert_eq!(local_txn.len(), 1);
5188 assert_eq!(local_txn[0].input.len(), 1);
5189 check_spends!(local_txn[0], chan_1.3);
5191 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5192 nodes[1].node.claim_funds(payment_preimage);
5193 check_added_monitors!(nodes[1], 1);
5194 mine_transaction(&nodes[1], &local_txn[0]);
5195 check_added_monitors!(nodes[1], 1);
5196 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5197 let events = nodes[1].node.get_and_clear_pending_msg_events();
5199 MessageSendEvent::UpdateHTLCs { .. } => {},
5200 _ => panic!("Unexpected event"),
5203 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5204 _ => panic!("Unexepected event"),
5207 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5208 assert_eq!(node_txn.len(), 3);
5209 assert_eq!(node_txn[0], node_txn[2]);
5210 assert_eq!(node_txn[1], local_txn[0]);
5211 assert_eq!(node_txn[0].input.len(), 1);
5212 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5213 check_spends!(node_txn[0], local_txn[0]);
5217 mine_transaction(&nodes[1], &node_tx);
5218 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5220 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5221 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5222 assert_eq!(spend_txn.len(), 1);
5223 assert_eq!(spend_txn[0].input.len(), 1);
5224 check_spends!(spend_txn[0], node_tx);
5225 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5228 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5229 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5230 // unrevoked commitment transaction.
5231 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5232 // a remote RAA before they could be failed backwards (and combinations thereof).
5233 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5234 // use the same payment hashes.
5235 // Thus, we use a six-node network:
5240 // And test where C fails back to A/B when D announces its latest commitment transaction
5241 let chanmon_cfgs = create_chanmon_cfgs(6);
5242 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5243 // When this test was written, the default base fee floated based on the HTLC count.
5244 // It is now fixed, so we simply set the fee to the expected value here.
5245 let mut config = test_default_channel_config();
5246 config.channel_options.forwarding_fee_base_msat = 196;
5247 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5248 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5249 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5251 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5252 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5253 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5254 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5255 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5257 // Rebalance and check output sanity...
5258 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5259 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5260 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5262 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5264 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
5266 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
5267 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5269 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5271 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5273 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5275 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5276 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5278 send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, 0).unwrap());
5280 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, 0).unwrap());
5283 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5285 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5286 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, 0).unwrap()); // not added < dust limit + HTLC tx fee
5289 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
5291 let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5292 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, 0).unwrap());
5294 // Double-check that six of the new HTLC were added
5295 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5296 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5297 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5298 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5300 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5301 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5302 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5303 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5304 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5305 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5306 check_added_monitors!(nodes[4], 0);
5307 expect_pending_htlcs_forwardable!(nodes[4]);
5308 check_added_monitors!(nodes[4], 1);
5310 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5311 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5312 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5313 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5314 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5315 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5317 // Fail 3rd below-dust and 7th above-dust HTLCs
5318 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5319 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5320 check_added_monitors!(nodes[5], 0);
5321 expect_pending_htlcs_forwardable!(nodes[5]);
5322 check_added_monitors!(nodes[5], 1);
5324 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5325 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5326 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5327 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5329 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5331 expect_pending_htlcs_forwardable!(nodes[3]);
5332 check_added_monitors!(nodes[3], 1);
5333 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5334 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5335 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5336 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5337 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5338 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5339 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5340 if deliver_last_raa {
5341 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5343 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5346 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5347 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5348 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5349 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5351 // We now broadcast the latest commitment transaction, which *should* result in failures for
5352 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5353 // the non-broadcast above-dust HTLCs.
5355 // Alternatively, we may broadcast the previous commitment transaction, which should only
5356 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5357 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5359 if announce_latest {
5360 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5362 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5364 let events = nodes[2].node.get_and_clear_pending_events();
5365 let close_event = if deliver_last_raa {
5366 assert_eq!(events.len(), 2);
5369 assert_eq!(events.len(), 1);
5373 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5374 _ => panic!("Unexpected event"),
5377 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5378 check_closed_broadcast!(nodes[2], true);
5379 if deliver_last_raa {
5380 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5382 expect_pending_htlcs_forwardable!(nodes[2]);
5384 check_added_monitors!(nodes[2], 3);
5386 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5387 assert_eq!(cs_msgs.len(), 2);
5388 let mut a_done = false;
5389 for msg in cs_msgs {
5391 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5392 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5393 // should be failed-backwards here.
5394 let target = if *node_id == nodes[0].node.get_our_node_id() {
5395 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5396 for htlc in &updates.update_fail_htlcs {
5397 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 });
5399 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5404 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5405 for htlc in &updates.update_fail_htlcs {
5406 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5408 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5409 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5412 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5413 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5414 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5415 if announce_latest {
5416 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5417 if *node_id == nodes[0].node.get_our_node_id() {
5418 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5421 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5423 _ => panic!("Unexpected event"),
5427 let as_events = nodes[0].node.get_and_clear_pending_events();
5428 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5429 let mut as_failds = HashSet::new();
5430 let mut as_updates = 0;
5431 for event in as_events.iter() {
5432 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5433 assert!(as_failds.insert(*payment_hash));
5434 if *payment_hash != payment_hash_2 {
5435 assert_eq!(*rejected_by_dest, deliver_last_raa);
5437 assert!(!rejected_by_dest);
5439 if network_update.is_some() {
5442 } else { panic!("Unexpected event"); }
5444 assert!(as_failds.contains(&payment_hash_1));
5445 assert!(as_failds.contains(&payment_hash_2));
5446 if announce_latest {
5447 assert!(as_failds.contains(&payment_hash_3));
5448 assert!(as_failds.contains(&payment_hash_5));
5450 assert!(as_failds.contains(&payment_hash_6));
5452 let bs_events = nodes[1].node.get_and_clear_pending_events();
5453 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5454 let mut bs_failds = HashSet::new();
5455 let mut bs_updates = 0;
5456 for event in bs_events.iter() {
5457 if let &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, .. } = event {
5458 assert!(bs_failds.insert(*payment_hash));
5459 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5460 assert_eq!(*rejected_by_dest, deliver_last_raa);
5462 assert!(!rejected_by_dest);
5464 if network_update.is_some() {
5467 } else { panic!("Unexpected event"); }
5469 assert!(bs_failds.contains(&payment_hash_1));
5470 assert!(bs_failds.contains(&payment_hash_2));
5471 if announce_latest {
5472 assert!(bs_failds.contains(&payment_hash_4));
5474 assert!(bs_failds.contains(&payment_hash_5));
5476 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5477 // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5478 // unknown-preimage-etc, B should have gotten 2. Thus, in the
5479 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5480 assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5481 assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5485 fn test_fail_backwards_latest_remote_announce_a() {
5486 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5490 fn test_fail_backwards_latest_remote_announce_b() {
5491 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5495 fn test_fail_backwards_previous_remote_announce() {
5496 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5497 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5498 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5502 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5503 let chanmon_cfgs = create_chanmon_cfgs(2);
5504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5508 // Create some initial channels
5509 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5511 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5512 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5513 assert_eq!(local_txn[0].input.len(), 1);
5514 check_spends!(local_txn[0], chan_1.3);
5516 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5517 mine_transaction(&nodes[0], &local_txn[0]);
5518 check_closed_broadcast!(nodes[0], true);
5519 check_added_monitors!(nodes[0], 1);
5520 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5521 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5523 let htlc_timeout = {
5524 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5525 assert_eq!(node_txn.len(), 2);
5526 check_spends!(node_txn[0], chan_1.3);
5527 assert_eq!(node_txn[1].input.len(), 1);
5528 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5529 check_spends!(node_txn[1], local_txn[0]);
5533 mine_transaction(&nodes[0], &htlc_timeout);
5534 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5535 expect_payment_failed!(nodes[0], our_payment_hash, true);
5537 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5538 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5539 assert_eq!(spend_txn.len(), 3);
5540 check_spends!(spend_txn[0], local_txn[0]);
5541 assert_eq!(spend_txn[1].input.len(), 1);
5542 check_spends!(spend_txn[1], htlc_timeout);
5543 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5544 assert_eq!(spend_txn[2].input.len(), 2);
5545 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5546 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5547 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5551 fn test_key_derivation_params() {
5552 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5553 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5554 // let us re-derive the channel key set to then derive a delayed_payment_key.
5556 let chanmon_cfgs = create_chanmon_cfgs(3);
5558 // We manually create the node configuration to backup the seed.
5559 let seed = [42; 32];
5560 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5561 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);
5562 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager: &keys_manager, node_seed: seed, features: InitFeatures::known() };
5563 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5564 node_cfgs.remove(0);
5565 node_cfgs.insert(0, node);
5567 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5568 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5570 // Create some initial channels
5571 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5573 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5574 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5575 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5577 // Ensure all nodes are at the same height
5578 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5579 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5580 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5581 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5583 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5584 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5585 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5586 assert_eq!(local_txn_1[0].input.len(), 1);
5587 check_spends!(local_txn_1[0], chan_1.3);
5589 // We check funding pubkey are unique
5590 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]));
5591 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]));
5592 if from_0_funding_key_0 == from_1_funding_key_0
5593 || from_0_funding_key_0 == from_1_funding_key_1
5594 || from_0_funding_key_1 == from_1_funding_key_0
5595 || from_0_funding_key_1 == from_1_funding_key_1 {
5596 panic!("Funding pubkeys aren't unique");
5599 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5600 mine_transaction(&nodes[0], &local_txn_1[0]);
5601 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5602 check_closed_broadcast!(nodes[0], true);
5603 check_added_monitors!(nodes[0], 1);
5604 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5606 let htlc_timeout = {
5607 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5608 assert_eq!(node_txn[1].input.len(), 1);
5609 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5610 check_spends!(node_txn[1], local_txn_1[0]);
5614 mine_transaction(&nodes[0], &htlc_timeout);
5615 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5616 expect_payment_failed!(nodes[0], our_payment_hash, true);
5618 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5619 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5620 let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5621 assert_eq!(spend_txn.len(), 3);
5622 check_spends!(spend_txn[0], local_txn_1[0]);
5623 assert_eq!(spend_txn[1].input.len(), 1);
5624 check_spends!(spend_txn[1], htlc_timeout);
5625 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5626 assert_eq!(spend_txn[2].input.len(), 2);
5627 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5628 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5629 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5633 fn test_static_output_closing_tx() {
5634 let chanmon_cfgs = create_chanmon_cfgs(2);
5635 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5636 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5637 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5639 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5641 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5642 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5644 mine_transaction(&nodes[0], &closing_tx);
5645 check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure);
5646 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5648 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5649 assert_eq!(spend_txn.len(), 1);
5650 check_spends!(spend_txn[0], closing_tx);
5652 mine_transaction(&nodes[1], &closing_tx);
5653 check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure);
5654 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5656 let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5657 assert_eq!(spend_txn.len(), 1);
5658 check_spends!(spend_txn[0], closing_tx);
5661 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5662 let chanmon_cfgs = create_chanmon_cfgs(2);
5663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5665 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5666 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5668 let (our_payment_preimage, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5670 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5671 // present in B's local commitment transaction, but none of A's commitment transactions.
5672 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5673 check_added_monitors!(nodes[1], 1);
5675 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5676 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5677 let events = nodes[0].node.get_and_clear_pending_events();
5678 assert_eq!(events.len(), 1);
5680 Event::PaymentSent { payment_preimage, payment_hash } => {
5681 assert_eq!(payment_preimage, our_payment_preimage);
5682 assert_eq!(payment_hash, our_payment_hash);
5684 _ => panic!("Unexpected event"),
5687 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5688 check_added_monitors!(nodes[0], 1);
5689 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5690 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5691 check_added_monitors!(nodes[1], 1);
5693 let starting_block = nodes[1].best_block_info();
5694 let mut block = Block {
5695 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5698 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5699 connect_block(&nodes[1], &block);
5700 block.header.prev_blockhash = block.block_hash();
5702 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5703 check_closed_broadcast!(nodes[1], true);
5704 check_added_monitors!(nodes[1], 1);
5705 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
5708 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5709 let chanmon_cfgs = create_chanmon_cfgs(2);
5710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5712 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5713 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5715 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5716 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
5717 check_added_monitors!(nodes[0], 1);
5719 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5721 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5722 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5723 // to "time out" the HTLC.
5725 let starting_block = nodes[1].best_block_info();
5726 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5728 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5729 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5730 header.prev_blockhash = header.block_hash();
5732 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5733 check_closed_broadcast!(nodes[0], true);
5734 check_added_monitors!(nodes[0], 1);
5735 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5738 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5739 let chanmon_cfgs = create_chanmon_cfgs(3);
5740 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5741 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5742 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5743 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5745 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5746 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5747 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5748 // actually revoked.
5749 let htlc_value = if use_dust { 50000 } else { 3000000 };
5750 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5751 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
5752 expect_pending_htlcs_forwardable!(nodes[1]);
5753 check_added_monitors!(nodes[1], 1);
5755 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5756 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5757 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5758 check_added_monitors!(nodes[0], 1);
5759 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5760 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5761 check_added_monitors!(nodes[1], 1);
5762 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5763 check_added_monitors!(nodes[1], 1);
5764 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5766 if check_revoke_no_close {
5767 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5768 check_added_monitors!(nodes[0], 1);
5771 let starting_block = nodes[1].best_block_info();
5772 let mut block = Block {
5773 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5776 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5777 connect_block(&nodes[0], &block);
5778 block.header.prev_blockhash = block.block_hash();
5780 if !check_revoke_no_close {
5781 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5782 check_closed_broadcast!(nodes[0], true);
5783 check_added_monitors!(nodes[0], 1);
5784 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
5786 expect_payment_failed!(nodes[0], our_payment_hash, true);
5790 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5791 // There are only a few cases to test here:
5792 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5793 // broadcastable commitment transactions result in channel closure,
5794 // * its included in an unrevoked-but-previous remote commitment transaction,
5795 // * its included in the latest remote or local commitment transactions.
5796 // We test each of the three possible commitment transactions individually and use both dust and
5798 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5799 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5800 // tested for at least one of the cases in other tests.
5802 fn htlc_claim_single_commitment_only_a() {
5803 do_htlc_claim_local_commitment_only(true);
5804 do_htlc_claim_local_commitment_only(false);
5806 do_htlc_claim_current_remote_commitment_only(true);
5807 do_htlc_claim_current_remote_commitment_only(false);
5811 fn htlc_claim_single_commitment_only_b() {
5812 do_htlc_claim_previous_remote_commitment_only(true, false);
5813 do_htlc_claim_previous_remote_commitment_only(false, false);
5814 do_htlc_claim_previous_remote_commitment_only(true, true);
5815 do_htlc_claim_previous_remote_commitment_only(false, true);
5820 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5821 let chanmon_cfgs = create_chanmon_cfgs(2);
5822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5825 //Force duplicate channel ids
5826 for node in nodes.iter() {
5827 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5830 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5831 let channel_value_satoshis=10000;
5832 let push_msat=10001;
5833 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5834 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5835 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5837 //Create a second channel with a channel_id collision
5838 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5842 fn bolt2_open_channel_sending_node_checks_part2() {
5843 let chanmon_cfgs = create_chanmon_cfgs(2);
5844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5848 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5849 let channel_value_satoshis=2^24;
5850 let push_msat=10001;
5851 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5853 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5854 let channel_value_satoshis=10000;
5855 // Test when push_msat is equal to 1000 * funding_satoshis.
5856 let push_msat=1000*channel_value_satoshis+1;
5857 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5859 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5860 let channel_value_satoshis=10000;
5861 let push_msat=10001;
5862 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
5863 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5864 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5866 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5867 // 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
5868 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5870 // 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.
5871 assert!(BREAKDOWN_TIMEOUT>0);
5872 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5874 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5875 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5876 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5878 // 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.
5879 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5880 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5881 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5882 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5883 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5887 fn bolt2_open_channel_sane_dust_limit() {
5888 let chanmon_cfgs = create_chanmon_cfgs(2);
5889 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5890 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5891 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5893 let channel_value_satoshis=1000000;
5894 let push_msat=10001;
5895 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5896 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5897 node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5898 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5900 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5901 let events = nodes[1].node.get_and_clear_pending_msg_events();
5902 let err_msg = match events[0] {
5903 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5906 _ => panic!("Unexpected event"),
5908 assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5911 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5912 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5913 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5914 // is no longer affordable once it's freed.
5916 fn test_fail_holding_cell_htlc_upon_free() {
5917 let chanmon_cfgs = create_chanmon_cfgs(2);
5918 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5919 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5920 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5921 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5923 // First nodes[0] generates an update_fee, setting the channel's
5924 // pending_update_fee.
5926 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5927 *feerate_lock += 20;
5929 nodes[0].node.timer_tick_occurred();
5930 check_added_monitors!(nodes[0], 1);
5932 let events = nodes[0].node.get_and_clear_pending_msg_events();
5933 assert_eq!(events.len(), 1);
5934 let (update_msg, commitment_signed) = match events[0] {
5935 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5936 (update_fee.as_ref(), commitment_signed)
5938 _ => panic!("Unexpected event"),
5941 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5943 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5944 let channel_reserve = chan_stat.channel_reserve_msat;
5945 let feerate = get_feerate!(nodes[0], chan.2);
5947 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5948 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5949 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5951 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5952 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
5953 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5954 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5956 // Flush the pending fee update.
5957 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5958 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5959 check_added_monitors!(nodes[1], 1);
5960 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5961 check_added_monitors!(nodes[0], 1);
5963 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5964 // HTLC, but now that the fee has been raised the payment will now fail, causing
5965 // us to surface its failure to the user.
5966 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5967 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5968 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);
5969 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 {}",
5970 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
5971 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5973 // Check that the payment failed to be sent out.
5974 let events = nodes[0].node.get_and_clear_pending_events();
5975 assert_eq!(events.len(), 1);
5977 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
5978 assert_eq!(our_payment_hash.clone(), *payment_hash);
5979 assert_eq!(*rejected_by_dest, false);
5980 assert_eq!(*all_paths_failed, true);
5981 assert_eq!(*network_update, None);
5982 assert_eq!(*short_channel_id, None);
5983 assert_eq!(*error_code, None);
5984 assert_eq!(*error_data, None);
5986 _ => panic!("Unexpected event"),
5990 // Test that if multiple HTLCs are released from the holding cell and one is
5991 // valid but the other is no longer valid upon release, the valid HTLC can be
5992 // successfully completed while the other one fails as expected.
5994 fn test_free_and_fail_holding_cell_htlcs() {
5995 let chanmon_cfgs = create_chanmon_cfgs(2);
5996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5998 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5999 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6001 // First nodes[0] generates an update_fee, setting the channel's
6002 // pending_update_fee.
6004 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
6005 *feerate_lock += 200;
6007 nodes[0].node.timer_tick_occurred();
6008 check_added_monitors!(nodes[0], 1);
6010 let events = nodes[0].node.get_and_clear_pending_msg_events();
6011 assert_eq!(events.len(), 1);
6012 let (update_msg, commitment_signed) = match events[0] {
6013 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6014 (update_fee.as_ref(), commitment_signed)
6016 _ => panic!("Unexpected event"),
6019 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6021 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6022 let channel_reserve = chan_stat.channel_reserve_msat;
6023 let feerate = get_feerate!(nodes[0], chan.2);
6025 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6027 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6028 let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
6029 let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
6031 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6032 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6033 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6034 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6035 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6036 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6037 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6039 // Flush the pending fee update.
6040 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6041 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6042 check_added_monitors!(nodes[1], 1);
6043 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6044 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6045 check_added_monitors!(nodes[0], 2);
6047 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6048 // but now that the fee has been raised the second payment will now fail, causing us
6049 // to surface its failure to the user. The first payment should succeed.
6050 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6051 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6052 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);
6053 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 {}",
6054 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6055 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6057 // Check that the second payment failed to be sent out.
6058 let events = nodes[0].node.get_and_clear_pending_events();
6059 assert_eq!(events.len(), 1);
6061 &Event::PaymentPathFailed { ref payment_hash, ref rejected_by_dest, ref network_update, ref all_paths_failed, path: _, ref short_channel_id, ref error_code, ref error_data } => {
6062 assert_eq!(payment_hash_2.clone(), *payment_hash);
6063 assert_eq!(*rejected_by_dest, false);
6064 assert_eq!(*all_paths_failed, true);
6065 assert_eq!(*network_update, None);
6066 assert_eq!(*short_channel_id, None);
6067 assert_eq!(*error_code, None);
6068 assert_eq!(*error_data, None);
6070 _ => panic!("Unexpected event"),
6073 // Complete the first payment and the RAA from the fee update.
6074 let (payment_event, send_raa_event) = {
6075 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6076 assert_eq!(msgs.len(), 2);
6077 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6079 let raa = match send_raa_event {
6080 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6081 _ => panic!("Unexpected event"),
6083 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6084 check_added_monitors!(nodes[1], 1);
6085 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6086 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6087 let events = nodes[1].node.get_and_clear_pending_events();
6088 assert_eq!(events.len(), 1);
6090 Event::PendingHTLCsForwardable { .. } => {},
6091 _ => panic!("Unexpected event"),
6093 nodes[1].node.process_pending_htlc_forwards();
6094 let events = nodes[1].node.get_and_clear_pending_events();
6095 assert_eq!(events.len(), 1);
6097 Event::PaymentReceived { .. } => {},
6098 _ => panic!("Unexpected event"),
6100 nodes[1].node.claim_funds(payment_preimage_1);
6101 check_added_monitors!(nodes[1], 1);
6102 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6103 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6104 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6105 let events = nodes[0].node.get_and_clear_pending_events();
6106 assert_eq!(events.len(), 1);
6108 Event::PaymentSent { ref payment_preimage, ref payment_hash } => {
6109 assert_eq!(*payment_preimage, payment_preimage_1);
6110 assert_eq!(*payment_hash, payment_hash_1);
6112 _ => panic!("Unexpected event"),
6116 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6117 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6118 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6121 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6122 let chanmon_cfgs = create_chanmon_cfgs(3);
6123 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6124 // When this test was written, the default base fee floated based on the HTLC count.
6125 // It is now fixed, so we simply set the fee to the expected value here.
6126 let mut config = test_default_channel_config();
6127 config.channel_options.forwarding_fee_base_msat = 196;
6128 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6129 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6130 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6131 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6133 // First nodes[1] generates an update_fee, setting the channel's
6134 // pending_update_fee.
6136 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6137 *feerate_lock += 20;
6139 nodes[1].node.timer_tick_occurred();
6140 check_added_monitors!(nodes[1], 1);
6142 let events = nodes[1].node.get_and_clear_pending_msg_events();
6143 assert_eq!(events.len(), 1);
6144 let (update_msg, commitment_signed) = match events[0] {
6145 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6146 (update_fee.as_ref(), commitment_signed)
6148 _ => panic!("Unexpected event"),
6151 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6153 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6154 let channel_reserve = chan_stat.channel_reserve_msat;
6155 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6157 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6159 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6160 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6161 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6162 let payment_event = {
6163 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6164 check_added_monitors!(nodes[0], 1);
6166 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6167 assert_eq!(events.len(), 1);
6169 SendEvent::from_event(events.remove(0))
6171 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6172 check_added_monitors!(nodes[1], 0);
6173 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6174 expect_pending_htlcs_forwardable!(nodes[1]);
6176 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6177 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6179 // Flush the pending fee update.
6180 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6181 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6182 check_added_monitors!(nodes[2], 1);
6183 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6184 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6185 check_added_monitors!(nodes[1], 2);
6187 // A final RAA message is generated to finalize the fee update.
6188 let events = nodes[1].node.get_and_clear_pending_msg_events();
6189 assert_eq!(events.len(), 1);
6191 let raa_msg = match &events[0] {
6192 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6195 _ => panic!("Unexpected event"),
6198 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6199 check_added_monitors!(nodes[2], 1);
6200 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6202 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6203 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6204 assert_eq!(process_htlc_forwards_event.len(), 1);
6205 match &process_htlc_forwards_event[0] {
6206 &Event::PendingHTLCsForwardable { .. } => {},
6207 _ => panic!("Unexpected event"),
6210 // In response, we call ChannelManager's process_pending_htlc_forwards
6211 nodes[1].node.process_pending_htlc_forwards();
6212 check_added_monitors!(nodes[1], 1);
6214 // This causes the HTLC to be failed backwards.
6215 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6216 assert_eq!(fail_event.len(), 1);
6217 let (fail_msg, commitment_signed) = match &fail_event[0] {
6218 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6219 assert_eq!(updates.update_add_htlcs.len(), 0);
6220 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6221 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6222 assert_eq!(updates.update_fail_htlcs.len(), 1);
6223 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6225 _ => panic!("Unexpected event"),
6228 // Pass the failure messages back to nodes[0].
6229 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6230 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6232 // Complete the HTLC failure+removal process.
6233 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6234 check_added_monitors!(nodes[0], 1);
6235 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6236 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6237 check_added_monitors!(nodes[1], 2);
6238 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6239 assert_eq!(final_raa_event.len(), 1);
6240 let raa = match &final_raa_event[0] {
6241 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6242 _ => panic!("Unexpected event"),
6244 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6245 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6246 check_added_monitors!(nodes[0], 1);
6249 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6250 // 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.
6251 //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.
6254 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6255 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6256 let chanmon_cfgs = create_chanmon_cfgs(2);
6257 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6258 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6259 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6260 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6262 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6263 route.paths[0][0].fee_msat = 100;
6265 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6266 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6267 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6268 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6272 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6273 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6274 let chanmon_cfgs = create_chanmon_cfgs(2);
6275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6277 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6278 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6280 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6281 route.paths[0][0].fee_msat = 0;
6282 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6283 assert_eq!(err, "Cannot send 0-msat HTLC"));
6285 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6286 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6290 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6291 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6292 let chanmon_cfgs = create_chanmon_cfgs(2);
6293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6295 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6296 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6298 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6299 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6300 check_added_monitors!(nodes[0], 1);
6301 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6302 updates.update_add_htlcs[0].amount_msat = 0;
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6305 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6306 check_closed_broadcast!(nodes[1], true).unwrap();
6307 check_added_monitors!(nodes[1], 1);
6308 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() });
6312 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6313 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6314 //It is enforced when constructing a route.
6315 let chanmon_cfgs = create_chanmon_cfgs(2);
6316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6318 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6321 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], vec![], 100000000, 500000001);
6322 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6323 assert_eq!(err, &"Channel CLTV overflowed?"));
6327 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6328 //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.
6329 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6330 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6331 let chanmon_cfgs = create_chanmon_cfgs(2);
6332 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6333 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6334 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6335 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6336 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6338 for i in 0..max_accepted_htlcs {
6339 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6340 let payment_event = {
6341 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6342 check_added_monitors!(nodes[0], 1);
6344 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6345 assert_eq!(events.len(), 1);
6346 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6347 assert_eq!(htlcs[0].htlc_id, i);
6351 SendEvent::from_event(events.remove(0))
6353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6354 check_added_monitors!(nodes[1], 0);
6355 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6357 expect_pending_htlcs_forwardable!(nodes[1]);
6358 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6360 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6361 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6362 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6364 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6365 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6369 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6370 //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.
6371 let chanmon_cfgs = create_chanmon_cfgs(2);
6372 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6373 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6374 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6375 let channel_value = 100000;
6376 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6377 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6379 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6381 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6382 // Manually create a route over our max in flight (which our router normally automatically
6384 route.paths[0][0].fee_msat = max_in_flight + 1;
6385 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6386 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)));
6388 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6389 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);
6391 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6394 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6396 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6397 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6398 let chanmon_cfgs = create_chanmon_cfgs(2);
6399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6401 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6402 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6403 let htlc_minimum_msat: u64;
6405 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6406 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6407 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6410 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6411 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6412 check_added_monitors!(nodes[0], 1);
6413 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6414 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6415 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6416 assert!(nodes[1].node.list_channels().is_empty());
6417 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6418 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()));
6419 check_added_monitors!(nodes[1], 1);
6420 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6424 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6425 //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
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 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6433 let channel_reserve = chan_stat.channel_reserve_msat;
6434 let feerate = get_feerate!(nodes[0], chan.2);
6435 // The 2* and +1 are for the fee spike reserve.
6436 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6438 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6439 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6440 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6441 check_added_monitors!(nodes[0], 1);
6442 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6444 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6445 // at this time channel-initiatee receivers are not required to enforce that senders
6446 // respect the fee_spike_reserve.
6447 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6448 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6450 assert!(nodes[1].node.list_channels().is_empty());
6451 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6452 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6453 check_added_monitors!(nodes[1], 1);
6454 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6458 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6459 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6460 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6461 let chanmon_cfgs = create_chanmon_cfgs(2);
6462 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6463 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6464 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6465 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6467 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3999999);
6468 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6469 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6470 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6471 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height, &None).unwrap();
6472 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6474 let mut msg = msgs::UpdateAddHTLC {
6478 payment_hash: our_payment_hash,
6479 cltv_expiry: htlc_cltv,
6480 onion_routing_packet: onion_packet.clone(),
6483 for i in 0..super::channel::OUR_MAX_HTLCS {
6484 msg.htlc_id = i as u64;
6485 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6487 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6488 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6490 assert!(nodes[1].node.list_channels().is_empty());
6491 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6492 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6493 check_added_monitors!(nodes[1], 1);
6494 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6498 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6499 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6500 let chanmon_cfgs = create_chanmon_cfgs(2);
6501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6503 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6504 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6506 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6507 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6508 check_added_monitors!(nodes[0], 1);
6509 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6510 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6511 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6513 assert!(nodes[1].node.list_channels().is_empty());
6514 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6515 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6516 check_added_monitors!(nodes[1], 1);
6517 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6521 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6522 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6523 let chanmon_cfgs = create_chanmon_cfgs(2);
6524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6526 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6528 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6529 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6530 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6531 check_added_monitors!(nodes[0], 1);
6532 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6533 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6534 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6536 assert!(nodes[1].node.list_channels().is_empty());
6537 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6538 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6539 check_added_monitors!(nodes[1], 1);
6540 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6544 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6545 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6546 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6547 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6548 let chanmon_cfgs = create_chanmon_cfgs(2);
6549 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6550 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6551 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6553 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6554 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6555 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6556 check_added_monitors!(nodes[0], 1);
6557 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6558 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6560 //Disconnect and Reconnect
6561 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6562 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6563 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6564 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6565 assert_eq!(reestablish_1.len(), 1);
6566 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6567 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6568 assert_eq!(reestablish_2.len(), 1);
6569 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6570 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6571 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6572 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6575 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6576 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6577 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6578 check_added_monitors!(nodes[1], 1);
6579 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6583 assert!(nodes[1].node.list_channels().is_empty());
6584 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6585 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6586 check_added_monitors!(nodes[1], 1);
6587 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data });
6591 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6592 //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.
6594 let chanmon_cfgs = create_chanmon_cfgs(2);
6595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6598 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6599 let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6600 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6602 check_added_monitors!(nodes[0], 1);
6603 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6604 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6606 let update_msg = msgs::UpdateFulfillHTLC{
6609 payment_preimage: our_payment_preimage,
6612 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6614 assert!(nodes[0].node.list_channels().is_empty());
6615 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6616 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()));
6617 check_added_monitors!(nodes[0], 1);
6618 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6622 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6623 //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.
6625 let chanmon_cfgs = create_chanmon_cfgs(2);
6626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6629 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6631 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6632 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6633 check_added_monitors!(nodes[0], 1);
6634 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6635 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6637 let update_msg = msgs::UpdateFailHTLC{
6640 reason: msgs::OnionErrorPacket { data: Vec::new()},
6643 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6645 assert!(nodes[0].node.list_channels().is_empty());
6646 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6647 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()));
6648 check_added_monitors!(nodes[0], 1);
6649 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6653 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6654 //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.
6656 let chanmon_cfgs = create_chanmon_cfgs(2);
6657 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6658 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6659 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6660 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6662 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6663 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6664 check_added_monitors!(nodes[0], 1);
6665 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6666 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6667 let update_msg = msgs::UpdateFailMalformedHTLC{
6670 sha256_of_onion: [1; 32],
6671 failure_code: 0x8000,
6674 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6676 assert!(nodes[0].node.list_channels().is_empty());
6677 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6678 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()));
6679 check_added_monitors!(nodes[0], 1);
6680 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6684 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6685 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6687 let chanmon_cfgs = create_chanmon_cfgs(2);
6688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6693 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6695 nodes[1].node.claim_funds(our_payment_preimage);
6696 check_added_monitors!(nodes[1], 1);
6698 let events = nodes[1].node.get_and_clear_pending_msg_events();
6699 assert_eq!(events.len(), 1);
6700 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6702 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, .. } } => {
6703 assert!(update_add_htlcs.is_empty());
6704 assert_eq!(update_fulfill_htlcs.len(), 1);
6705 assert!(update_fail_htlcs.is_empty());
6706 assert!(update_fail_malformed_htlcs.is_empty());
6707 assert!(update_fee.is_none());
6708 update_fulfill_htlcs[0].clone()
6710 _ => panic!("Unexpected event"),
6714 update_fulfill_msg.htlc_id = 1;
6716 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6718 assert!(nodes[0].node.list_channels().is_empty());
6719 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6720 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6721 check_added_monitors!(nodes[0], 1);
6722 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6726 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6727 //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.
6729 let chanmon_cfgs = create_chanmon_cfgs(2);
6730 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6731 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6732 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6733 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6735 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6737 nodes[1].node.claim_funds(our_payment_preimage);
6738 check_added_monitors!(nodes[1], 1);
6740 let events = nodes[1].node.get_and_clear_pending_msg_events();
6741 assert_eq!(events.len(), 1);
6742 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6744 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, .. } } => {
6745 assert!(update_add_htlcs.is_empty());
6746 assert_eq!(update_fulfill_htlcs.len(), 1);
6747 assert!(update_fail_htlcs.is_empty());
6748 assert!(update_fail_malformed_htlcs.is_empty());
6749 assert!(update_fee.is_none());
6750 update_fulfill_htlcs[0].clone()
6752 _ => panic!("Unexpected event"),
6756 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6758 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6760 assert!(nodes[0].node.list_channels().is_empty());
6761 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6762 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6763 check_added_monitors!(nodes[0], 1);
6764 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6768 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6769 //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.
6771 let chanmon_cfgs = create_chanmon_cfgs(2);
6772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6777 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6778 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6779 check_added_monitors!(nodes[0], 1);
6781 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6782 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785 check_added_monitors!(nodes[1], 0);
6786 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6788 let events = nodes[1].node.get_and_clear_pending_msg_events();
6790 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6792 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, .. } } => {
6793 assert!(update_add_htlcs.is_empty());
6794 assert!(update_fulfill_htlcs.is_empty());
6795 assert!(update_fail_htlcs.is_empty());
6796 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6797 assert!(update_fee.is_none());
6798 update_fail_malformed_htlcs[0].clone()
6800 _ => panic!("Unexpected event"),
6803 update_msg.failure_code &= !0x8000;
6804 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6806 assert!(nodes[0].node.list_channels().is_empty());
6807 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6808 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6809 check_added_monitors!(nodes[0], 1);
6810 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data });
6814 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6815 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6816 // * 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.
6818 let chanmon_cfgs = create_chanmon_cfgs(3);
6819 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6820 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6821 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6822 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6823 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6825 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6828 let mut payment_event = {
6829 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6830 check_added_monitors!(nodes[0], 1);
6831 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6832 assert_eq!(events.len(), 1);
6833 SendEvent::from_event(events.remove(0))
6835 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6836 check_added_monitors!(nodes[1], 0);
6837 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6838 expect_pending_htlcs_forwardable!(nodes[1]);
6839 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6840 assert_eq!(events_2.len(), 1);
6841 check_added_monitors!(nodes[1], 1);
6842 payment_event = SendEvent::from_event(events_2.remove(0));
6843 assert_eq!(payment_event.msgs.len(), 1);
6846 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6847 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6848 check_added_monitors!(nodes[2], 0);
6849 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6851 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6852 assert_eq!(events_3.len(), 1);
6853 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6855 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 } } => {
6856 assert!(update_add_htlcs.is_empty());
6857 assert!(update_fulfill_htlcs.is_empty());
6858 assert!(update_fail_htlcs.is_empty());
6859 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6860 assert!(update_fee.is_none());
6861 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6863 _ => panic!("Unexpected event"),
6867 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6869 check_added_monitors!(nodes[1], 0);
6870 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6871 expect_pending_htlcs_forwardable!(nodes[1]);
6872 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6873 assert_eq!(events_4.len(), 1);
6875 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6877 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, .. } } => {
6878 assert!(update_add_htlcs.is_empty());
6879 assert!(update_fulfill_htlcs.is_empty());
6880 assert_eq!(update_fail_htlcs.len(), 1);
6881 assert!(update_fail_malformed_htlcs.is_empty());
6882 assert!(update_fee.is_none());
6884 _ => panic!("Unexpected event"),
6887 check_added_monitors!(nodes[1], 1);
6890 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6891 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6892 // 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
6893 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6895 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6896 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6897 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6898 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6899 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6900 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6902 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6904 // We route 2 dust-HTLCs between A and B
6905 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6906 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6907 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6909 // Cache one local commitment tx as previous
6910 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6912 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6913 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6914 check_added_monitors!(nodes[1], 0);
6915 expect_pending_htlcs_forwardable!(nodes[1]);
6916 check_added_monitors!(nodes[1], 1);
6918 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6919 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6920 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6921 check_added_monitors!(nodes[0], 1);
6923 // Cache one local commitment tx as lastest
6924 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6926 let events = nodes[0].node.get_and_clear_pending_msg_events();
6928 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6929 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6931 _ => panic!("Unexpected event"),
6934 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6935 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6937 _ => panic!("Unexpected event"),
6940 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6941 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6942 if announce_latest {
6943 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6945 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6948 check_closed_broadcast!(nodes[0], true);
6949 check_added_monitors!(nodes[0], 1);
6950 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
6952 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6953 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6954 let events = nodes[0].node.get_and_clear_pending_events();
6955 // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
6956 assert_eq!(events.len(), 2);
6957 let mut first_failed = false;
6958 for event in events {
6960 Event::PaymentPathFailed { payment_hash, .. } => {
6961 if payment_hash == payment_hash_1 {
6962 assert!(!first_failed);
6963 first_failed = true;
6965 assert_eq!(payment_hash, payment_hash_2);
6968 _ => panic!("Unexpected event"),
6974 fn test_failure_delay_dust_htlc_local_commitment() {
6975 do_test_failure_delay_dust_htlc_local_commitment(true);
6976 do_test_failure_delay_dust_htlc_local_commitment(false);
6979 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6980 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6981 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6982 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6983 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6984 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6985 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6987 let chanmon_cfgs = create_chanmon_cfgs(3);
6988 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6989 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6990 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6991 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6993 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6995 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6996 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6998 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6999 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7001 // We revoked bs_commitment_tx
7003 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7004 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7007 let mut timeout_tx = Vec::new();
7009 // We fail dust-HTLC 1 by broadcast of local commitment tx
7010 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7011 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7012 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7013 expect_payment_failed!(nodes[0], dust_hash, true);
7015 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7016 check_closed_broadcast!(nodes[0], true);
7017 check_added_monitors!(nodes[0], 1);
7018 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7019 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7020 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7021 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7022 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7023 mine_transaction(&nodes[0], &timeout_tx[0]);
7024 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7025 expect_payment_failed!(nodes[0], non_dust_hash, true);
7027 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7028 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7029 check_closed_broadcast!(nodes[0], true);
7030 check_added_monitors!(nodes[0], 1);
7031 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7032 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7033 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7034 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7036 expect_payment_failed!(nodes[0], dust_hash, true);
7037 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7038 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7039 mine_transaction(&nodes[0], &timeout_tx[0]);
7040 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7041 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7042 expect_payment_failed!(nodes[0], non_dust_hash, true);
7044 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7046 let events = nodes[0].node.get_and_clear_pending_events();
7047 assert_eq!(events.len(), 2);
7050 Event::PaymentPathFailed { payment_hash, .. } => {
7051 if payment_hash == dust_hash { first = true; }
7052 else { first = false; }
7054 _ => panic!("Unexpected event"),
7057 Event::PaymentPathFailed { payment_hash, .. } => {
7058 if first { assert_eq!(payment_hash, non_dust_hash); }
7059 else { assert_eq!(payment_hash, dust_hash); }
7061 _ => panic!("Unexpected event"),
7068 fn test_sweep_outbound_htlc_failure_update() {
7069 do_test_sweep_outbound_htlc_failure_update(false, true);
7070 do_test_sweep_outbound_htlc_failure_update(false, false);
7071 do_test_sweep_outbound_htlc_failure_update(true, false);
7075 fn test_user_configurable_csv_delay() {
7076 // We test our channel constructors yield errors when we pass them absurd csv delay
7078 let mut low_our_to_self_config = UserConfig::default();
7079 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7080 let mut high_their_to_self_config = UserConfig::default();
7081 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7082 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7083 let chanmon_cfgs = create_chanmon_cfgs(2);
7084 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7085 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7086 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7088 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7089 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) {
7091 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())); },
7092 _ => panic!("Unexpected event"),
7094 } else { assert!(false) }
7096 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7097 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7098 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7099 open_channel.to_self_delay = 200;
7100 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) {
7102 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())); },
7103 _ => panic!("Unexpected event"),
7105 } else { assert!(false); }
7107 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7108 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7109 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()));
7110 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7111 accept_channel.to_self_delay = 200;
7112 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7114 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7116 &ErrorAction::SendErrorMessage { ref msg } => {
7117 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()));
7118 reason_msg = msg.data.clone();
7122 } else { panic!(); }
7123 check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg });
7125 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7126 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7127 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7128 open_channel.to_self_delay = 200;
7129 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) {
7131 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())); },
7132 _ => panic!("Unexpected event"),
7134 } else { assert!(false); }
7138 fn test_data_loss_protect() {
7139 // We want to be sure that :
7140 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7141 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7142 // * we close channel in case of detecting other being fallen behind
7143 // * we are able to claim our own outputs thanks to to_remote being static
7144 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7150 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7151 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7152 // during signing due to revoked tx
7153 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7154 let keys_manager = &chanmon_cfgs[0].keys_manager;
7157 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7158 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7159 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7161 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7163 // Cache node A state before any channel update
7164 let previous_node_state = nodes[0].node.encode();
7165 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7166 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7168 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7169 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7171 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7172 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7174 // Restore node A from previous state
7175 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7176 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7177 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7178 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7179 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) };
7180 persister = test_utils::TestPersister::new();
7181 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7183 let mut channel_monitors = HashMap::new();
7184 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7185 <(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 {
7186 keys_manager: keys_manager,
7187 fee_estimator: &fee_estimator,
7188 chain_monitor: &monitor,
7190 tx_broadcaster: &tx_broadcaster,
7191 default_config: UserConfig::default(),
7195 nodes[0].node = &node_state_0;
7196 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7197 nodes[0].chain_monitor = &monitor;
7198 nodes[0].chain_source = &chain_source;
7200 check_added_monitors!(nodes[0], 1);
7202 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7203 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7205 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7207 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7208 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7209 check_added_monitors!(nodes[0], 1);
7212 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7213 assert_eq!(node_txn.len(), 0);
7216 let mut reestablish_1 = Vec::with_capacity(1);
7217 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7218 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7219 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7220 reestablish_1.push(msg.clone());
7221 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7222 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7224 &ErrorAction::SendErrorMessage { ref msg } => {
7225 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");
7227 _ => panic!("Unexpected event!"),
7230 panic!("Unexpected event")
7234 // Check we close channel detecting A is fallen-behind
7235 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7236 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Peer attempted to reestablish channel with a very old local commitment transaction".to_string() });
7237 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7238 check_added_monitors!(nodes[1], 1);
7240 // Check A is able to claim to_remote output
7241 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7242 assert_eq!(node_txn.len(), 1);
7243 check_spends!(node_txn[0], chan.3);
7244 assert_eq!(node_txn[0].output.len(), 2);
7245 mine_transaction(&nodes[0], &node_txn[0]);
7246 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7247 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() });
7248 let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
7249 assert_eq!(spend_txn.len(), 1);
7250 check_spends!(spend_txn[0], node_txn[0]);
7254 fn test_check_htlc_underpaying() {
7255 // Send payment through A -> B but A is maliciously
7256 // sending a probe payment (i.e less than expected value0
7257 // to B, B should refuse payment.
7259 let chanmon_cfgs = create_chanmon_cfgs(2);
7260 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7261 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7262 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7264 // Create some initial channels
7265 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7267 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph, &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7268 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7269 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7270 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7271 check_added_monitors!(nodes[0], 1);
7273 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7274 assert_eq!(events.len(), 1);
7275 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7276 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7277 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7279 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7280 // and then will wait a second random delay before failing the HTLC back:
7281 expect_pending_htlcs_forwardable!(nodes[1]);
7282 expect_pending_htlcs_forwardable!(nodes[1]);
7284 // Node 3 is expecting payment of 100_000 but received 10_000,
7285 // it should fail htlc like we didn't know the preimage.
7286 nodes[1].node.process_pending_htlc_forwards();
7288 let events = nodes[1].node.get_and_clear_pending_msg_events();
7289 assert_eq!(events.len(), 1);
7290 let (update_fail_htlc, commitment_signed) = match events[0] {
7291 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 } } => {
7292 assert!(update_add_htlcs.is_empty());
7293 assert!(update_fulfill_htlcs.is_empty());
7294 assert_eq!(update_fail_htlcs.len(), 1);
7295 assert!(update_fail_malformed_htlcs.is_empty());
7296 assert!(update_fee.is_none());
7297 (update_fail_htlcs[0].clone(), commitment_signed)
7299 _ => panic!("Unexpected event"),
7301 check_added_monitors!(nodes[1], 1);
7303 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7304 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7306 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7307 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7308 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7309 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7313 fn test_announce_disable_channels() {
7314 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7315 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7317 let chanmon_cfgs = create_chanmon_cfgs(2);
7318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7320 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7322 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7323 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7324 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7327 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7328 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7330 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7331 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7332 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7333 assert_eq!(msg_events.len(), 3);
7334 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7335 for e in msg_events {
7337 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7338 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7339 // Check that each channel gets updated exactly once
7340 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7341 panic!("Generated ChannelUpdate for wrong chan!");
7344 _ => panic!("Unexpected event"),
7348 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7349 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7350 assert_eq!(reestablish_1.len(), 3);
7351 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7352 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7353 assert_eq!(reestablish_2.len(), 3);
7355 // Reestablish chan_1
7356 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7357 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7358 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7359 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7360 // Reestablish chan_2
7361 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7362 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7363 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7364 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7365 // Reestablish chan_3
7366 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7367 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7368 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7369 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7371 nodes[0].node.timer_tick_occurred();
7372 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7373 nodes[0].node.timer_tick_occurred();
7374 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7375 assert_eq!(msg_events.len(), 3);
7376 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7377 for e in msg_events {
7379 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7380 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7381 // Check that each channel gets updated exactly once
7382 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7383 panic!("Generated ChannelUpdate for wrong chan!");
7386 _ => panic!("Unexpected event"),
7392 fn test_priv_forwarding_rejection() {
7393 // If we have a private channel with outbound liquidity, and
7394 // UserConfig::accept_forwards_to_priv_channels is set to false, we should reject any attempts
7395 // to forward through that channel.
7396 let chanmon_cfgs = create_chanmon_cfgs(3);
7397 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7398 let mut no_announce_cfg = test_default_channel_config();
7399 no_announce_cfg.channel_options.announced_channel = false;
7400 no_announce_cfg.accept_forwards_to_priv_channels = false;
7401 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, Some(no_announce_cfg), None]);
7402 let persister: test_utils::TestPersister;
7403 let new_chain_monitor: test_utils::TestChainMonitor;
7404 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
7405 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7407 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
7409 // Note that the create_*_chan functions in utils requires announcement_signatures, which we do
7410 // not send for private channels.
7411 nodes[1].node.create_channel(nodes[2].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None).unwrap();
7412 let open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[2].node.get_our_node_id());
7413 nodes[2].node.handle_open_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel);
7414 let accept_channel = get_event_msg!(nodes[2], MessageSendEvent::SendAcceptChannel, nodes[1].node.get_our_node_id());
7415 nodes[1].node.handle_accept_channel(&nodes[2].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7417 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[1], 1_000_000, 42);
7418 nodes[1].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
7419 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()));
7420 check_added_monitors!(nodes[2], 1);
7422 nodes[1].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[1].node.get_our_node_id()));
7423 check_added_monitors!(nodes[1], 1);
7425 let conf_height = core::cmp::max(nodes[1].best_block_info().1 + 1, nodes[2].best_block_info().1 + 1);
7426 confirm_transaction_at(&nodes[1], &tx, conf_height);
7427 connect_blocks(&nodes[1], CHAN_CONFIRM_DEPTH - 1);
7428 confirm_transaction_at(&nodes[2], &tx, conf_height);
7429 connect_blocks(&nodes[2], CHAN_CONFIRM_DEPTH - 1);
7430 let as_funding_locked = get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[2].node.get_our_node_id());
7431 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()));
7432 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7433 nodes[2].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &as_funding_locked);
7434 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7436 assert!(nodes[0].node.list_usable_channels()[0].is_public);
7437 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
7438 assert!(!nodes[2].node.list_usable_channels()[0].is_public);
7440 // We should always be able to forward through nodes[1] as long as its out through a public
7442 send_payment(&nodes[2], &[&nodes[1], &nodes[0]], 10_000);
7444 // ... however, if we send to nodes[2], we will have to pass the private channel from nodes[1]
7445 // to nodes[2], which should be rejected:
7446 let route_hint = RouteHint(vec![RouteHintHop {
7447 src_node_id: nodes[1].node.get_our_node_id(),
7448 short_channel_id: nodes[2].node.list_channels()[0].short_channel_id.unwrap(),
7449 fees: RoutingFees { base_msat: 1000, proportional_millionths: 0 },
7450 cltv_expiry_delta: MIN_CLTV_EXPIRY_DELTA,
7451 htlc_minimum_msat: None,
7452 htlc_maximum_msat: None,
7454 let last_hops = vec![&route_hint];
7455 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);
7457 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7458 check_added_monitors!(nodes[0], 1);
7459 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
7460 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7461 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false, true);
7463 let htlc_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7464 assert!(htlc_fail_updates.update_add_htlcs.is_empty());
7465 assert_eq!(htlc_fail_updates.update_fail_htlcs.len(), 1);
7466 assert!(htlc_fail_updates.update_fail_malformed_htlcs.is_empty());
7467 assert!(htlc_fail_updates.update_fee.is_none());
7469 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_fail_updates.update_fail_htlcs[0]);
7470 commitment_signed_dance!(nodes[0], nodes[1], htlc_fail_updates.commitment_signed, true, true);
7471 expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, nodes[2].node.list_channels()[0].short_channel_id.unwrap(), true);
7473 // Now disconnect nodes[1] from its peers and restart with accept_forwards_to_priv_channels set
7474 // to true. Sadly there is currently no way to change it at runtime.
7476 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7477 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7479 let nodes_1_serialized = nodes[1].node.encode();
7480 let mut monitor_a_serialized = test_utils::TestVecWriter(Vec::new());
7481 let mut monitor_b_serialized = test_utils::TestVecWriter(Vec::new());
7483 let mons = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
7484 let mut mon_iter = mons.iter();
7485 mon_iter.next().unwrap().1.write(&mut monitor_a_serialized).unwrap();
7486 mon_iter.next().unwrap().1.write(&mut monitor_b_serialized).unwrap();
7489 persister = test_utils::TestPersister::new();
7490 let keys_manager = &chanmon_cfgs[1].keys_manager;
7491 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);
7492 nodes[1].chain_monitor = &new_chain_monitor;
7494 let mut monitor_a_read = &monitor_a_serialized.0[..];
7495 let mut monitor_b_read = &monitor_b_serialized.0[..];
7496 let (_, mut monitor_a) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_a_read, keys_manager).unwrap();
7497 let (_, mut monitor_b) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut monitor_b_read, keys_manager).unwrap();
7498 assert!(monitor_a_read.is_empty());
7499 assert!(monitor_b_read.is_empty());
7501 no_announce_cfg.accept_forwards_to_priv_channels = true;
7503 let mut nodes_1_read = &nodes_1_serialized[..];
7504 let (_, nodes_1_deserialized_tmp) = {
7505 let mut channel_monitors = HashMap::new();
7506 channel_monitors.insert(monitor_a.get_funding_txo().0, &mut monitor_a);
7507 channel_monitors.insert(monitor_b.get_funding_txo().0, &mut monitor_b);
7508 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
7509 default_config: no_announce_cfg,
7511 fee_estimator: node_cfgs[1].fee_estimator,
7512 chain_monitor: nodes[1].chain_monitor,
7513 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
7514 logger: nodes[1].logger,
7518 assert!(nodes_1_read.is_empty());
7519 nodes_1_deserialized = nodes_1_deserialized_tmp;
7521 assert!(nodes[1].chain_monitor.watch_channel(monitor_a.get_funding_txo().0, monitor_a).is_ok());
7522 assert!(nodes[1].chain_monitor.watch_channel(monitor_b.get_funding_txo().0, monitor_b).is_ok());
7523 check_added_monitors!(nodes[1], 2);
7524 nodes[1].node = &nodes_1_deserialized;
7526 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7527 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7528 let as_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7529 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
7530 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &as_reestablish);
7531 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7532 get_event_msg!(nodes[0], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7533 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[0].node.get_our_node_id());
7535 nodes[1].node.peer_connected(&nodes[2].node.get_our_node_id(), &msgs::Init { features: InitFeatures::known() });
7536 nodes[2].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7537 let bs_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[2].node.get_our_node_id());
7538 let cs_reestablish = get_event_msg!(nodes[2], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
7539 nodes[2].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bs_reestablish);
7540 nodes[1].node.handle_channel_reestablish(&nodes[2].node.get_our_node_id(), &cs_reestablish);
7541 get_event_msg!(nodes[1], MessageSendEvent::SendChannelUpdate, nodes[2].node.get_our_node_id());
7542 get_event_msg!(nodes[2], MessageSendEvent::SendChannelUpdate, nodes[1].node.get_our_node_id());
7544 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7545 check_added_monitors!(nodes[0], 1);
7546 pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], 10_000, our_payment_hash, our_payment_secret);
7547 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], our_payment_preimage);
7551 fn test_bump_penalty_txn_on_revoked_commitment() {
7552 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7553 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7555 let chanmon_cfgs = create_chanmon_cfgs(2);
7556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7558 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7560 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7562 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7563 let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], vec![], 3000000, 30);
7564 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7566 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7567 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7568 assert_eq!(revoked_txn[0].output.len(), 4);
7569 assert_eq!(revoked_txn[0].input.len(), 1);
7570 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7571 let revoked_txid = revoked_txn[0].txid();
7573 let mut penalty_sum = 0;
7574 for outp in revoked_txn[0].output.iter() {
7575 if outp.script_pubkey.is_v0_p2wsh() {
7576 penalty_sum += outp.value;
7580 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7581 let header_114 = connect_blocks(&nodes[1], 14);
7583 // Actually revoke tx by claiming a HTLC
7584 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7585 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7586 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7587 check_added_monitors!(nodes[1], 1);
7589 // One or more justice tx should have been broadcast, check it
7593 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7594 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7595 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7596 assert_eq!(node_txn[0].output.len(), 1);
7597 check_spends!(node_txn[0], revoked_txn[0]);
7598 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7599 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7600 penalty_1 = node_txn[0].txid();
7604 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7605 connect_blocks(&nodes[1], 15);
7606 let mut penalty_2 = penalty_1;
7607 let mut feerate_2 = 0;
7609 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7610 assert_eq!(node_txn.len(), 1);
7611 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7612 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7613 assert_eq!(node_txn[0].output.len(), 1);
7614 check_spends!(node_txn[0], revoked_txn[0]);
7615 penalty_2 = node_txn[0].txid();
7616 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7617 assert_ne!(penalty_2, penalty_1);
7618 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7619 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7620 // Verify 25% bump heuristic
7621 assert!(feerate_2 * 100 >= feerate_1 * 125);
7625 assert_ne!(feerate_2, 0);
7627 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7628 connect_blocks(&nodes[1], 1);
7630 let mut feerate_3 = 0;
7632 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7633 assert_eq!(node_txn.len(), 1);
7634 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7635 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7636 assert_eq!(node_txn[0].output.len(), 1);
7637 check_spends!(node_txn[0], revoked_txn[0]);
7638 penalty_3 = node_txn[0].txid();
7639 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7640 assert_ne!(penalty_3, penalty_2);
7641 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7642 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7643 // Verify 25% bump heuristic
7644 assert!(feerate_3 * 100 >= feerate_2 * 125);
7648 assert_ne!(feerate_3, 0);
7650 nodes[1].node.get_and_clear_pending_events();
7651 nodes[1].node.get_and_clear_pending_msg_events();
7655 fn test_bump_penalty_txn_on_revoked_htlcs() {
7656 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7657 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7659 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7660 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7661 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7662 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7663 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7665 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7666 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7667 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph,
7668 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7669 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7670 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph,
7671 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
7672 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7674 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7675 assert_eq!(revoked_local_txn[0].input.len(), 1);
7676 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7678 // Revoke local commitment tx
7679 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7681 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7682 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7683 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7684 check_closed_broadcast!(nodes[1], true);
7685 check_added_monitors!(nodes[1], 1);
7686 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
7687 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7689 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7690 assert_eq!(revoked_htlc_txn.len(), 3);
7691 check_spends!(revoked_htlc_txn[1], chan.3);
7693 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7694 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7695 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7697 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
7698 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7699 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
7700 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
7702 // Broadcast set of revoked txn on A
7703 let hash_128 = connect_blocks(&nodes[0], 40);
7704 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7705 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7706 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7707 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
7708 let events = nodes[0].node.get_and_clear_pending_events();
7709 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7711 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7712 _ => panic!("Unexpected event"),
7718 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7719 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7720 // Verify claim tx are spending revoked HTLC txn
7722 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7723 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7724 // which are included in the same block (they are broadcasted because we scan the
7725 // transactions linearly and generate claims as we go, they likely should be removed in the
7727 assert_eq!(node_txn[0].input.len(), 1);
7728 check_spends!(node_txn[0], revoked_local_txn[0]);
7729 assert_eq!(node_txn[1].input.len(), 1);
7730 check_spends!(node_txn[1], revoked_local_txn[0]);
7731 assert_eq!(node_txn[2].input.len(), 1);
7732 check_spends!(node_txn[2], revoked_local_txn[0]);
7734 // Each of the three justice transactions claim a separate (single) output of the three
7735 // available, which we check here:
7736 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7737 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7738 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7740 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7741 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7743 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7744 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7745 // a remote commitment tx has already been confirmed).
7746 check_spends!(node_txn[3], chan.3);
7748 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7749 // output, checked above).
7750 assert_eq!(node_txn[4].input.len(), 2);
7751 assert_eq!(node_txn[4].output.len(), 1);
7752 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7754 first = node_txn[4].txid();
7755 // Store both feerates for later comparison
7756 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
7757 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7758 penalty_txn = vec![node_txn[2].clone()];
7762 // Connect one more block to see if bumped penalty are issued for HTLC txn
7763 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7764 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7765 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7766 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7768 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7769 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7771 check_spends!(node_txn[0], revoked_local_txn[0]);
7772 check_spends!(node_txn[1], revoked_local_txn[0]);
7773 // Note that these are both bogus - they spend outputs already claimed in block 129:
7774 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7775 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7777 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
7778 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7784 // Few more blocks to confirm penalty txn
7785 connect_blocks(&nodes[0], 4);
7786 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7787 let header_144 = connect_blocks(&nodes[0], 9);
7789 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7790 assert_eq!(node_txn.len(), 1);
7792 assert_eq!(node_txn[0].input.len(), 2);
7793 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
7794 // Verify bumped tx is different and 25% bump heuristic
7795 assert_ne!(first, node_txn[0].txid());
7796 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
7797 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7798 assert!(feerate_2 * 100 > feerate_1 * 125);
7799 let txn = vec![node_txn[0].clone()];
7803 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7804 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7805 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7806 connect_blocks(&nodes[0], 20);
7808 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7809 // We verify than no new transaction has been broadcast because previously
7810 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7811 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7812 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7813 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7814 // up bumped justice generation.
7815 assert_eq!(node_txn.len(), 0);
7818 check_closed_broadcast!(nodes[0], true);
7819 check_added_monitors!(nodes[0], 1);
7823 fn test_bump_penalty_txn_on_remote_commitment() {
7824 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7825 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7828 // Provide preimage for one
7829 // Check aggregation
7831 let chanmon_cfgs = create_chanmon_cfgs(2);
7832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7834 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7836 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7837 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7838 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7840 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7841 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7842 assert_eq!(remote_txn[0].output.len(), 4);
7843 assert_eq!(remote_txn[0].input.len(), 1);
7844 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7846 // Claim a HTLC without revocation (provide B monitor with preimage)
7847 nodes[1].node.claim_funds(payment_preimage);
7848 mine_transaction(&nodes[1], &remote_txn[0]);
7849 check_added_monitors!(nodes[1], 2);
7850 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7852 // One or more claim tx should have been broadcast, check it
7856 let feerate_timeout;
7857 let feerate_preimage;
7859 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7860 // 9 transactions including:
7861 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
7862 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
7863 // 2 * HTLC-Success (one RBF bump we'll check later)
7865 assert_eq!(node_txn.len(), 8);
7866 assert_eq!(node_txn[0].input.len(), 1);
7867 assert_eq!(node_txn[6].input.len(), 1);
7868 check_spends!(node_txn[0], remote_txn[0]);
7869 check_spends!(node_txn[6], remote_txn[0]);
7870 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
7871 preimage_bump = node_txn[3].clone();
7873 check_spends!(node_txn[1], chan.3);
7874 check_spends!(node_txn[2], node_txn[1]);
7875 assert_eq!(node_txn[1], node_txn[4]);
7876 assert_eq!(node_txn[2], node_txn[5]);
7878 timeout = node_txn[6].txid();
7879 let index = node_txn[6].input[0].previous_output.vout;
7880 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
7881 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
7883 preimage = node_txn[0].txid();
7884 let index = node_txn[0].input[0].previous_output.vout;
7885 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7886 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7890 assert_ne!(feerate_timeout, 0);
7891 assert_ne!(feerate_preimage, 0);
7893 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7894 connect_blocks(&nodes[1], 15);
7896 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7897 assert_eq!(node_txn.len(), 1);
7898 assert_eq!(node_txn[0].input.len(), 1);
7899 assert_eq!(preimage_bump.input.len(), 1);
7900 check_spends!(node_txn[0], remote_txn[0]);
7901 check_spends!(preimage_bump, remote_txn[0]);
7903 let index = preimage_bump.input[0].previous_output.vout;
7904 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7905 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
7906 assert!(new_feerate * 100 > feerate_timeout * 125);
7907 assert_ne!(timeout, preimage_bump.txid());
7909 let index = node_txn[0].input[0].previous_output.vout;
7910 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7911 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7912 assert!(new_feerate * 100 > feerate_preimage * 125);
7913 assert_ne!(preimage, node_txn[0].txid());
7918 nodes[1].node.get_and_clear_pending_events();
7919 nodes[1].node.get_and_clear_pending_msg_events();
7923 fn test_counterparty_raa_skip_no_crash() {
7924 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7925 // commitment transaction, we would have happily carried on and provided them the next
7926 // commitment transaction based on one RAA forward. This would probably eventually have led to
7927 // channel closure, but it would not have resulted in funds loss. Still, our
7928 // EnforcingSigner would have panicked as it doesn't like jumps into the future. Here, we
7929 // check simply that the channel is closed in response to such an RAA, but don't check whether
7930 // we decide to punish our counterparty for revoking their funds (as we don't currently
7932 let chanmon_cfgs = create_chanmon_cfgs(2);
7933 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7934 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7935 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7936 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7938 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7939 let keys = guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7941 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7943 // Make signer believe we got a counterparty signature, so that it allows the revocation
7944 keys.get_enforcement_state().last_holder_commitment -= 1;
7945 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7947 // Must revoke without gaps
7948 keys.get_enforcement_state().last_holder_commitment -= 1;
7949 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7951 keys.get_enforcement_state().last_holder_commitment -= 1;
7952 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7953 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7955 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7956 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7957 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7958 check_added_monitors!(nodes[1], 1);
7959 check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() });
7963 fn test_bump_txn_sanitize_tracking_maps() {
7964 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7965 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7967 let chanmon_cfgs = create_chanmon_cfgs(2);
7968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7970 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7972 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7973 // Lock HTLC in both directions
7974 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7975 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7977 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7978 assert_eq!(revoked_local_txn[0].input.len(), 1);
7979 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7981 // Revoke local commitment tx
7982 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7984 // Broadcast set of revoked txn on A
7985 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7986 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7987 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7989 mine_transaction(&nodes[0], &revoked_local_txn[0]);
7990 check_closed_broadcast!(nodes[0], true);
7991 check_added_monitors!(nodes[0], 1);
7992 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
7994 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7995 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7996 check_spends!(node_txn[0], revoked_local_txn[0]);
7997 check_spends!(node_txn[1], revoked_local_txn[0]);
7998 check_spends!(node_txn[2], revoked_local_txn[0]);
7999 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8003 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8004 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8005 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8007 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8008 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8009 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8010 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8016 fn test_override_channel_config() {
8017 let chanmon_cfgs = create_chanmon_cfgs(2);
8018 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8019 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8020 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8022 // Node0 initiates a channel to node1 using the override config.
8023 let mut override_config = UserConfig::default();
8024 override_config.own_channel_config.our_to_self_delay = 200;
8026 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8028 // Assert the channel created by node0 is using the override config.
8029 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8030 assert_eq!(res.channel_flags, 0);
8031 assert_eq!(res.to_self_delay, 200);
8035 fn test_override_0msat_htlc_minimum() {
8036 let mut zero_config = UserConfig::default();
8037 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8038 let chanmon_cfgs = create_chanmon_cfgs(2);
8039 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8040 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8041 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8043 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8044 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8045 assert_eq!(res.htlc_minimum_msat, 1);
8047 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8048 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8049 assert_eq!(res.htlc_minimum_msat, 1);
8053 fn test_simple_mpp() {
8054 // Simple test of sending a multi-path payment.
8055 let chanmon_cfgs = create_chanmon_cfgs(4);
8056 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8057 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8058 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8060 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8061 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8062 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8063 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8065 let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8066 let path = route.paths[0].clone();
8067 route.paths.push(path);
8068 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8069 route.paths[0][0].short_channel_id = chan_1_id;
8070 route.paths[0][1].short_channel_id = chan_3_id;
8071 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8072 route.paths[1][0].short_channel_id = chan_2_id;
8073 route.paths[1][1].short_channel_id = chan_4_id;
8074 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8075 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8079 fn test_preimage_storage() {
8080 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8081 let chanmon_cfgs = create_chanmon_cfgs(2);
8082 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8083 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8084 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8086 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8089 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8090 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8091 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8092 check_added_monitors!(nodes[0], 1);
8093 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8094 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8095 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8096 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8098 // Note that after leaving the above scope we have no knowledge of any arguments or return
8099 // values from previous calls.
8100 expect_pending_htlcs_forwardable!(nodes[1]);
8101 let events = nodes[1].node.get_and_clear_pending_events();
8102 assert_eq!(events.len(), 1);
8104 Event::PaymentReceived { ref purpose, .. } => {
8106 PaymentPurpose::InvoicePayment { payment_preimage, user_payment_id, .. } => {
8107 assert_eq!(*user_payment_id, 42);
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, 0);
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, 0) {
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, 0) {
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 with a different user_payment_id (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, 42).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, user_payment_id }, .. } => {
8174 assert!(payment_preimage.is_none());
8175 assert_eq!(user_payment_id, 42);
8176 assert_eq!(payment_secret, our_payment_secret);
8177 // We don't actually have the payment preimage with which to claim this payment!
8179 _ => panic!("Unexpected event"),
8184 fn test_bad_secret_hash() {
8185 // Simple test of unregistered payment hash/invalid payment secret handling
8186 let chanmon_cfgs = create_chanmon_cfgs(2);
8187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8189 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8191 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8193 let random_payment_hash = PaymentHash([42; 32]);
8194 let random_payment_secret = PaymentSecret([43; 32]);
8195 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8196 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8198 // All the below cases should end up being handled exactly identically, so we macro the
8199 // resulting events.
8200 macro_rules! handle_unknown_invalid_payment_data {
8202 check_added_monitors!(nodes[0], 1);
8203 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8204 let payment_event = SendEvent::from_event(events.pop().unwrap());
8205 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8206 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8208 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8209 // again to process the pending backwards-failure of the HTLC
8210 expect_pending_htlcs_forwardable!(nodes[1]);
8211 expect_pending_htlcs_forwardable!(nodes[1]);
8212 check_added_monitors!(nodes[1], 1);
8214 // We should fail the payment back
8215 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8216 match events.pop().unwrap() {
8217 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8218 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8219 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8221 _ => panic!("Unexpected event"),
8226 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8227 // Error data is the HTLC value (100,000) and current block height
8228 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8230 // Send a payment with the right payment hash but the wrong payment secret
8231 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8232 handle_unknown_invalid_payment_data!();
8233 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8235 // Send a payment with a random payment hash, but the right payment secret
8236 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8237 handle_unknown_invalid_payment_data!();
8238 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8240 // Send a payment with a random payment hash and random payment secret
8241 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8242 handle_unknown_invalid_payment_data!();
8243 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8247 fn test_update_err_monitor_lockdown() {
8248 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8249 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8250 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8252 // This scenario may happen in a watchtower setup, where watchtower process a block height
8253 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8254 // commitment at same time.
8256 let chanmon_cfgs = create_chanmon_cfgs(2);
8257 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8258 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8259 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8261 // Create some initial channel
8262 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8263 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8265 // Rebalance the network to generate htlc in the two directions
8266 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8268 // Route a HTLC from node 0 to node 1 (but don't settle)
8269 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8271 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8272 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8273 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8274 let persister = test_utils::TestPersister::new();
8276 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8277 let monitor = monitors.get(&outpoint).unwrap();
8278 let mut w = test_utils::TestVecWriter(Vec::new());
8279 monitor.write(&mut w).unwrap();
8280 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8281 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8282 assert!(new_monitor == *monitor);
8283 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);
8284 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8287 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8288 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8289 // transaction lock time requirements here.
8290 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8291 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8293 // Try to update ChannelMonitor
8294 assert!(nodes[1].node.claim_funds(preimage));
8295 check_added_monitors!(nodes[1], 1);
8296 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8297 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8298 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8299 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8300 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8301 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8302 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8303 } else { assert!(false); }
8304 } else { assert!(false); };
8305 // Our local monitor is in-sync and hasn't processed yet timeout
8306 check_added_monitors!(nodes[0], 1);
8307 let events = nodes[0].node.get_and_clear_pending_events();
8308 assert_eq!(events.len(), 1);
8312 fn test_concurrent_monitor_claim() {
8313 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8314 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8315 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8316 // state N+1 confirms. Alice claims output from state N+1.
8318 let chanmon_cfgs = create_chanmon_cfgs(2);
8319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8323 // Create some initial channel
8324 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8325 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8327 // Rebalance the network to generate htlc in the two directions
8328 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8330 // Route a HTLC from node 0 to node 1 (but don't settle)
8331 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8333 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8334 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8335 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8336 let persister = test_utils::TestPersister::new();
8337 let watchtower_alice = {
8338 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8339 let monitor = monitors.get(&outpoint).unwrap();
8340 let mut w = test_utils::TestVecWriter(Vec::new());
8341 monitor.write(&mut w).unwrap();
8342 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8343 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8344 assert!(new_monitor == *monitor);
8345 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);
8346 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8349 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8350 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8351 // transaction lock time requirements here.
8352 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8353 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8355 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8357 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8358 assert_eq!(txn.len(), 2);
8362 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8363 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8364 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8365 let persister = test_utils::TestPersister::new();
8366 let watchtower_bob = {
8367 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8368 let monitor = monitors.get(&outpoint).unwrap();
8369 let mut w = test_utils::TestVecWriter(Vec::new());
8370 monitor.write(&mut w).unwrap();
8371 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8372 &mut io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8373 assert!(new_monitor == *monitor);
8374 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);
8375 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8378 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8379 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8381 // Route another payment to generate another update with still previous HTLC pending
8382 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8384 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8386 check_added_monitors!(nodes[1], 1);
8388 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8389 assert_eq!(updates.update_add_htlcs.len(), 1);
8390 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8391 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8392 if let Ok((_, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8393 // Watchtower Alice should already have seen the block and reject the update
8394 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8395 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8396 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8397 } else { assert!(false); }
8398 } else { assert!(false); };
8399 // Our local monitor is in-sync and hasn't processed yet timeout
8400 check_added_monitors!(nodes[0], 1);
8402 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8404 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8406 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8409 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8410 assert_eq!(txn.len(), 2);
8411 bob_state_y = txn[0].clone();
8415 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8416 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8417 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);
8419 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8420 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8421 // the onchain detection of the HTLC output
8422 assert_eq!(htlc_txn.len(), 2);
8423 check_spends!(htlc_txn[0], bob_state_y);
8424 check_spends!(htlc_txn[1], bob_state_y);
8429 fn test_pre_lockin_no_chan_closed_update() {
8430 // Test that if a peer closes a channel in response to a funding_created message we don't
8431 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8434 // Doing so would imply a channel monitor update before the initial channel monitor
8435 // registration, violating our API guarantees.
8437 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8438 // then opening a second channel with the same funding output as the first (which is not
8439 // rejected because the first channel does not exist in the ChannelManager) and closing it
8440 // before receiving funding_signed.
8441 let chanmon_cfgs = create_chanmon_cfgs(2);
8442 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8443 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8444 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8446 // Create an initial channel
8447 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8448 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8449 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8450 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8451 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8453 // Move the first channel through the funding flow...
8454 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8456 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8457 check_added_monitors!(nodes[0], 0);
8459 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8460 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8461 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8462 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8463 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "Hi".to_string() }, true);
8467 fn test_htlc_no_detection() {
8468 // This test is a mutation to underscore the detection logic bug we had
8469 // before #653. HTLC value routed is above the remaining balance, thus
8470 // inverting HTLC and `to_remote` output. HTLC will come second and
8471 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8472 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8473 // outputs order detection for correct spending children filtring.
8475 let chanmon_cfgs = create_chanmon_cfgs(2);
8476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8478 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8480 // Create some initial channels
8481 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8483 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8484 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8485 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8486 assert_eq!(local_txn[0].input.len(), 1);
8487 assert_eq!(local_txn[0].output.len(), 3);
8488 check_spends!(local_txn[0], chan_1.3);
8490 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8491 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8492 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8493 // We deliberately connect the local tx twice as this should provoke a failure calling
8494 // this test before #653 fix.
8495 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);
8496 check_closed_broadcast!(nodes[0], true);
8497 check_added_monitors!(nodes[0], 1);
8498 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed);
8499 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8501 let htlc_timeout = {
8502 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8503 assert_eq!(node_txn[1].input.len(), 1);
8504 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8505 check_spends!(node_txn[1], local_txn[0]);
8509 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8510 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8511 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8512 expect_payment_failed!(nodes[0], our_payment_hash, true);
8515 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8516 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8517 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8518 // Carol, Alice would be the upstream node, and Carol the downstream.)
8520 // Steps of the test:
8521 // 1) Alice sends a HTLC to Carol through Bob.
8522 // 2) Carol doesn't settle the HTLC.
8523 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8524 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8525 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8526 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8527 // 5) Carol release the preimage to Bob off-chain.
8528 // 6) Bob claims the offered output on the broadcasted commitment.
8529 let chanmon_cfgs = create_chanmon_cfgs(3);
8530 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8531 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8532 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8534 // Create some initial channels
8535 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8536 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8538 // Steps (1) and (2):
8539 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8540 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8542 // Check that Alice's commitment transaction now contains an output for this HTLC.
8543 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8544 check_spends!(alice_txn[0], chan_ab.3);
8545 assert_eq!(alice_txn[0].output.len(), 2);
8546 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8547 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8548 assert_eq!(alice_txn.len(), 2);
8550 // Steps (3) and (4):
8551 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8552 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8553 let mut force_closing_node = 0; // Alice force-closes
8554 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8555 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8556 check_closed_broadcast!(nodes[force_closing_node], true);
8557 check_added_monitors!(nodes[force_closing_node], 1);
8558 check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed);
8559 if go_onchain_before_fulfill {
8560 let txn_to_broadcast = match broadcast_alice {
8561 true => alice_txn.clone(),
8562 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8564 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8565 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8566 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8567 if broadcast_alice {
8568 check_closed_broadcast!(nodes[1], true);
8569 check_added_monitors!(nodes[1], 1);
8570 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8572 assert_eq!(bob_txn.len(), 1);
8573 check_spends!(bob_txn[0], chan_ab.3);
8577 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8578 // process of removing the HTLC from their commitment transactions.
8579 assert!(nodes[2].node.claim_funds(payment_preimage));
8580 check_added_monitors!(nodes[2], 1);
8581 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8582 assert!(carol_updates.update_add_htlcs.is_empty());
8583 assert!(carol_updates.update_fail_htlcs.is_empty());
8584 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8585 assert!(carol_updates.update_fee.is_none());
8586 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8588 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8589 expect_payment_forwarded!(nodes[1], if go_onchain_before_fulfill || force_closing_node == 1 { None } else { Some(1000) }, false);
8590 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8591 if !go_onchain_before_fulfill && broadcast_alice {
8592 let events = nodes[1].node.get_and_clear_pending_msg_events();
8593 assert_eq!(events.len(), 1);
8595 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8596 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8598 _ => panic!("Unexpected event"),
8601 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8602 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8603 // Carol<->Bob's updated commitment transaction info.
8604 check_added_monitors!(nodes[1], 2);
8606 let events = nodes[1].node.get_and_clear_pending_msg_events();
8607 assert_eq!(events.len(), 2);
8608 let bob_revocation = match events[0] {
8609 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8610 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8613 _ => panic!("Unexpected event"),
8615 let bob_updates = match events[1] {
8616 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8617 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8620 _ => panic!("Unexpected event"),
8623 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8624 check_added_monitors!(nodes[2], 1);
8625 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8626 check_added_monitors!(nodes[2], 1);
8628 let events = nodes[2].node.get_and_clear_pending_msg_events();
8629 assert_eq!(events.len(), 1);
8630 let carol_revocation = match events[0] {
8631 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8632 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8635 _ => panic!("Unexpected event"),
8637 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8638 check_added_monitors!(nodes[1], 1);
8640 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8641 // here's where we put said channel's commitment tx on-chain.
8642 let mut txn_to_broadcast = alice_txn.clone();
8643 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8644 if !go_onchain_before_fulfill {
8645 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8646 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8647 // If Bob was the one to force-close, he will have already passed these checks earlier.
8648 if broadcast_alice {
8649 check_closed_broadcast!(nodes[1], true);
8650 check_added_monitors!(nodes[1], 1);
8651 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8653 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8654 if broadcast_alice {
8655 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8656 // new block being connected. The ChannelManager being notified triggers a monitor update,
8657 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8658 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8660 assert_eq!(bob_txn.len(), 3);
8661 check_spends!(bob_txn[1], chan_ab.3);
8663 assert_eq!(bob_txn.len(), 2);
8664 check_spends!(bob_txn[0], chan_ab.3);
8669 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8670 // broadcasted commitment transaction.
8672 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8673 if go_onchain_before_fulfill {
8674 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8675 assert_eq!(bob_txn.len(), 2);
8677 let script_weight = match broadcast_alice {
8678 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8679 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8681 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8682 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8683 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8684 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8685 if broadcast_alice && !go_onchain_before_fulfill {
8686 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8687 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8689 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8690 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8696 fn test_onchain_htlc_settlement_after_close() {
8697 do_test_onchain_htlc_settlement_after_close(true, true);
8698 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8699 do_test_onchain_htlc_settlement_after_close(true, false);
8700 do_test_onchain_htlc_settlement_after_close(false, false);
8704 fn test_duplicate_chan_id() {
8705 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8706 // already open we reject it and keep the old channel.
8708 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8709 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8710 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8711 // updating logic for the existing channel.
8712 let chanmon_cfgs = create_chanmon_cfgs(2);
8713 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8714 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8715 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8717 // Create an initial channel
8718 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8719 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8720 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8721 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()));
8723 // Try to create a second channel with the same temporary_channel_id as the first and check
8724 // that it is rejected.
8725 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8727 let events = nodes[1].node.get_and_clear_pending_msg_events();
8728 assert_eq!(events.len(), 1);
8730 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8731 // Technically, at this point, nodes[1] would be justified in thinking both the
8732 // first (valid) and second (invalid) channels are closed, given they both have
8733 // the same non-temporary channel_id. However, currently we do not, so we just
8734 // move forward with it.
8735 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8736 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8738 _ => panic!("Unexpected event"),
8742 // Move the first channel through the funding flow...
8743 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8745 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8746 check_added_monitors!(nodes[0], 0);
8748 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8749 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8751 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8752 assert_eq!(added_monitors.len(), 1);
8753 assert_eq!(added_monitors[0].0, funding_output);
8754 added_monitors.clear();
8756 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8758 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8759 let channel_id = funding_outpoint.to_channel_id();
8761 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8764 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8765 // Technically this is allowed by the spec, but we don't support it and there's little reason
8766 // to. Still, it shouldn't cause any other issues.
8767 open_chan_msg.temporary_channel_id = channel_id;
8768 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8770 let events = nodes[1].node.get_and_clear_pending_msg_events();
8771 assert_eq!(events.len(), 1);
8773 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8774 // Technically, at this point, nodes[1] would be justified in thinking both
8775 // channels are closed, but currently we do not, so we just move forward with it.
8776 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8777 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8779 _ => panic!("Unexpected event"),
8783 // Now try to create a second channel which has a duplicate funding output.
8784 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8785 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8786 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8787 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()));
8788 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8790 let funding_created = {
8791 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8792 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8793 let logger = test_utils::TestLogger::new();
8794 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8796 check_added_monitors!(nodes[0], 0);
8797 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8798 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8799 // still needs to be cleared here.
8800 check_added_monitors!(nodes[1], 1);
8802 // ...still, nodes[1] will reject the duplicate channel.
8804 let events = nodes[1].node.get_and_clear_pending_msg_events();
8805 assert_eq!(events.len(), 1);
8807 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8808 // Technically, at this point, nodes[1] would be justified in thinking both
8809 // channels are closed, but currently we do not, so we just move forward with it.
8810 assert_eq!(msg.channel_id, channel_id);
8811 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8813 _ => panic!("Unexpected event"),
8817 // finally, finish creating the original channel and send a payment over it to make sure
8818 // everything is functional.
8819 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8821 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8822 assert_eq!(added_monitors.len(), 1);
8823 assert_eq!(added_monitors[0].0, funding_output);
8824 added_monitors.clear();
8827 let events_4 = nodes[0].node.get_and_clear_pending_events();
8828 assert_eq!(events_4.len(), 0);
8829 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8830 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8832 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8833 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8834 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8835 send_payment(&nodes[0], &[&nodes[1]], 8000000);
8839 fn test_error_chans_closed() {
8840 // Test that we properly handle error messages, closing appropriate channels.
8842 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8843 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8844 // we can test various edge cases around it to ensure we don't regress.
8845 let chanmon_cfgs = create_chanmon_cfgs(3);
8846 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8847 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8848 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8850 // Create some initial channels
8851 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8852 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8853 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8855 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8856 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8857 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8859 // Closing a channel from a different peer has no effect
8860 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8861 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8863 // Closing one channel doesn't impact others
8864 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8865 check_added_monitors!(nodes[0], 1);
8866 check_closed_broadcast!(nodes[0], false);
8867 check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8868 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8869 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8870 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);
8871 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);
8873 // A null channel ID should close all channels
8874 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8875 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8876 check_added_monitors!(nodes[0], 2);
8877 check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: "ERR".to_string() });
8878 let events = nodes[0].node.get_and_clear_pending_msg_events();
8879 assert_eq!(events.len(), 2);
8881 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8882 assert_eq!(msg.contents.flags & 2, 2);
8884 _ => panic!("Unexpected event"),
8887 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8888 assert_eq!(msg.contents.flags & 2, 2);
8890 _ => panic!("Unexpected event"),
8892 // Note that at this point users of a standard PeerHandler will end up calling
8893 // peer_disconnected with no_connection_possible set to false, duplicating the
8894 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8895 // users with their own peer handling logic. We duplicate the call here, however.
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);
8899 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8900 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8901 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8905 fn test_invalid_funding_tx() {
8906 // Test that we properly handle invalid funding transactions sent to us from a peer.
8908 // Previously, all other major lightning implementations had failed to properly sanitize
8909 // funding transactions from their counterparties, leading to a multi-implementation critical
8910 // security vulnerability (though we always sanitized properly, we've previously had
8911 // un-released crashes in the sanitization process).
8912 let chanmon_cfgs = create_chanmon_cfgs(2);
8913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8917 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
8918 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()));
8919 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()));
8921 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
8922 for output in tx.output.iter_mut() {
8923 // Make the confirmed funding transaction have a bogus script_pubkey
8924 output.script_pubkey = bitcoin::Script::new();
8927 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
8928 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()));
8929 check_added_monitors!(nodes[1], 1);
8931 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()));
8932 check_added_monitors!(nodes[0], 1);
8934 let events_1 = nodes[0].node.get_and_clear_pending_events();
8935 assert_eq!(events_1.len(), 0);
8937 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8938 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
8939 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
8941 confirm_transaction_at(&nodes[1], &tx, 1);
8942 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed);
8943 check_added_monitors!(nodes[1], 1);
8944 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
8945 assert_eq!(events_2.len(), 1);
8946 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
8947 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8948 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
8949 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
8950 } else { panic!(); }
8951 } else { panic!(); }
8952 assert_eq!(nodes[1].node.list_channels().len(), 0);
8955 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
8956 // In the first version of the chain::Confirm interface, after a refactor was made to not
8957 // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
8958 // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
8959 // `best_block_updated` is at height N, and a transaction output which we wish to spend at
8960 // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
8961 // spending transaction until height N+1 (or greater). This was due to the way
8962 // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
8963 // spending transaction at the height the input transaction was confirmed at, not whether we
8964 // should broadcast a spending transaction at the current height.
8965 // A second, similar, issue involved failing HTLCs backwards - because we only provided the
8966 // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
8967 // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
8968 // until we learned about an additional block.
8970 // As an additional check, if `test_height_before_timelock` is set, we instead test that we
8971 // aren't broadcasting transactions too early (ie not broadcasting them at all).
8972 let chanmon_cfgs = create_chanmon_cfgs(3);
8973 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8974 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8975 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8976 *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
8978 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8979 let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8980 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
8981 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
8982 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
8984 nodes[1].node.force_close_channel(&channel_id).unwrap();
8985 check_closed_broadcast!(nodes[1], true);
8986 check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed);
8987 check_added_monitors!(nodes[1], 1);
8988 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
8989 assert_eq!(node_txn.len(), 1);
8991 let conf_height = nodes[1].best_block_info().1;
8992 if !test_height_before_timelock {
8993 connect_blocks(&nodes[1], 24 * 6);
8995 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
8996 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
8997 if test_height_before_timelock {
8998 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
8999 // generate any events or broadcast any transactions
9000 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9001 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9003 // We should broadcast an HTLC transaction spending our funding transaction first
9004 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9005 assert_eq!(spending_txn.len(), 2);
9006 assert_eq!(spending_txn[0], node_txn[0]);
9007 check_spends!(spending_txn[1], node_txn[0]);
9008 // We should also generate a SpendableOutputs event with the to_self output (as its
9010 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9011 assert_eq!(descriptor_spend_txn.len(), 1);
9013 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9014 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9015 // additional block built on top of the current chain.
9016 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9017 &nodes[1].get_block_header(conf_height + 1), &[(0, &spending_txn[1])], conf_height + 1);
9018 expect_pending_htlcs_forwardable!(nodes[1]);
9019 check_added_monitors!(nodes[1], 1);
9021 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9022 assert!(updates.update_add_htlcs.is_empty());
9023 assert!(updates.update_fulfill_htlcs.is_empty());
9024 assert_eq!(updates.update_fail_htlcs.len(), 1);
9025 assert!(updates.update_fail_malformed_htlcs.is_empty());
9026 assert!(updates.update_fee.is_none());
9027 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9028 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9029 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9034 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9035 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9036 do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9040 fn test_forwardable_regen() {
9041 // Tests that if we reload a ChannelManager while forwards are pending we will regenerate the
9042 // PendingHTLCsForwardable event automatically, ensuring we don't forget to forward/receive
9044 // We test it for both payment receipt and payment forwarding.
9046 let chanmon_cfgs = create_chanmon_cfgs(3);
9047 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9048 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9049 let persister: test_utils::TestPersister;
9050 let new_chain_monitor: test_utils::TestChainMonitor;
9051 let nodes_1_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
9052 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9053 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
9054 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
9056 // First send a payment to nodes[1]
9057 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
9058 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
9059 check_added_monitors!(nodes[0], 1);
9061 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9062 assert_eq!(events.len(), 1);
9063 let payment_event = SendEvent::from_event(events.pop().unwrap());
9064 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9065 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9067 expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9069 // Next send a payment which is forwarded by nodes[1]
9070 let (route_2, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 200_000);
9071 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
9072 check_added_monitors!(nodes[0], 1);
9074 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9075 assert_eq!(events.len(), 1);
9076 let payment_event = SendEvent::from_event(events.pop().unwrap());
9077 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9078 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9080 // There is already a PendingHTLCsForwardable event "pending" so another one will not be
9082 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
9084 // Now restart nodes[1] and make sure it regenerates a single PendingHTLCsForwardable
9085 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9086 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
9088 let nodes_1_serialized = nodes[1].node.encode();
9089 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9090 let mut chan_1_monitor_serialized = test_utils::TestVecWriter(Vec::new());
9092 let monitors = nodes[1].chain_monitor.chain_monitor.monitors.read().unwrap();
9093 let mut monitor_iter = monitors.iter();
9094 monitor_iter.next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
9095 monitor_iter.next().unwrap().1.write(&mut chan_1_monitor_serialized).unwrap();
9098 persister = test_utils::TestPersister::new();
9099 let keys_manager = &chanmon_cfgs[1].keys_manager;
9100 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);
9101 nodes[1].chain_monitor = &new_chain_monitor;
9103 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
9104 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9105 &mut chan_0_monitor_read, keys_manager).unwrap();
9106 assert!(chan_0_monitor_read.is_empty());
9107 let mut chan_1_monitor_read = &chan_1_monitor_serialized.0[..];
9108 let (_, mut chan_1_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
9109 &mut chan_1_monitor_read, keys_manager).unwrap();
9110 assert!(chan_1_monitor_read.is_empty());
9112 let mut nodes_1_read = &nodes_1_serialized[..];
9113 let (_, nodes_1_deserialized_tmp) = {
9114 let mut channel_monitors = HashMap::new();
9115 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
9116 channel_monitors.insert(chan_1_monitor.get_funding_txo().0, &mut chan_1_monitor);
9117 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_1_read, ChannelManagerReadArgs {
9118 default_config: UserConfig::default(),
9120 fee_estimator: node_cfgs[1].fee_estimator,
9121 chain_monitor: nodes[1].chain_monitor,
9122 tx_broadcaster: nodes[1].tx_broadcaster.clone(),
9123 logger: nodes[1].logger,
9127 nodes_1_deserialized = nodes_1_deserialized_tmp;
9128 assert!(nodes_1_read.is_empty());
9130 assert!(nodes[1].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
9131 assert!(nodes[1].chain_monitor.watch_channel(chan_1_monitor.get_funding_txo().0, chan_1_monitor).is_ok());
9132 nodes[1].node = &nodes_1_deserialized;
9133 check_added_monitors!(nodes[1], 2);
9135 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9136 // Note that nodes[1] and nodes[2] resend their funding_locked here since they haven't updated
9137 // the commitment state.
9138 reconnect_nodes(&nodes[1], &nodes[2], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
9140 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9142 expect_pending_htlcs_forwardable!(nodes[1]);
9143 expect_payment_received!(nodes[1], payment_hash, payment_secret, 100_000);
9144 check_added_monitors!(nodes[1], 1);
9146 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9147 assert_eq!(events.len(), 1);
9148 let payment_event = SendEvent::from_event(events.pop().unwrap());
9149 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9150 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false);
9151 expect_pending_htlcs_forwardable!(nodes[2]);
9152 expect_payment_received!(nodes[2], payment_hash_2, payment_secret_2, 200_000);
9154 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
9155 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage_2);
9159 fn test_keysend_payments_to_public_node() {
9160 let chanmon_cfgs = create_chanmon_cfgs(2);
9161 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9162 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9163 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9165 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9166 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9167 let payer_pubkey = nodes[0].node.get_our_node_id();
9168 let payee_pubkey = nodes[1].node.get_our_node_id();
9169 let route = get_keysend_route(
9170 &payer_pubkey, &network_graph, &payee_pubkey, None, &vec![], 10000, 40, nodes[0].logger
9173 let test_preimage = PaymentPreimage([42; 32]);
9174 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9175 check_added_monitors!(nodes[0], 1);
9176 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9177 assert_eq!(events.len(), 1);
9178 let event = events.pop().unwrap();
9179 let path = vec![&nodes[1]];
9180 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9181 claim_payment(&nodes[0], &path, test_preimage);
9185 fn test_keysend_payments_to_private_node() {
9186 let chanmon_cfgs = create_chanmon_cfgs(2);
9187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9189 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9191 let payer_pubkey = nodes[0].node.get_our_node_id();
9192 let payee_pubkey = nodes[1].node.get_our_node_id();
9193 nodes[0].node.peer_connected(&payee_pubkey, &msgs::Init { features: InitFeatures::known() });
9194 nodes[1].node.peer_connected(&payer_pubkey, &msgs::Init { features: InitFeatures::known() });
9196 let _chan = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
9197 let network_graph = &nodes[0].net_graph_msg_handler.network_graph;
9198 let first_hops = nodes[0].node.list_usable_channels();
9199 let route = get_keysend_route(
9200 &payer_pubkey, &network_graph, &payee_pubkey, Some(&first_hops.iter().collect::<Vec<_>>()),
9201 &vec![], 10000, 40, nodes[0].logger
9204 let test_preimage = PaymentPreimage([42; 32]);
9205 let (payment_hash, _) = nodes[0].node.send_spontaneous_payment(&route, Some(test_preimage)).unwrap();
9206 check_added_monitors!(nodes[0], 1);
9207 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9208 assert_eq!(events.len(), 1);
9209 let event = events.pop().unwrap();
9210 let path = vec![&nodes[1]];
9211 pass_along_path(&nodes[0], &path, 10000, payment_hash, None, event, true, Some(test_preimage));
9212 claim_payment(&nodes[0], &path, test_preimage);