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.
17 use chain::channelmonitor;
18 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use chain::transaction::OutPoint;
20 use chain::keysinterface::{KeysInterface, BaseSign};
21 use ln::{PaymentPreimage, PaymentSecret, PaymentHash};
22 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
23 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
24 use ln::channel::{Channel, ChannelError};
25 use ln::{chan_utils, onion_utils};
26 use routing::router::{Route, RouteHop, get_route};
27 use ln::features::{ChannelFeatures, InitFeatures, InvoiceFeatures, NodeFeatures};
29 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
30 use util::enforcing_trait_impls::EnforcingSigner;
31 use util::{byte_utils, test_utils};
32 use util::events::{Event, MessageSendEvent, MessageSendEventsProvider};
33 use util::errors::APIError;
34 use util::ser::{Writeable, ReadableArgs};
35 use util::config::UserConfig;
37 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
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, Message};
49 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
54 use alloc::collections::BTreeSet;
55 use core::default::Default;
56 use std::sync::{Arc, Mutex};
58 use ln::functional_test_utils::*;
59 use ln::chan_utils::CommitmentTransaction;
60 use ln::msgs::OptionalField::Present;
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 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
129 let logger = test_utils::TestLogger::new();
130 let channel_id = chan.2;
133 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
137 // send (1) commitment_signed -.
138 // <- update_add_htlc/commitment_signed
139 // send (2) RAA (awaiting remote revoke) -.
140 // (1) commitment_signed is delivered ->
141 // .- send (3) RAA (awaiting remote revoke)
142 // (2) RAA is delivered ->
143 // .- send (4) commitment_signed
144 // <- (3) RAA is delivered
145 // send (5) commitment_signed -.
146 // <- (4) commitment_signed is delivered
148 // (5) commitment_signed is delivered ->
150 // (6) RAA is delivered ->
152 // First nodes[0] generates an update_fee
153 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
154 check_added_monitors!(nodes[0], 1);
156 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
157 assert_eq!(events_0.len(), 1);
158 let (update_msg, commitment_signed) = match events_0[0] { // (1)
159 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
160 (update_fee.as_ref(), commitment_signed)
162 _ => panic!("Unexpected event"),
165 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
167 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
168 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
169 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
170 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
171 check_added_monitors!(nodes[1], 1);
173 let payment_event = {
174 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
175 assert_eq!(events_1.len(), 1);
176 SendEvent::from_event(events_1.remove(0))
178 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
179 assert_eq!(payment_event.msgs.len(), 1);
181 // ...now when the messages get delivered everyone should be happy
182 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
183 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
184 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
185 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
186 check_added_monitors!(nodes[0], 1);
188 // deliver(1), generate (3):
189 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
190 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
191 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
192 check_added_monitors!(nodes[1], 1);
194 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
195 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
196 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
197 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
198 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
199 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fee.is_none()); // (4)
201 check_added_monitors!(nodes[1], 1);
203 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
204 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
205 assert!(as_update.update_add_htlcs.is_empty()); // (5)
206 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
207 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
208 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fee.is_none()); // (5)
210 check_added_monitors!(nodes[0], 1);
212 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
213 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
214 // only (6) so get_event_msg's assert(len == 1) passes
215 check_added_monitors!(nodes[0], 1);
217 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
218 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
219 check_added_monitors!(nodes[1], 1);
221 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
222 check_added_monitors!(nodes[0], 1);
224 let events_2 = nodes[0].node.get_and_clear_pending_events();
225 assert_eq!(events_2.len(), 1);
227 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
228 _ => panic!("Unexpected event"),
231 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
232 check_added_monitors!(nodes[1], 1);
236 fn test_update_fee_unordered_raa() {
237 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
238 // crash in an earlier version of the update_fee patch)
239 let chanmon_cfgs = create_chanmon_cfgs(2);
240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
242 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
243 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
244 let channel_id = chan.2;
245 let logger = test_utils::TestLogger::new();
248 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
250 // First nodes[0] generates an update_fee
251 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
252 check_added_monitors!(nodes[0], 1);
254 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
255 assert_eq!(events_0.len(), 1);
256 let update_msg = match events_0[0] { // (1)
257 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
260 _ => panic!("Unexpected event"),
263 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
265 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
266 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
267 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
268 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &Some(our_payment_secret)).unwrap();
269 check_added_monitors!(nodes[1], 1);
271 let payment_event = {
272 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
273 assert_eq!(events_1.len(), 1);
274 SendEvent::from_event(events_1.remove(0))
276 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
277 assert_eq!(payment_event.msgs.len(), 1);
279 // ...now when the messages get delivered everyone should be happy
280 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
281 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
282 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
283 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
284 check_added_monitors!(nodes[0], 1);
286 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
287 check_added_monitors!(nodes[1], 1);
289 // We can't continue, sadly, because our (1) now has a bogus signature
293 fn test_multi_flight_update_fee() {
294 let chanmon_cfgs = create_chanmon_cfgs(2);
295 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
296 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
297 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
298 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
299 let channel_id = chan.2;
302 // update_fee/commitment_signed ->
303 // .- send (1) RAA and (2) commitment_signed
304 // update_fee (never committed) ->
306 // We have to manually generate the above update_fee, it is allowed by the protocol but we
307 // don't track which updates correspond to which revoke_and_ack responses so we're in
308 // AwaitingRAA mode and will not generate the update_fee yet.
309 // <- (1) RAA delivered
310 // (3) is generated and send (4) CS -.
311 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
312 // know the per_commitment_point to use for it.
313 // <- (2) commitment_signed delivered
315 // B should send no response here
316 // (4) commitment_signed delivered ->
317 // <- RAA/commitment_signed delivered
320 // First nodes[0] generates an update_fee
321 let initial_feerate = get_feerate!(nodes[0], channel_id);
322 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
323 check_added_monitors!(nodes[0], 1);
325 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
326 assert_eq!(events_0.len(), 1);
327 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
328 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
329 (update_fee.as_ref().unwrap(), commitment_signed)
331 _ => panic!("Unexpected event"),
334 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
335 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
336 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
337 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
338 check_added_monitors!(nodes[1], 1);
340 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
342 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
343 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
344 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
346 // Create the (3) update_fee message that nodes[0] will generate before it does...
347 let mut update_msg_2 = msgs::UpdateFee {
348 channel_id: update_msg_1.channel_id.clone(),
349 feerate_per_kw: (initial_feerate + 30) as u32,
352 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
354 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
356 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
358 // Deliver (1), generating (3) and (4)
359 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
360 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
361 check_added_monitors!(nodes[0], 1);
362 assert!(as_second_update.update_add_htlcs.is_empty());
363 assert!(as_second_update.update_fulfill_htlcs.is_empty());
364 assert!(as_second_update.update_fail_htlcs.is_empty());
365 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
366 // Check that the update_fee newly generated matches what we delivered:
367 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
368 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
370 // Deliver (2) commitment_signed
371 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
372 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
373 check_added_monitors!(nodes[0], 1);
374 // No commitment_signed so get_event_msg's assert(len == 1) passes
376 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
377 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
378 check_added_monitors!(nodes[1], 1);
381 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
382 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
383 check_added_monitors!(nodes[1], 1);
385 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
386 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
387 check_added_monitors!(nodes[0], 1);
389 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
390 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
391 // No commitment_signed so get_event_msg's assert(len == 1) passes
392 check_added_monitors!(nodes[0], 1);
394 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
395 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
396 check_added_monitors!(nodes[1], 1);
399 fn do_test_1_conf_open(connect_style: ConnectStyle) {
400 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
401 // tests that we properly send one in that case.
402 let mut alice_config = UserConfig::default();
403 alice_config.own_channel_config.minimum_depth = 1;
404 alice_config.channel_options.announced_channel = true;
405 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
406 let mut bob_config = UserConfig::default();
407 bob_config.own_channel_config.minimum_depth = 1;
408 bob_config.channel_options.announced_channel = true;
409 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
410 let chanmon_cfgs = create_chanmon_cfgs(2);
411 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
412 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
413 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
414 *nodes[0].connect_style.borrow_mut() = connect_style;
416 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
417 mine_transaction(&nodes[1], &tx);
418 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()));
420 mine_transaction(&nodes[0], &tx);
421 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
422 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
425 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
426 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
427 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
431 fn test_1_conf_open() {
432 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
433 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
434 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
437 fn do_test_sanity_on_in_flight_opens(steps: u8) {
438 // Previously, we had issues deserializing channels when we hadn't connected the first block
439 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
440 // serialization round-trips and simply do steps towards opening a channel and then drop the
443 let chanmon_cfgs = create_chanmon_cfgs(2);
444 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
445 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
446 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
448 if steps & 0b1000_0000 != 0{
450 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
453 connect_block(&nodes[0], &block);
454 connect_block(&nodes[1], &block);
457 if steps & 0x0f == 0 { return; }
458 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
459 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
461 if steps & 0x0f == 1 { return; }
462 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
463 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
465 if steps & 0x0f == 2 { return; }
466 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
468 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
470 if steps & 0x0f == 3 { return; }
471 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
472 check_added_monitors!(nodes[0], 0);
473 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
475 if steps & 0x0f == 4 { return; }
476 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
478 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
479 assert_eq!(added_monitors.len(), 1);
480 assert_eq!(added_monitors[0].0, funding_output);
481 added_monitors.clear();
483 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
485 if steps & 0x0f == 5 { return; }
486 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
488 let mut added_monitors = nodes[0].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();
494 let events_4 = nodes[0].node.get_and_clear_pending_events();
495 assert_eq!(events_4.len(), 0);
497 if steps & 0x0f == 6 { return; }
498 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
500 if steps & 0x0f == 7 { return; }
501 confirm_transaction_at(&nodes[0], &tx, 2);
502 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
503 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
507 fn test_sanity_on_in_flight_opens() {
508 do_test_sanity_on_in_flight_opens(0);
509 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
510 do_test_sanity_on_in_flight_opens(1);
511 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
512 do_test_sanity_on_in_flight_opens(2);
513 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
514 do_test_sanity_on_in_flight_opens(3);
515 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(4);
517 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
518 do_test_sanity_on_in_flight_opens(5);
519 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(6);
521 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(7);
523 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(8);
525 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
529 fn test_update_fee_vanilla() {
530 let chanmon_cfgs = create_chanmon_cfgs(2);
531 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
532 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
533 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
534 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
535 let channel_id = chan.2;
537 let feerate = get_feerate!(nodes[0], channel_id);
538 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
539 check_added_monitors!(nodes[0], 1);
541 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
542 assert_eq!(events_0.len(), 1);
543 let (update_msg, commitment_signed) = match events_0[0] {
544 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 } } => {
545 (update_fee.as_ref(), commitment_signed)
547 _ => panic!("Unexpected event"),
549 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
551 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
552 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
553 check_added_monitors!(nodes[1], 1);
555 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
556 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
557 check_added_monitors!(nodes[0], 1);
559 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
560 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
561 // No commitment_signed so get_event_msg's assert(len == 1) passes
562 check_added_monitors!(nodes[0], 1);
564 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
565 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
566 check_added_monitors!(nodes[1], 1);
570 fn test_update_fee_that_funder_cannot_afford() {
571 let chanmon_cfgs = create_chanmon_cfgs(2);
572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
575 let channel_value = 1888;
576 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
577 let channel_id = chan.2;
580 nodes[0].node.update_fee(channel_id, feerate).unwrap();
581 check_added_monitors!(nodes[0], 1);
582 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
584 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
586 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
588 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
589 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
591 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
593 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
594 let num_htlcs = commitment_tx.output.len() - 2;
595 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
596 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
597 actual_fee = channel_value - actual_fee;
598 assert_eq!(total_fee, actual_fee);
601 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
602 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
603 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
604 check_added_monitors!(nodes[0], 1);
606 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
608 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
610 //While producing the commitment_signed response after handling a received update_fee request the
611 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
612 //Should produce and error.
613 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
614 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
615 check_added_monitors!(nodes[1], 1);
616 check_closed_broadcast!(nodes[1], true);
620 fn test_update_fee_with_fundee_update_add_htlc() {
621 let chanmon_cfgs = create_chanmon_cfgs(2);
622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
624 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
625 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
626 let channel_id = chan.2;
627 let logger = test_utils::TestLogger::new();
630 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
632 let feerate = get_feerate!(nodes[0], channel_id);
633 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
634 check_added_monitors!(nodes[0], 1);
636 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
637 assert_eq!(events_0.len(), 1);
638 let (update_msg, commitment_signed) = match events_0[0] {
639 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 } } => {
640 (update_fee.as_ref(), commitment_signed)
642 _ => panic!("Unexpected event"),
644 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
645 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
646 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
647 check_added_monitors!(nodes[1], 1);
649 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[0]);
650 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
651 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
653 // nothing happens since node[1] is in AwaitingRemoteRevoke
654 nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
656 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
657 assert_eq!(added_monitors.len(), 0);
658 added_monitors.clear();
660 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
661 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
662 // node[1] has nothing to do
664 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
665 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
666 check_added_monitors!(nodes[0], 1);
668 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
669 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
670 // No commitment_signed so get_event_msg's assert(len == 1) passes
671 check_added_monitors!(nodes[0], 1);
672 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
673 check_added_monitors!(nodes[1], 1);
674 // AwaitingRemoteRevoke ends here
676 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
677 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
678 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
679 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
680 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
681 assert_eq!(commitment_update.update_fee.is_none(), true);
683 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
684 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
685 check_added_monitors!(nodes[0], 1);
686 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
688 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
689 check_added_monitors!(nodes[1], 1);
690 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
692 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
693 check_added_monitors!(nodes[1], 1);
694 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
695 // No commitment_signed so get_event_msg's assert(len == 1) passes
697 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
698 check_added_monitors!(nodes[0], 1);
699 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
701 expect_pending_htlcs_forwardable!(nodes[0]);
703 let events = nodes[0].node.get_and_clear_pending_events();
704 assert_eq!(events.len(), 1);
706 Event::PaymentReceived { .. } => { },
707 _ => panic!("Unexpected event"),
710 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
712 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
713 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
714 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
718 fn test_update_fee() {
719 let chanmon_cfgs = create_chanmon_cfgs(2);
720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
722 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
723 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
724 let channel_id = chan.2;
727 // (1) update_fee/commitment_signed ->
728 // <- (2) revoke_and_ack
729 // .- send (3) commitment_signed
730 // (4) update_fee/commitment_signed ->
731 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
732 // <- (3) commitment_signed delivered
733 // send (6) revoke_and_ack -.
734 // <- (5) deliver revoke_and_ack
735 // (6) deliver revoke_and_ack ->
736 // .- send (7) commitment_signed in response to (4)
737 // <- (7) deliver commitment_signed
740 // Create and deliver (1)...
741 let feerate = get_feerate!(nodes[0], channel_id);
742 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
743 check_added_monitors!(nodes[0], 1);
745 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
746 assert_eq!(events_0.len(), 1);
747 let (update_msg, commitment_signed) = match events_0[0] {
748 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 } } => {
749 (update_fee.as_ref(), commitment_signed)
751 _ => panic!("Unexpected event"),
753 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
755 // Generate (2) and (3):
756 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
757 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
758 check_added_monitors!(nodes[1], 1);
761 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
762 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
763 check_added_monitors!(nodes[0], 1);
765 // Create and deliver (4)...
766 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
767 check_added_monitors!(nodes[0], 1);
768 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
769 assert_eq!(events_0.len(), 1);
770 let (update_msg, commitment_signed) = match events_0[0] {
771 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 } } => {
772 (update_fee.as_ref(), commitment_signed)
774 _ => panic!("Unexpected event"),
777 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
778 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
779 check_added_monitors!(nodes[1], 1);
781 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
782 // No commitment_signed so get_event_msg's assert(len == 1) passes
784 // Handle (3), creating (6):
785 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
786 check_added_monitors!(nodes[0], 1);
787 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
788 // No commitment_signed so get_event_msg's assert(len == 1) passes
791 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
792 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
793 check_added_monitors!(nodes[0], 1);
795 // Deliver (6), creating (7):
796 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
797 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
798 assert!(commitment_update.update_add_htlcs.is_empty());
799 assert!(commitment_update.update_fulfill_htlcs.is_empty());
800 assert!(commitment_update.update_fail_htlcs.is_empty());
801 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
802 assert!(commitment_update.update_fee.is_none());
803 check_added_monitors!(nodes[1], 1);
806 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
807 check_added_monitors!(nodes[0], 1);
808 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
809 // No commitment_signed so get_event_msg's assert(len == 1) passes
811 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
812 check_added_monitors!(nodes[1], 1);
813 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
815 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
816 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
817 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
821 fn pre_funding_lock_shutdown_test() {
822 // Test sending a shutdown prior to funding_locked after funding generation
823 let chanmon_cfgs = create_chanmon_cfgs(2);
824 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
825 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
826 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
827 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
828 mine_transaction(&nodes[0], &tx);
829 mine_transaction(&nodes[1], &tx);
831 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
832 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
833 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
834 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
835 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
837 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
838 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
839 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
840 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
841 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
842 assert!(node_0_none.is_none());
844 assert!(nodes[0].node.list_channels().is_empty());
845 assert!(nodes[1].node.list_channels().is_empty());
849 fn updates_shutdown_wait() {
850 // Test sending a shutdown with outstanding updates pending
851 let chanmon_cfgs = create_chanmon_cfgs(3);
852 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
853 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
854 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
855 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
856 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
857 let logger = test_utils::TestLogger::new();
859 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
861 nodes[0].node.close_channel(&chan_1.2).unwrap();
862 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
863 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
864 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
865 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
867 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
868 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
870 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
872 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
873 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
874 let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
875 let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
876 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable {..}, {});
877 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &Some(payment_secret)), true, APIError::ChannelUnavailable {..}, {});
879 assert!(nodes[2].node.claim_funds(our_payment_preimage));
880 check_added_monitors!(nodes[2], 1);
881 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
882 assert!(updates.update_add_htlcs.is_empty());
883 assert!(updates.update_fail_htlcs.is_empty());
884 assert!(updates.update_fail_malformed_htlcs.is_empty());
885 assert!(updates.update_fee.is_none());
886 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
887 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
888 check_added_monitors!(nodes[1], 1);
889 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
890 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
892 assert!(updates_2.update_add_htlcs.is_empty());
893 assert!(updates_2.update_fail_htlcs.is_empty());
894 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
895 assert!(updates_2.update_fee.is_none());
896 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
897 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
898 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
900 let events = nodes[0].node.get_and_clear_pending_events();
901 assert_eq!(events.len(), 1);
903 Event::PaymentSent { ref payment_preimage } => {
904 assert_eq!(our_payment_preimage, *payment_preimage);
906 _ => panic!("Unexpected event"),
909 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
910 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
911 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
912 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
913 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
914 assert!(node_0_none.is_none());
916 assert!(nodes[0].node.list_channels().is_empty());
918 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
919 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
920 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
921 assert!(nodes[1].node.list_channels().is_empty());
922 assert!(nodes[2].node.list_channels().is_empty());
926 fn htlc_fail_async_shutdown() {
927 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
928 let chanmon_cfgs = create_chanmon_cfgs(3);
929 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
930 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
931 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
932 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
933 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
934 let logger = test_utils::TestLogger::new();
936 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
937 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
938 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
939 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
940 check_added_monitors!(nodes[0], 1);
941 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
942 assert_eq!(updates.update_add_htlcs.len(), 1);
943 assert!(updates.update_fulfill_htlcs.is_empty());
944 assert!(updates.update_fail_htlcs.is_empty());
945 assert!(updates.update_fail_malformed_htlcs.is_empty());
946 assert!(updates.update_fee.is_none());
948 nodes[1].node.close_channel(&chan_1.2).unwrap();
949 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
950 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
951 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
954 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
955 check_added_monitors!(nodes[1], 1);
956 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
957 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
959 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
960 assert!(updates_2.update_add_htlcs.is_empty());
961 assert!(updates_2.update_fulfill_htlcs.is_empty());
962 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
963 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
964 assert!(updates_2.update_fee.is_none());
966 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
967 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
969 expect_payment_failed!(nodes[0], our_payment_hash, false);
971 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
972 assert_eq!(msg_events.len(), 2);
973 let node_0_closing_signed = match msg_events[0] {
974 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
975 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
978 _ => panic!("Unexpected event"),
980 match msg_events[1] {
981 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
982 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
984 _ => panic!("Unexpected event"),
987 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
988 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
989 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
990 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
991 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
992 assert!(node_0_none.is_none());
994 assert!(nodes[0].node.list_channels().is_empty());
996 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
997 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
998 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
999 assert!(nodes[1].node.list_channels().is_empty());
1000 assert!(nodes[2].node.list_channels().is_empty());
1003 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1004 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1005 // messages delivered prior to disconnect
1006 let chanmon_cfgs = create_chanmon_cfgs(3);
1007 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1008 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1009 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1010 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1011 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1013 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1015 nodes[1].node.close_channel(&chan_1.2).unwrap();
1016 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1018 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1019 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1021 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1025 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1026 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1028 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1029 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1030 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1031 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1033 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1034 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1035 assert!(node_1_shutdown == node_1_2nd_shutdown);
1037 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1038 let node_0_2nd_shutdown = if recv_count > 0 {
1039 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1040 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1043 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1044 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1045 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1047 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1049 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1050 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1052 assert!(nodes[2].node.claim_funds(our_payment_preimage));
1053 check_added_monitors!(nodes[2], 1);
1054 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1055 assert!(updates.update_add_htlcs.is_empty());
1056 assert!(updates.update_fail_htlcs.is_empty());
1057 assert!(updates.update_fail_malformed_htlcs.is_empty());
1058 assert!(updates.update_fee.is_none());
1059 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1060 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1061 check_added_monitors!(nodes[1], 1);
1062 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1063 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1065 assert!(updates_2.update_add_htlcs.is_empty());
1066 assert!(updates_2.update_fail_htlcs.is_empty());
1067 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1068 assert!(updates_2.update_fee.is_none());
1069 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1070 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1071 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1073 let events = nodes[0].node.get_and_clear_pending_events();
1074 assert_eq!(events.len(), 1);
1076 Event::PaymentSent { ref payment_preimage } => {
1077 assert_eq!(our_payment_preimage, *payment_preimage);
1079 _ => panic!("Unexpected event"),
1082 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1084 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1085 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1086 assert!(node_1_closing_signed.is_some());
1089 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1090 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1092 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1093 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1094 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1095 if recv_count == 0 {
1096 // If all closing_signeds weren't delivered we can just resume where we left off...
1097 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1099 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1100 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1101 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1103 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1104 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1105 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1107 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1108 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1110 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1111 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1112 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1114 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1115 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1116 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1117 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1118 assert!(node_0_none.is_none());
1120 // If one node, however, received + responded with an identical closing_signed we end
1121 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1122 // There isn't really anything better we can do simply, but in the future we might
1123 // explore storing a set of recently-closed channels that got disconnected during
1124 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1125 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1127 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1129 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1130 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1131 assert_eq!(msg_events.len(), 1);
1132 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1134 &ErrorAction::SendErrorMessage { ref msg } => {
1135 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1136 assert_eq!(msg.channel_id, chan_1.2);
1138 _ => panic!("Unexpected event!"),
1140 } else { panic!("Needed SendErrorMessage close"); }
1142 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1143 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1144 // closing_signed so we do it ourselves
1145 check_closed_broadcast!(nodes[0], false);
1146 check_added_monitors!(nodes[0], 1);
1149 assert!(nodes[0].node.list_channels().is_empty());
1151 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1152 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1153 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1154 assert!(nodes[1].node.list_channels().is_empty());
1155 assert!(nodes[2].node.list_channels().is_empty());
1159 fn test_shutdown_rebroadcast() {
1160 do_test_shutdown_rebroadcast(0);
1161 do_test_shutdown_rebroadcast(1);
1162 do_test_shutdown_rebroadcast(2);
1166 fn fake_network_test() {
1167 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1168 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1169 let chanmon_cfgs = create_chanmon_cfgs(4);
1170 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1171 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1172 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1174 // Create some initial channels
1175 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1176 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1177 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1179 // Rebalance the network a bit by relaying one payment through all the channels...
1180 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1183 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1185 // Send some more payments
1186 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1187 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1188 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1190 // Test failure packets
1191 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1192 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1194 // Add a new channel that skips 3
1195 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1197 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1198 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1199 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1200 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1201 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1202 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1203 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1205 // Do some rebalance loop payments, simultaneously
1206 let mut hops = Vec::with_capacity(3);
1207 hops.push(RouteHop {
1208 pubkey: nodes[2].node.get_our_node_id(),
1209 node_features: NodeFeatures::empty(),
1210 short_channel_id: chan_2.0.contents.short_channel_id,
1211 channel_features: ChannelFeatures::empty(),
1213 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1215 hops.push(RouteHop {
1216 pubkey: nodes[3].node.get_our_node_id(),
1217 node_features: NodeFeatures::empty(),
1218 short_channel_id: chan_3.0.contents.short_channel_id,
1219 channel_features: ChannelFeatures::empty(),
1221 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1223 hops.push(RouteHop {
1224 pubkey: nodes[1].node.get_our_node_id(),
1225 node_features: NodeFeatures::known(),
1226 short_channel_id: chan_4.0.contents.short_channel_id,
1227 channel_features: ChannelFeatures::known(),
1229 cltv_expiry_delta: TEST_FINAL_CLTV,
1231 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;
1232 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;
1233 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1235 let mut hops = Vec::with_capacity(3);
1236 hops.push(RouteHop {
1237 pubkey: nodes[3].node.get_our_node_id(),
1238 node_features: NodeFeatures::empty(),
1239 short_channel_id: chan_4.0.contents.short_channel_id,
1240 channel_features: ChannelFeatures::empty(),
1242 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1244 hops.push(RouteHop {
1245 pubkey: nodes[2].node.get_our_node_id(),
1246 node_features: NodeFeatures::empty(),
1247 short_channel_id: chan_3.0.contents.short_channel_id,
1248 channel_features: ChannelFeatures::empty(),
1250 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1252 hops.push(RouteHop {
1253 pubkey: nodes[1].node.get_our_node_id(),
1254 node_features: NodeFeatures::known(),
1255 short_channel_id: chan_2.0.contents.short_channel_id,
1256 channel_features: ChannelFeatures::known(),
1258 cltv_expiry_delta: TEST_FINAL_CLTV,
1260 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;
1261 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;
1262 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1264 // Claim the rebalances...
1265 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1266 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1268 // Add a duplicate new channel from 2 to 4
1269 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1271 // Send some payments across both channels
1272 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1274 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1277 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1278 let events = nodes[0].node.get_and_clear_pending_msg_events();
1279 assert_eq!(events.len(), 0);
1280 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);
1282 //TODO: Test that routes work again here as we've been notified that the channel is full
1284 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1285 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1286 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1288 // Close down the channels...
1289 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1290 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1291 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1292 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1293 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1297 fn holding_cell_htlc_counting() {
1298 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1299 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1300 // commitment dance rounds.
1301 let chanmon_cfgs = create_chanmon_cfgs(3);
1302 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1303 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1304 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1305 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1306 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1307 let logger = test_utils::TestLogger::new();
1309 let mut payments = Vec::new();
1310 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1311 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[2]);
1312 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1313 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1314 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
1315 payments.push((payment_preimage, payment_hash));
1317 check_added_monitors!(nodes[1], 1);
1319 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1320 assert_eq!(events.len(), 1);
1321 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1322 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1324 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1325 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1327 let (_, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[2]);
1329 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1330 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1331 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)), true, APIError::ChannelUnavailable { ref err },
1332 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1333 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1334 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1337 // This should also be true if we try to forward a payment.
1338 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[2]);
1340 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1341 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1342 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
1343 check_added_monitors!(nodes[0], 1);
1346 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1347 assert_eq!(events.len(), 1);
1348 let payment_event = SendEvent::from_event(events.pop().unwrap());
1349 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1351 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1352 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1353 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1354 // fails), the second will process the resulting failure and fail the HTLC backward.
1355 expect_pending_htlcs_forwardable!(nodes[1]);
1356 expect_pending_htlcs_forwardable!(nodes[1]);
1357 check_added_monitors!(nodes[1], 1);
1359 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1360 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1361 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1363 let events = nodes[0].node.get_and_clear_pending_msg_events();
1364 assert_eq!(events.len(), 1);
1366 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1367 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1369 _ => panic!("Unexpected event"),
1372 expect_payment_failed!(nodes[0], payment_hash_2, false);
1374 // Now forward all the pending HTLCs and claim them back
1375 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1376 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1377 check_added_monitors!(nodes[2], 1);
1379 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1380 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1381 check_added_monitors!(nodes[1], 1);
1382 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1384 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1385 check_added_monitors!(nodes[1], 1);
1386 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1388 for ref update in as_updates.update_add_htlcs.iter() {
1389 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1391 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1392 check_added_monitors!(nodes[2], 1);
1393 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1394 check_added_monitors!(nodes[2], 1);
1395 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1397 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1398 check_added_monitors!(nodes[1], 1);
1399 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1400 check_added_monitors!(nodes[1], 1);
1401 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1403 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1404 check_added_monitors!(nodes[2], 1);
1406 expect_pending_htlcs_forwardable!(nodes[2]);
1408 let events = nodes[2].node.get_and_clear_pending_events();
1409 assert_eq!(events.len(), payments.len());
1410 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1412 &Event::PaymentReceived { ref payment_hash, .. } => {
1413 assert_eq!(*payment_hash, *hash);
1415 _ => panic!("Unexpected event"),
1419 for (preimage, _) in payments.drain(..) {
1420 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1423 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1427 fn duplicate_htlc_test() {
1428 // Test that we accept duplicate payment_hash HTLCs across the network and that
1429 // claiming/failing them are all separate and don't affect each other
1430 let chanmon_cfgs = create_chanmon_cfgs(6);
1431 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1432 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1433 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1435 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1436 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1437 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1438 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1439 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1440 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1442 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1444 *nodes[0].network_payment_count.borrow_mut() -= 1;
1445 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1447 *nodes[0].network_payment_count.borrow_mut() -= 1;
1448 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1450 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1451 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1452 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1456 fn test_duplicate_htlc_different_direction_onchain() {
1457 // Test that ChannelMonitor doesn't generate 2 preimage txn
1458 // when we have 2 HTLCs with same preimage that go across a node
1459 // in opposite directions, even with the same payment secret.
1460 let chanmon_cfgs = create_chanmon_cfgs(2);
1461 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1462 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1463 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1465 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1466 let logger = test_utils::TestLogger::new();
1469 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1471 let (payment_preimage, payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1473 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1474 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1475 let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, 0).unwrap();
1476 send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1478 // Provide preimage to node 0 by claiming payment
1479 nodes[0].node.claim_funds(payment_preimage);
1480 check_added_monitors!(nodes[0], 1);
1482 // Broadcast node 1 commitment txn
1483 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1485 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1486 let mut has_both_htlcs = 0; // check htlcs match ones committed
1487 for outp in remote_txn[0].output.iter() {
1488 if outp.value == 800_000 / 1000 {
1489 has_both_htlcs += 1;
1490 } else if outp.value == 900_000 / 1000 {
1491 has_both_htlcs += 1;
1494 assert_eq!(has_both_htlcs, 2);
1496 mine_transaction(&nodes[0], &remote_txn[0]);
1497 check_added_monitors!(nodes[0], 1);
1498 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
1500 // Check we only broadcast 1 timeout tx
1501 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1502 assert_eq!(claim_txn.len(), 8);
1503 assert_eq!(claim_txn[1], claim_txn[4]);
1504 assert_eq!(claim_txn[2], claim_txn[5]);
1505 check_spends!(claim_txn[1], chan_1.3);
1506 check_spends!(claim_txn[2], claim_txn[1]);
1507 check_spends!(claim_txn[7], claim_txn[1]);
1509 assert_eq!(claim_txn[0].input.len(), 1);
1510 assert_eq!(claim_txn[3].input.len(), 1);
1511 assert_eq!(claim_txn[0].input[0].previous_output, claim_txn[3].input[0].previous_output);
1513 assert_eq!(claim_txn[0].input.len(), 1);
1514 assert_eq!(claim_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1515 check_spends!(claim_txn[0], remote_txn[0]);
1516 assert_eq!(remote_txn[0].output[claim_txn[0].input[0].previous_output.vout as usize].value, 800);
1517 assert_eq!(claim_txn[6].input.len(), 1);
1518 assert_eq!(claim_txn[6].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1519 check_spends!(claim_txn[6], remote_txn[0]);
1520 assert_eq!(remote_txn[0].output[claim_txn[6].input[0].previous_output.vout as usize].value, 900);
1522 let events = nodes[0].node.get_and_clear_pending_msg_events();
1523 assert_eq!(events.len(), 3);
1526 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1527 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1528 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1529 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1531 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, .. } } => {
1532 assert!(update_add_htlcs.is_empty());
1533 assert!(update_fail_htlcs.is_empty());
1534 assert_eq!(update_fulfill_htlcs.len(), 1);
1535 assert!(update_fail_malformed_htlcs.is_empty());
1536 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1538 _ => panic!("Unexpected event"),
1544 fn test_basic_channel_reserve() {
1545 let chanmon_cfgs = create_chanmon_cfgs(2);
1546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1549 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1550 let logger = test_utils::TestLogger::new();
1552 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1553 let channel_reserve = chan_stat.channel_reserve_msat;
1555 // The 2* and +1 are for the fee spike reserve.
1556 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
1557 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1558 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1559 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1560 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1561 let err = nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).err().unwrap();
1563 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1565 &APIError::ChannelUnavailable{ref err} =>
1566 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1567 _ => panic!("Unexpected error variant"),
1570 _ => panic!("Unexpected error variant"),
1572 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1573 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);
1575 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1579 fn test_fee_spike_violation_fails_htlc() {
1580 let chanmon_cfgs = create_chanmon_cfgs(2);
1581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1583 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1584 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1586 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 3460001);
1587 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1588 let secp_ctx = Secp256k1::new();
1589 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1591 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1593 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1594 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &Some(payment_secret), cur_height).unwrap();
1595 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1596 let msg = msgs::UpdateAddHTLC {
1599 amount_msat: htlc_msat,
1600 payment_hash: payment_hash,
1601 cltv_expiry: htlc_cltv,
1602 onion_routing_packet: onion_packet,
1605 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1607 // Now manually create the commitment_signed message corresponding to the update_add
1608 // nodes[0] just sent. In the code for construction of this message, "local" refers
1609 // to the sender of the message, and "remote" refers to the receiver.
1611 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1613 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1615 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1616 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1617 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1618 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1619 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1620 let chan_signer = local_chan.get_signer();
1621 let pubkeys = chan_signer.pubkeys();
1622 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1623 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1624 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1626 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1627 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1628 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1629 let chan_signer = remote_chan.get_signer();
1630 let pubkeys = chan_signer.pubkeys();
1631 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1632 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1635 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1636 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1637 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1639 // Build the remote commitment transaction so we can sign it, and then later use the
1640 // signature for the commitment_signed message.
1641 let local_chan_balance = 1313;
1643 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1645 amount_msat: 3460001,
1646 cltv_expiry: htlc_cltv,
1648 transaction_output_index: Some(1),
1651 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1654 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1655 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1656 let local_chan_signer = local_chan.get_signer();
1657 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1661 commit_tx_keys.clone(),
1663 &mut vec![(accepted_htlc_info, ())],
1664 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1666 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1669 let commit_signed_msg = msgs::CommitmentSigned {
1672 htlc_signatures: res.1
1675 // Send the commitment_signed message to the nodes[1].
1676 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1677 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1679 // Send the RAA to nodes[1].
1680 let raa_msg = msgs::RevokeAndACK {
1682 per_commitment_secret: local_secret,
1683 next_per_commitment_point: next_local_point
1685 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1687 let events = nodes[1].node.get_and_clear_pending_msg_events();
1688 assert_eq!(events.len(), 1);
1689 // Make sure the HTLC failed in the way we expect.
1691 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1692 assert_eq!(update_fail_htlcs.len(), 1);
1693 update_fail_htlcs[0].clone()
1695 _ => panic!("Unexpected event"),
1697 nodes[1].logger.assert_log("lightning::ln::channel".to_string(),
1698 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", ::hex::encode(raa_msg.channel_id)), 1);
1700 check_added_monitors!(nodes[1], 2);
1704 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1705 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1706 // Set the fee rate for the channel very high, to the point where the fundee
1707 // sending any above-dust amount would result in a channel reserve violation.
1708 // In this test we check that we would be prevented from sending an HTLC in
1710 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1711 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1715 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1717 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 4843000);
1718 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1719 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1720 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1721 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);
1725 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1726 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1727 // Set the fee rate for the channel very high, to the point where the funder
1728 // receiving 1 update_add_htlc would result in them closing the channel due
1729 // to channel reserve violation. This close could also happen if the fee went
1730 // up a more realistic amount, but many HTLCs were outstanding at the time of
1731 // the update_add_htlc.
1732 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1733 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1734 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1735 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1736 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1737 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1739 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1740 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1741 let secp_ctx = Secp256k1::new();
1742 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1743 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1744 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1745 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &Some(payment_secret), cur_height).unwrap();
1746 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1747 let msg = msgs::UpdateAddHTLC {
1750 amount_msat: htlc_msat + 1,
1751 payment_hash: payment_hash,
1752 cltv_expiry: htlc_cltv,
1753 onion_routing_packet: onion_packet,
1756 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1757 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1758 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);
1759 assert_eq!(nodes[0].node.list_channels().len(), 0);
1760 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1761 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1762 check_added_monitors!(nodes[0], 1);
1766 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1767 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1768 // calculating our commitment transaction fee (this was previously broken).
1769 let chanmon_cfgs = create_chanmon_cfgs(2);
1770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1772 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1774 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1775 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1776 // transaction fee with 0 HTLCs (183 sats)).
1777 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1779 let dust_amt = 329000; // Dust amount
1780 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1781 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1782 // commitment transaction fee.
1783 let (_, _, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1787 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1788 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1789 // calculating our counterparty's commitment transaction fee (this was previously broken).
1790 let chanmon_cfgs = create_chanmon_cfgs(2);
1791 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1792 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1793 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1794 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1796 let payment_amt = 46000; // Dust amount
1797 // In the previous code, these first four payments would succeed.
1798 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1799 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1800 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1801 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1803 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1804 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1805 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1806 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1807 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1808 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1810 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1811 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1812 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1813 let (_, _, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1817 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1818 let chanmon_cfgs = create_chanmon_cfgs(3);
1819 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1820 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1821 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1822 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1823 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1826 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1827 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1828 let feerate = get_feerate!(nodes[0], chan.2);
1830 // Add a 2* and +1 for the fee spike reserve.
1831 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1832 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;
1833 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1835 // Add a pending HTLC.
1836 let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1837 let payment_event_1 = {
1838 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1839 check_added_monitors!(nodes[0], 1);
1841 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1842 assert_eq!(events.len(), 1);
1843 SendEvent::from_event(events.remove(0))
1845 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1847 // Attempt to trigger a channel reserve violation --> payment failure.
1848 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1849 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;
1850 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1851 let (route_2, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_2);
1853 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1854 let secp_ctx = Secp256k1::new();
1855 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1856 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1857 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1858 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1859 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1860 let msg = msgs::UpdateAddHTLC {
1863 amount_msat: htlc_msat + 1,
1864 payment_hash: our_payment_hash_1,
1865 cltv_expiry: htlc_cltv,
1866 onion_routing_packet: onion_packet,
1869 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1870 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1871 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1872 assert_eq!(nodes[1].node.list_channels().len(), 1);
1873 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1874 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1875 check_added_monitors!(nodes[1], 1);
1879 fn test_inbound_outbound_capacity_is_not_zero() {
1880 let chanmon_cfgs = create_chanmon_cfgs(2);
1881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1884 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1885 let channels0 = node_chanmgrs[0].list_channels();
1886 let channels1 = node_chanmgrs[1].list_channels();
1887 assert_eq!(channels0.len(), 1);
1888 assert_eq!(channels1.len(), 1);
1890 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1891 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1893 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1894 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1897 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1898 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1902 fn test_channel_reserve_holding_cell_htlcs() {
1903 let chanmon_cfgs = create_chanmon_cfgs(3);
1904 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1905 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1906 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1907 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1908 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1910 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1911 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1913 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1914 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1916 macro_rules! expect_forward {
1918 let mut events = $node.node.get_and_clear_pending_msg_events();
1919 assert_eq!(events.len(), 1);
1920 check_added_monitors!($node, 1);
1921 let payment_event = SendEvent::from_event(events.remove(0));
1926 let feemsat = 239; // somehow we know?
1927 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1928 let feerate = get_feerate!(nodes[0], chan_1.2);
1930 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1932 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1934 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_0);
1935 route.paths[0].last_mut().unwrap().fee_msat += 1;
1936 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1937 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
1938 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)));
1939 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1940 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);
1943 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1944 // nodes[0]'s wealth
1946 let amt_msat = recv_value_0 + total_fee_msat;
1947 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1948 // Also, ensure that each payment has enough to be over the dust limit to
1949 // ensure it'll be included in each commit tx fee calculation.
1950 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1951 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1952 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1955 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1957 let (stat01_, stat11_, stat12_, stat22_) = (
1958 get_channel_value_stat!(nodes[0], chan_1.2),
1959 get_channel_value_stat!(nodes[1], chan_1.2),
1960 get_channel_value_stat!(nodes[1], chan_2.2),
1961 get_channel_value_stat!(nodes[2], chan_2.2),
1964 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1965 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1966 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1967 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1968 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1971 // adding pending output.
1972 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1973 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1974 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1975 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1976 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1977 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1978 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1979 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1980 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1982 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1983 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1984 let amt_msat_1 = recv_value_1 + total_fee_msat;
1986 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);
1987 let payment_event_1 = {
1988 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &Some(our_payment_secret_1)).unwrap();
1989 check_added_monitors!(nodes[0], 1);
1991 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1992 assert_eq!(events.len(), 1);
1993 SendEvent::from_event(events.remove(0))
1995 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1997 // channel reserve test with htlc pending output > 0
1998 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2000 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_2 + 1);
2001 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
2002 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2003 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2006 // split the rest to test holding cell
2007 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2008 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2009 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2010 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2012 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2013 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);
2016 // now see if they go through on both sides
2017 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);
2018 // but this will stuck in the holding cell
2019 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &Some(our_payment_secret_21)).unwrap();
2020 check_added_monitors!(nodes[0], 0);
2021 let events = nodes[0].node.get_and_clear_pending_events();
2022 assert_eq!(events.len(), 0);
2024 // test with outbound holding cell amount > 0
2026 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22+1);
2027 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
2028 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2029 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2030 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);
2033 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);
2034 // this will also stuck in the holding cell
2035 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &Some(our_payment_secret_22)).unwrap();
2036 check_added_monitors!(nodes[0], 0);
2037 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2038 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2040 // flush the pending htlc
2041 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2042 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2043 check_added_monitors!(nodes[1], 1);
2045 // the pending htlc should be promoted to committed
2046 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2047 check_added_monitors!(nodes[0], 1);
2048 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2050 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2051 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2052 // No commitment_signed so get_event_msg's assert(len == 1) passes
2053 check_added_monitors!(nodes[0], 1);
2055 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2056 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2057 check_added_monitors!(nodes[1], 1);
2059 expect_pending_htlcs_forwardable!(nodes[1]);
2061 let ref payment_event_11 = expect_forward!(nodes[1]);
2062 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2063 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2065 expect_pending_htlcs_forwardable!(nodes[2]);
2066 expect_payment_received!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2068 // flush the htlcs in the holding cell
2069 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2070 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2071 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2072 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2073 expect_pending_htlcs_forwardable!(nodes[1]);
2075 let ref payment_event_3 = expect_forward!(nodes[1]);
2076 assert_eq!(payment_event_3.msgs.len(), 2);
2077 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2078 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2080 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2081 expect_pending_htlcs_forwardable!(nodes[2]);
2083 let events = nodes[2].node.get_and_clear_pending_events();
2084 assert_eq!(events.len(), 2);
2086 Event::PaymentReceived { ref payment_hash, ref payment_preimage, ref payment_secret, amt, user_payment_id: _ } => {
2087 assert_eq!(our_payment_hash_21, *payment_hash);
2088 assert!(payment_preimage.is_none());
2089 assert_eq!(our_payment_secret_21, *payment_secret);
2090 assert_eq!(recv_value_21, amt);
2092 _ => panic!("Unexpected event"),
2095 Event::PaymentReceived { ref payment_hash, ref payment_preimage, ref payment_secret, amt, user_payment_id: _ } => {
2096 assert_eq!(our_payment_hash_22, *payment_hash);
2097 assert!(payment_preimage.is_none());
2098 assert_eq!(our_payment_secret_22, *payment_secret);
2099 assert_eq!(recv_value_22, amt);
2101 _ => panic!("Unexpected event"),
2104 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2105 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2106 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2108 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2109 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2110 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2112 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2113 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);
2114 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2115 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2116 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2118 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2119 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2123 fn channel_reserve_in_flight_removes() {
2124 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2125 // can send to its counterparty, but due to update ordering, the other side may not yet have
2126 // considered those HTLCs fully removed.
2127 // This tests that we don't count HTLCs which will not be included in the next remote
2128 // commitment transaction towards the reserve value (as it implies no commitment transaction
2129 // will be generated which violates the remote reserve value).
2130 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2132 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2133 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2134 // you only consider the value of the first HTLC, it may not),
2135 // * start routing a third HTLC from A to B,
2136 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2137 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2138 // * deliver the first fulfill from B
2139 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2141 // * deliver A's response CS and RAA.
2142 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2143 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2144 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2145 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2146 let chanmon_cfgs = create_chanmon_cfgs(2);
2147 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2148 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2149 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2150 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2151 let logger = test_utils::TestLogger::new();
2153 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2154 // Route the first two HTLCs.
2155 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2156 let (payment_preimage_2, _, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2158 // Start routing the third HTLC (this is just used to get everyone in the right state).
2159 let (payment_preimage_3, payment_hash_3, payment_secret_3) = get_payment_preimage_hash!(nodes[1]);
2161 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2162 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2163 nodes[0].node.send_payment(&route, payment_hash_3, &Some(payment_secret_3)).unwrap();
2164 check_added_monitors!(nodes[0], 1);
2165 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2166 assert_eq!(events.len(), 1);
2167 SendEvent::from_event(events.remove(0))
2170 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2171 // initial fulfill/CS.
2172 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2173 check_added_monitors!(nodes[1], 1);
2174 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2176 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2177 // remove the second HTLC when we send the HTLC back from B to A.
2178 assert!(nodes[1].node.claim_funds(payment_preimage_2));
2179 check_added_monitors!(nodes[1], 1);
2180 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2182 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2183 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2184 check_added_monitors!(nodes[0], 1);
2185 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2186 expect_payment_sent!(nodes[0], payment_preimage_1);
2188 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2189 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2190 check_added_monitors!(nodes[1], 1);
2191 // B is already AwaitingRAA, so cant generate a CS here
2192 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2194 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2195 check_added_monitors!(nodes[1], 1);
2196 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2198 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2199 check_added_monitors!(nodes[0], 1);
2200 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2202 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2203 check_added_monitors!(nodes[1], 1);
2204 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2206 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2207 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2208 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2209 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2210 // on-chain as necessary).
2211 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2212 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2213 check_added_monitors!(nodes[0], 1);
2214 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2215 expect_payment_sent!(nodes[0], payment_preimage_2);
2217 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2218 check_added_monitors!(nodes[1], 1);
2219 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2221 expect_pending_htlcs_forwardable!(nodes[1]);
2222 expect_payment_received!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2224 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2225 // resolve the second HTLC from A's point of view.
2226 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2227 check_added_monitors!(nodes[0], 1);
2228 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2230 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2231 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2232 let (payment_preimage_4, payment_hash_4, payment_secret_4) = get_payment_preimage_hash!(nodes[0]);
2234 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2235 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2236 nodes[1].node.send_payment(&route, payment_hash_4, &Some(payment_secret_4)).unwrap();
2237 check_added_monitors!(nodes[1], 1);
2238 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2239 assert_eq!(events.len(), 1);
2240 SendEvent::from_event(events.remove(0))
2243 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2244 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2245 check_added_monitors!(nodes[0], 1);
2246 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2248 // Now just resolve all the outstanding messages/HTLCs for completeness...
2250 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2251 check_added_monitors!(nodes[1], 1);
2252 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2254 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2255 check_added_monitors!(nodes[1], 1);
2257 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2258 check_added_monitors!(nodes[0], 1);
2259 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2261 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2262 check_added_monitors!(nodes[1], 1);
2263 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2265 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2266 check_added_monitors!(nodes[0], 1);
2268 expect_pending_htlcs_forwardable!(nodes[0]);
2269 expect_payment_received!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2271 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2272 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2276 fn channel_monitor_network_test() {
2277 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2278 // tests that ChannelMonitor is able to recover from various states.
2279 let chanmon_cfgs = create_chanmon_cfgs(5);
2280 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2281 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2282 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2284 // Create some initial channels
2285 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2286 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2287 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2288 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2290 // Make sure all nodes are at the same starting height
2291 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2292 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2293 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2294 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2295 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2297 // Rebalance the network a bit by relaying one payment through all the channels...
2298 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2299 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2300 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2301 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2303 // Simple case with no pending HTLCs:
2304 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2305 check_added_monitors!(nodes[1], 1);
2306 check_closed_broadcast!(nodes[1], false);
2308 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2309 assert_eq!(node_txn.len(), 1);
2310 mine_transaction(&nodes[0], &node_txn[0]);
2311 check_added_monitors!(nodes[0], 1);
2312 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2314 check_closed_broadcast!(nodes[0], true);
2315 assert_eq!(nodes[0].node.list_channels().len(), 0);
2316 assert_eq!(nodes[1].node.list_channels().len(), 1);
2318 // One pending HTLC is discarded by the force-close:
2319 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2321 // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2322 // broadcasted until we reach the timelock time).
2323 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2324 check_closed_broadcast!(nodes[1], false);
2325 check_added_monitors!(nodes[1], 1);
2327 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2328 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2329 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2330 mine_transaction(&nodes[2], &node_txn[0]);
2331 check_added_monitors!(nodes[2], 1);
2332 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2334 check_closed_broadcast!(nodes[2], true);
2335 assert_eq!(nodes[1].node.list_channels().len(), 0);
2336 assert_eq!(nodes[2].node.list_channels().len(), 1);
2338 macro_rules! claim_funds {
2339 ($node: expr, $prev_node: expr, $preimage: expr) => {
2341 assert!($node.node.claim_funds($preimage));
2342 check_added_monitors!($node, 1);
2344 let events = $node.node.get_and_clear_pending_msg_events();
2345 assert_eq!(events.len(), 1);
2347 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2348 assert!(update_add_htlcs.is_empty());
2349 assert!(update_fail_htlcs.is_empty());
2350 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2352 _ => panic!("Unexpected event"),
2358 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2359 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2360 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2361 check_added_monitors!(nodes[2], 1);
2362 check_closed_broadcast!(nodes[2], false);
2363 let node2_commitment_txid;
2365 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2366 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2367 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2368 node2_commitment_txid = node_txn[0].txid();
2370 // Claim the payment on nodes[3], giving it knowledge of the preimage
2371 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
2372 mine_transaction(&nodes[3], &node_txn[0]);
2373 check_added_monitors!(nodes[3], 1);
2374 check_preimage_claim(&nodes[3], &node_txn);
2376 check_closed_broadcast!(nodes[3], true);
2377 assert_eq!(nodes[2].node.list_channels().len(), 0);
2378 assert_eq!(nodes[3].node.list_channels().len(), 1);
2380 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2381 // confusing us in the following tests.
2382 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2384 // One pending HTLC to time out:
2385 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2386 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2389 let (close_chan_update_1, close_chan_update_2) = {
2390 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2391 let events = nodes[3].node.get_and_clear_pending_msg_events();
2392 assert_eq!(events.len(), 2);
2393 let close_chan_update_1 = match events[0] {
2394 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2397 _ => panic!("Unexpected event"),
2400 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2401 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2403 _ => panic!("Unexpected event"),
2405 check_added_monitors!(nodes[3], 1);
2407 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2409 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2410 node_txn.retain(|tx| {
2411 if tx.input[0].previous_output.txid == node2_commitment_txid {
2417 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2419 // Claim the payment on nodes[4], giving it knowledge of the preimage
2420 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
2422 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2423 let events = nodes[4].node.get_and_clear_pending_msg_events();
2424 assert_eq!(events.len(), 2);
2425 let close_chan_update_2 = match events[0] {
2426 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2429 _ => panic!("Unexpected event"),
2432 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2433 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2435 _ => panic!("Unexpected event"),
2437 check_added_monitors!(nodes[4], 1);
2438 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2440 mine_transaction(&nodes[4], &node_txn[0]);
2441 check_preimage_claim(&nodes[4], &node_txn);
2442 (close_chan_update_1, close_chan_update_2)
2444 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2445 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2446 assert_eq!(nodes[3].node.list_channels().len(), 0);
2447 assert_eq!(nodes[4].node.list_channels().len(), 0);
2449 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2453 fn test_justice_tx() {
2454 // Test justice txn built on revoked HTLC-Success tx, against both sides
2455 let mut alice_config = UserConfig::default();
2456 alice_config.channel_options.announced_channel = true;
2457 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2458 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2459 let mut bob_config = UserConfig::default();
2460 bob_config.channel_options.announced_channel = true;
2461 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2462 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2463 let user_cfgs = [Some(alice_config), Some(bob_config)];
2464 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2465 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2466 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2470 // Create some new channels:
2471 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2473 // A pending HTLC which will be revoked:
2474 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2475 // Get the will-be-revoked local txn from nodes[0]
2476 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2477 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2478 assert_eq!(revoked_local_txn[0].input.len(), 1);
2479 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2480 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2481 assert_eq!(revoked_local_txn[1].input.len(), 1);
2482 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2483 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2484 // Revoke the old state
2485 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2488 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2490 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2491 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2492 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2494 check_spends!(node_txn[0], revoked_local_txn[0]);
2495 node_txn.swap_remove(0);
2496 node_txn.truncate(1);
2498 check_added_monitors!(nodes[1], 1);
2499 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2501 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2502 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2503 // Verify broadcast of revoked HTLC-timeout
2504 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2505 check_added_monitors!(nodes[0], 1);
2506 // Broadcast revoked HTLC-timeout on node 1
2507 mine_transaction(&nodes[1], &node_txn[1]);
2508 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2510 get_announce_close_broadcast_events(&nodes, 0, 1);
2512 assert_eq!(nodes[0].node.list_channels().len(), 0);
2513 assert_eq!(nodes[1].node.list_channels().len(), 0);
2515 // We test justice_tx build by A on B's revoked HTLC-Success tx
2516 // Create some new channels:
2517 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2519 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2523 // A pending HTLC which will be revoked:
2524 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2525 // Get the will-be-revoked local txn from B
2526 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2527 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2528 assert_eq!(revoked_local_txn[0].input.len(), 1);
2529 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2530 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2531 // Revoke the old state
2532 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2534 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2536 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2537 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2538 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2540 check_spends!(node_txn[0], revoked_local_txn[0]);
2541 node_txn.swap_remove(0);
2543 check_added_monitors!(nodes[0], 1);
2544 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2546 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2547 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2548 check_added_monitors!(nodes[1], 1);
2549 mine_transaction(&nodes[0], &node_txn[1]);
2550 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2552 get_announce_close_broadcast_events(&nodes, 0, 1);
2553 assert_eq!(nodes[0].node.list_channels().len(), 0);
2554 assert_eq!(nodes[1].node.list_channels().len(), 0);
2558 fn revoked_output_claim() {
2559 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2560 // transaction is broadcast by its counterparty
2561 let chanmon_cfgs = create_chanmon_cfgs(2);
2562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2565 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2566 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2567 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2568 assert_eq!(revoked_local_txn.len(), 1);
2569 // Only output is the full channel value back to nodes[0]:
2570 assert_eq!(revoked_local_txn[0].output.len(), 1);
2571 // Send a payment through, updating everyone's latest commitment txn
2572 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2574 // Inform nodes[1] that nodes[0] broadcast a stale tx
2575 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2576 check_added_monitors!(nodes[1], 1);
2577 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2578 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2580 check_spends!(node_txn[0], revoked_local_txn[0]);
2581 check_spends!(node_txn[1], chan_1.3);
2583 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2584 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2585 get_announce_close_broadcast_events(&nodes, 0, 1);
2586 check_added_monitors!(nodes[0], 1)
2590 fn claim_htlc_outputs_shared_tx() {
2591 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2592 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2593 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2594 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2595 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2596 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2598 // Create some new channel:
2599 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2601 // Rebalance the network to generate htlc in the two directions
2602 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2603 // 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
2604 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2605 let (_payment_preimage_2, payment_hash_2, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2607 // Get the will-be-revoked local txn from node[0]
2608 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2609 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2610 assert_eq!(revoked_local_txn[0].input.len(), 1);
2611 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2612 assert_eq!(revoked_local_txn[1].input.len(), 1);
2613 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2614 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2615 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2617 //Revoke the old state
2618 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2621 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2622 check_added_monitors!(nodes[0], 1);
2623 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2624 check_added_monitors!(nodes[1], 1);
2625 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2626 expect_payment_failed!(nodes[1], payment_hash_2, true);
2628 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2629 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment
2631 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2632 check_spends!(node_txn[0], revoked_local_txn[0]);
2634 let mut witness_lens = BTreeSet::new();
2635 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2636 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2637 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2638 assert_eq!(witness_lens.len(), 3);
2639 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2640 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2641 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2643 // Next nodes[1] broadcasts its current local tx state:
2644 assert_eq!(node_txn[1].input.len(), 1);
2645 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2647 get_announce_close_broadcast_events(&nodes, 0, 1);
2648 assert_eq!(nodes[0].node.list_channels().len(), 0);
2649 assert_eq!(nodes[1].node.list_channels().len(), 0);
2653 fn claim_htlc_outputs_single_tx() {
2654 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2655 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2656 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2657 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2658 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2659 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2661 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2663 // Rebalance the network to generate htlc in the two directions
2664 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
2665 // 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
2666 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2667 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2668 let (_payment_preimage_2, payment_hash_2, _payment_secret_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2670 // Get the will-be-revoked local txn from node[0]
2671 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2673 //Revoke the old state
2674 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2677 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2678 check_added_monitors!(nodes[0], 1);
2679 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2680 check_added_monitors!(nodes[1], 1);
2681 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2683 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2684 expect_payment_failed!(nodes[1], payment_hash_2, true);
2686 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2687 assert_eq!(node_txn.len(), 9);
2688 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2689 // ChannelManager: local commmitment + local HTLC-timeout (2)
2690 // 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)
2691 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2693 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2694 assert_eq!(node_txn[0].input.len(), 1);
2695 check_spends!(node_txn[0], chan_1.3);
2696 assert_eq!(node_txn[1].input.len(), 1);
2697 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2698 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2699 check_spends!(node_txn[1], node_txn[0]);
2701 // Justice transactions are indices 1-2-4
2702 assert_eq!(node_txn[2].input.len(), 1);
2703 assert_eq!(node_txn[3].input.len(), 1);
2704 assert_eq!(node_txn[4].input.len(), 1);
2706 check_spends!(node_txn[2], revoked_local_txn[0]);
2707 check_spends!(node_txn[3], revoked_local_txn[0]);
2708 check_spends!(node_txn[4], revoked_local_txn[0]);
2710 let mut witness_lens = BTreeSet::new();
2711 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2712 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2713 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2714 assert_eq!(witness_lens.len(), 3);
2715 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2716 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2717 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2719 get_announce_close_broadcast_events(&nodes, 0, 1);
2720 assert_eq!(nodes[0].node.list_channels().len(), 0);
2721 assert_eq!(nodes[1].node.list_channels().len(), 0);
2725 fn test_htlc_on_chain_success() {
2726 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2727 // the preimage backward accordingly. So here we test that ChannelManager is
2728 // broadcasting the right event to other nodes in payment path.
2729 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2730 // A --------------------> B ----------------------> C (preimage)
2731 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2732 // commitment transaction was broadcast.
2733 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2735 // B should be able to claim via preimage if A then broadcasts its local tx.
2736 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2737 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2738 // PaymentSent event).
2740 let chanmon_cfgs = create_chanmon_cfgs(3);
2741 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2742 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2743 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2745 // Create some initial channels
2746 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2747 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2749 // Ensure all nodes are at the same height
2750 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2751 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2752 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2753 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2755 // Rebalance the network a bit by relaying one payment through all the channels...
2756 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2757 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2759 let (our_payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2760 let (our_payment_preimage_2, _payment_hash_2, _payment_secret_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2762 // Broadcast legit commitment tx from C on B's chain
2763 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2764 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2765 assert_eq!(commitment_tx.len(), 1);
2766 check_spends!(commitment_tx[0], chan_2.3);
2767 nodes[2].node.claim_funds(our_payment_preimage);
2768 nodes[2].node.claim_funds(our_payment_preimage_2);
2769 check_added_monitors!(nodes[2], 2);
2770 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2771 assert!(updates.update_add_htlcs.is_empty());
2772 assert!(updates.update_fail_htlcs.is_empty());
2773 assert!(updates.update_fail_malformed_htlcs.is_empty());
2774 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2776 mine_transaction(&nodes[2], &commitment_tx[0]);
2777 check_closed_broadcast!(nodes[2], true);
2778 check_added_monitors!(nodes[2], 1);
2779 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)
2780 assert_eq!(node_txn.len(), 5);
2781 assert_eq!(node_txn[0], node_txn[3]);
2782 assert_eq!(node_txn[1], node_txn[4]);
2783 assert_eq!(node_txn[2], commitment_tx[0]);
2784 check_spends!(node_txn[0], commitment_tx[0]);
2785 check_spends!(node_txn[1], commitment_tx[0]);
2786 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2787 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2788 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2789 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2790 assert_eq!(node_txn[0].lock_time, 0);
2791 assert_eq!(node_txn[1].lock_time, 0);
2793 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2794 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2795 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2796 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
2798 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2799 assert_eq!(added_monitors.len(), 1);
2800 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2801 added_monitors.clear();
2803 let events = nodes[1].node.get_and_clear_pending_msg_events();
2805 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2806 assert_eq!(added_monitors.len(), 2);
2807 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2808 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2809 added_monitors.clear();
2811 assert_eq!(events.len(), 3);
2813 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2814 _ => panic!("Unexpected event"),
2817 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2818 _ => panic!("Unexpected event"),
2822 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, .. } } => {
2823 assert!(update_add_htlcs.is_empty());
2824 assert!(update_fail_htlcs.is_empty());
2825 assert_eq!(update_fulfill_htlcs.len(), 1);
2826 assert!(update_fail_malformed_htlcs.is_empty());
2827 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2829 _ => panic!("Unexpected event"),
2831 macro_rules! check_tx_local_broadcast {
2832 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2833 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2834 assert_eq!(node_txn.len(), 3);
2835 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2836 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2837 check_spends!(node_txn[1], $commitment_tx);
2838 check_spends!(node_txn[2], $commitment_tx);
2839 assert_ne!(node_txn[1].lock_time, 0);
2840 assert_ne!(node_txn[2].lock_time, 0);
2842 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2843 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2844 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2845 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2847 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2848 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2849 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2850 assert!(node_txn[2].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2852 check_spends!(node_txn[0], $chan_tx);
2853 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2857 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2858 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2859 // timeout-claim of the output that nodes[2] just claimed via success.
2860 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2862 // Broadcast legit commitment tx from A on B's chain
2863 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2864 let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2865 check_spends!(node_a_commitment_tx[0], chan_1.3);
2866 mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2867 check_closed_broadcast!(nodes[1], true);
2868 check_added_monitors!(nodes[1], 1);
2869 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2870 assert_eq!(node_txn.len(), 6); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 3 (HTLC-Success, 2* RBF bumps of above HTLC txn)
2871 let commitment_spend =
2872 if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2873 check_spends!(node_txn[1], commitment_tx[0]);
2874 check_spends!(node_txn[2], commitment_tx[0]);
2875 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2878 check_spends!(node_txn[0], commitment_tx[0]);
2879 check_spends!(node_txn[1], commitment_tx[0]);
2880 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2884 check_spends!(commitment_spend, node_a_commitment_tx[0]);
2885 assert_eq!(commitment_spend.input.len(), 2);
2886 assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887 assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2888 assert_eq!(commitment_spend.lock_time, 0);
2889 assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2890 check_spends!(node_txn[3], chan_1.3);
2891 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2892 check_spends!(node_txn[4], node_txn[3]);
2893 check_spends!(node_txn[5], node_txn[3]);
2894 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2895 // we already checked the same situation with A.
2897 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2898 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2899 connect_block(&nodes[0], &Block { header, txdata: vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()] });
2900 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
2901 check_closed_broadcast!(nodes[0], true);
2902 check_added_monitors!(nodes[0], 1);
2903 let events = nodes[0].node.get_and_clear_pending_events();
2904 assert_eq!(events.len(), 2);
2905 let mut first_claimed = false;
2906 for event in events {
2908 Event::PaymentSent { payment_preimage } => {
2909 if payment_preimage == our_payment_preimage {
2910 assert!(!first_claimed);
2911 first_claimed = true;
2913 assert_eq!(payment_preimage, our_payment_preimage_2);
2916 _ => panic!("Unexpected event"),
2919 check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0], chan_1.3);
2922 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2923 // Test that in case of a unilateral close onchain, we detect the state of output and
2924 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2925 // broadcasting the right event to other nodes in payment path.
2926 // A ------------------> B ----------------------> C (timeout)
2927 // B's commitment tx C's commitment tx
2929 // B's HTLC timeout tx B's timeout tx
2931 let chanmon_cfgs = create_chanmon_cfgs(3);
2932 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2933 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2934 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2935 *nodes[0].connect_style.borrow_mut() = connect_style;
2936 *nodes[1].connect_style.borrow_mut() = connect_style;
2937 *nodes[2].connect_style.borrow_mut() = connect_style;
2939 // Create some intial channels
2940 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2941 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2943 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2944 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2945 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2947 let (_payment_preimage, payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2949 // Broadcast legit commitment tx from C on B's chain
2950 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2951 check_spends!(commitment_tx[0], chan_2.3);
2952 nodes[2].node.fail_htlc_backwards(&payment_hash);
2953 check_added_monitors!(nodes[2], 0);
2954 expect_pending_htlcs_forwardable!(nodes[2]);
2955 check_added_monitors!(nodes[2], 1);
2957 let events = nodes[2].node.get_and_clear_pending_msg_events();
2958 assert_eq!(events.len(), 1);
2960 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, .. } } => {
2961 assert!(update_add_htlcs.is_empty());
2962 assert!(!update_fail_htlcs.is_empty());
2963 assert!(update_fulfill_htlcs.is_empty());
2964 assert!(update_fail_malformed_htlcs.is_empty());
2965 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2967 _ => panic!("Unexpected event"),
2969 mine_transaction(&nodes[2], &commitment_tx[0]);
2970 check_closed_broadcast!(nodes[2], true);
2971 check_added_monitors!(nodes[2], 1);
2972 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2973 assert_eq!(node_txn.len(), 1);
2974 check_spends!(node_txn[0], chan_2.3);
2975 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2977 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2978 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2979 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2980 mine_transaction(&nodes[1], &commitment_tx[0]);
2983 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2984 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2985 assert_eq!(node_txn[0], node_txn[3]);
2986 assert_eq!(node_txn[1], node_txn[4]);
2988 check_spends!(node_txn[2], commitment_tx[0]);
2989 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2991 check_spends!(node_txn[0], chan_2.3);
2992 check_spends!(node_txn[1], node_txn[0]);
2993 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2994 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2996 timeout_tx = node_txn[2].clone();
3000 mine_transaction(&nodes[1], &timeout_tx);
3001 check_added_monitors!(nodes[1], 1);
3002 check_closed_broadcast!(nodes[1], true);
3004 // B will rebroadcast a fee-bumped timeout transaction here.
3005 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3006 assert_eq!(node_txn.len(), 1);
3007 check_spends!(node_txn[0], commitment_tx[0]);
3010 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3012 // B will rebroadcast its own holder commitment transaction here...just because
3013 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3014 assert_eq!(node_txn.len(), 1);
3015 check_spends!(node_txn[0], chan_2.3);
3018 expect_pending_htlcs_forwardable!(nodes[1]);
3019 check_added_monitors!(nodes[1], 1);
3020 let events = nodes[1].node.get_and_clear_pending_msg_events();
3021 assert_eq!(events.len(), 1);
3023 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, .. } } => {
3024 assert!(update_add_htlcs.is_empty());
3025 assert!(!update_fail_htlcs.is_empty());
3026 assert!(update_fulfill_htlcs.is_empty());
3027 assert!(update_fail_malformed_htlcs.is_empty());
3028 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3030 _ => panic!("Unexpected event"),
3033 // Broadcast legit commitment tx from B on A's chain
3034 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3035 check_spends!(commitment_tx[0], chan_1.3);
3037 mine_transaction(&nodes[0], &commitment_tx[0]);
3038 connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
3040 check_closed_broadcast!(nodes[0], true);
3041 check_added_monitors!(nodes[0], 1);
3042 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 commitment tx, ChannelMonitor : 1 timeout tx
3043 assert_eq!(node_txn.len(), 2);
3044 check_spends!(node_txn[0], chan_1.3);
3045 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3046 check_spends!(node_txn[1], commitment_tx[0]);
3047 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3051 fn test_htlc_on_chain_timeout() {
3052 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3053 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3054 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3058 fn test_simple_commitment_revoked_fail_backward() {
3059 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3060 // and fail backward accordingly.
3062 let chanmon_cfgs = create_chanmon_cfgs(3);
3063 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3064 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3065 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3067 // Create some initial channels
3068 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3069 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3071 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3072 // Get the will-be-revoked local txn from nodes[2]
3073 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3074 // Revoke the old state
3075 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3077 let (_, payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3079 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3080 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3081 check_added_monitors!(nodes[1], 1);
3082 check_closed_broadcast!(nodes[1], true);
3084 expect_pending_htlcs_forwardable!(nodes[1]);
3085 check_added_monitors!(nodes[1], 1);
3086 let events = nodes[1].node.get_and_clear_pending_msg_events();
3087 assert_eq!(events.len(), 1);
3089 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, .. } } => {
3090 assert!(update_add_htlcs.is_empty());
3091 assert_eq!(update_fail_htlcs.len(), 1);
3092 assert!(update_fulfill_htlcs.is_empty());
3093 assert!(update_fail_malformed_htlcs.is_empty());
3094 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3096 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3097 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3099 let events = nodes[0].node.get_and_clear_pending_msg_events();
3100 assert_eq!(events.len(), 1);
3102 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3103 _ => panic!("Unexpected event"),
3105 expect_payment_failed!(nodes[0], payment_hash, false);
3107 _ => panic!("Unexpected event"),
3111 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3112 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3113 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3114 // commitment transaction anymore.
3115 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3116 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3117 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3118 // technically disallowed and we should probably handle it reasonably.
3119 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3120 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3122 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3123 // commitment_signed (implying it will be in the latest remote commitment transaction).
3124 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3125 // and once they revoke the previous commitment transaction (allowing us to send a new
3126 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3127 let chanmon_cfgs = create_chanmon_cfgs(3);
3128 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3129 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3130 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3132 // Create some initial channels
3133 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3134 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3136 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 });
3137 // Get the will-be-revoked local txn from nodes[2]
3138 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3139 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3140 // Revoke the old state
3141 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3143 let value = if use_dust {
3144 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3145 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3146 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3149 let (_, first_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3150 let (_, second_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3151 let (_, third_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3153 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
3154 expect_pending_htlcs_forwardable!(nodes[2]);
3155 check_added_monitors!(nodes[2], 1);
3156 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3157 assert!(updates.update_add_htlcs.is_empty());
3158 assert!(updates.update_fulfill_htlcs.is_empty());
3159 assert!(updates.update_fail_malformed_htlcs.is_empty());
3160 assert_eq!(updates.update_fail_htlcs.len(), 1);
3161 assert!(updates.update_fee.is_none());
3162 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3163 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3164 // Drop the last RAA from 3 -> 2
3166 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
3167 expect_pending_htlcs_forwardable!(nodes[2]);
3168 check_added_monitors!(nodes[2], 1);
3169 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3170 assert!(updates.update_add_htlcs.is_empty());
3171 assert!(updates.update_fulfill_htlcs.is_empty());
3172 assert!(updates.update_fail_malformed_htlcs.is_empty());
3173 assert_eq!(updates.update_fail_htlcs.len(), 1);
3174 assert!(updates.update_fee.is_none());
3175 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3176 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3177 check_added_monitors!(nodes[1], 1);
3178 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3179 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3180 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3181 check_added_monitors!(nodes[2], 1);
3183 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
3184 expect_pending_htlcs_forwardable!(nodes[2]);
3185 check_added_monitors!(nodes[2], 1);
3186 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3187 assert!(updates.update_add_htlcs.is_empty());
3188 assert!(updates.update_fulfill_htlcs.is_empty());
3189 assert!(updates.update_fail_malformed_htlcs.is_empty());
3190 assert_eq!(updates.update_fail_htlcs.len(), 1);
3191 assert!(updates.update_fee.is_none());
3192 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3193 // At this point first_payment_hash has dropped out of the latest two commitment
3194 // transactions that nodes[1] is tracking...
3195 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3196 check_added_monitors!(nodes[1], 1);
3197 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3198 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3199 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3200 check_added_monitors!(nodes[2], 1);
3202 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3203 // on nodes[2]'s RAA.
3204 let (_, fourth_payment_hash, fourth_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3205 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3206 let logger = test_utils::TestLogger::new();
3207 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3208 nodes[1].node.send_payment(&route, fourth_payment_hash, &Some(fourth_payment_secret)).unwrap();
3209 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3210 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3211 check_added_monitors!(nodes[1], 0);
3214 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3215 // One monitor for the new revocation preimage, no second on as we won't generate a new
3216 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3217 check_added_monitors!(nodes[1], 1);
3218 let events = nodes[1].node.get_and_clear_pending_events();
3219 assert_eq!(events.len(), 1);
3221 Event::PendingHTLCsForwardable { .. } => { },
3222 _ => panic!("Unexpected event"),
3224 // Deliberately don't process the pending fail-back so they all fail back at once after
3225 // block connection just like the !deliver_bs_raa case
3228 let mut failed_htlcs = HashSet::new();
3229 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3231 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3232 check_added_monitors!(nodes[1], 1);
3233 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3235 let events = nodes[1].node.get_and_clear_pending_events();
3236 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3238 Event::PaymentFailed { ref payment_hash, .. } => {
3239 assert_eq!(*payment_hash, fourth_payment_hash);
3241 _ => panic!("Unexpected event"),
3243 if !deliver_bs_raa {
3245 Event::PendingHTLCsForwardable { .. } => { },
3246 _ => panic!("Unexpected event"),
3249 nodes[1].node.process_pending_htlc_forwards();
3250 check_added_monitors!(nodes[1], 1);
3252 let events = nodes[1].node.get_and_clear_pending_msg_events();
3253 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3254 match events[if deliver_bs_raa { 1 } else { 0 }] {
3255 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3256 _ => panic!("Unexpected event"),
3258 match events[if deliver_bs_raa { 2 } else { 1 }] {
3259 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3260 assert_eq!(channel_id, chan_2.2);
3261 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3263 _ => panic!("Unexpected event"),
3267 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, .. } } => {
3268 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3269 assert_eq!(update_add_htlcs.len(), 1);
3270 assert!(update_fulfill_htlcs.is_empty());
3271 assert!(update_fail_htlcs.is_empty());
3272 assert!(update_fail_malformed_htlcs.is_empty());
3274 _ => panic!("Unexpected event"),
3277 match events[if deliver_bs_raa { 3 } else { 2 }] {
3278 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, .. } } => {
3279 assert!(update_add_htlcs.is_empty());
3280 assert_eq!(update_fail_htlcs.len(), 3);
3281 assert!(update_fulfill_htlcs.is_empty());
3282 assert!(update_fail_malformed_htlcs.is_empty());
3283 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3285 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3286 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3287 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3289 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3291 let events = nodes[0].node.get_and_clear_pending_msg_events();
3292 // If we delivered B's RAA we got an unknown preimage error, not something
3293 // that we should update our routing table for.
3294 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3295 for event in events {
3297 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3298 _ => panic!("Unexpected event"),
3301 let events = nodes[0].node.get_and_clear_pending_events();
3302 assert_eq!(events.len(), 3);
3304 Event::PaymentFailed { ref payment_hash, .. } => {
3305 assert!(failed_htlcs.insert(payment_hash.0));
3307 _ => panic!("Unexpected event"),
3310 Event::PaymentFailed { ref payment_hash, .. } => {
3311 assert!(failed_htlcs.insert(payment_hash.0));
3313 _ => panic!("Unexpected event"),
3316 Event::PaymentFailed { ref payment_hash, .. } => {
3317 assert!(failed_htlcs.insert(payment_hash.0));
3319 _ => panic!("Unexpected event"),
3322 _ => panic!("Unexpected event"),
3325 assert!(failed_htlcs.contains(&first_payment_hash.0));
3326 assert!(failed_htlcs.contains(&second_payment_hash.0));
3327 assert!(failed_htlcs.contains(&third_payment_hash.0));
3331 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3332 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3333 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3334 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3335 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3339 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3340 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3341 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3342 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3343 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3347 fn fail_backward_pending_htlc_upon_channel_failure() {
3348 let chanmon_cfgs = create_chanmon_cfgs(2);
3349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3352 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3353 let logger = test_utils::TestLogger::new();
3355 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3357 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
3358 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3359 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3360 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
3361 check_added_monitors!(nodes[0], 1);
3363 let payment_event = {
3364 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3365 assert_eq!(events.len(), 1);
3366 SendEvent::from_event(events.remove(0))
3368 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3369 assert_eq!(payment_event.msgs.len(), 1);
3372 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3373 let (_, failed_payment_hash, failed_payment_secret) = get_payment_preimage_hash!(nodes[1]);
3375 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3376 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3377 nodes[0].node.send_payment(&route, failed_payment_hash, &Some(failed_payment_secret)).unwrap();
3378 check_added_monitors!(nodes[0], 0);
3380 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3383 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3385 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
3387 let secp_ctx = Secp256k1::new();
3388 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3389 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3390 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3391 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3392 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &Some(payment_secret), current_height).unwrap();
3393 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3394 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3396 // Send a 0-msat update_add_htlc to fail the channel.
3397 let update_add_htlc = msgs::UpdateAddHTLC {
3403 onion_routing_packet,
3405 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3408 // Check that Alice fails backward the pending HTLC from the second payment.
3409 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3410 check_closed_broadcast!(nodes[0], true);
3411 check_added_monitors!(nodes[0], 1);
3415 fn test_htlc_ignore_latest_remote_commitment() {
3416 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3417 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3418 let chanmon_cfgs = create_chanmon_cfgs(2);
3419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3421 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3422 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3424 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3425 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3426 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3427 check_closed_broadcast!(nodes[0], true);
3428 check_added_monitors!(nodes[0], 1);
3430 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3431 assert_eq!(node_txn.len(), 3);
3432 assert_eq!(node_txn[0], node_txn[1]);
3434 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3435 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3436 check_closed_broadcast!(nodes[1], true);
3437 check_added_monitors!(nodes[1], 1);
3439 // Duplicate the connect_block call since this may happen due to other listeners
3440 // registering new transactions
3441 header.prev_blockhash = header.block_hash();
3442 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[2].clone()]});
3446 fn test_force_close_fail_back() {
3447 // Check which HTLCs are failed-backwards on channel force-closure
3448 let chanmon_cfgs = create_chanmon_cfgs(3);
3449 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3450 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3451 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3452 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3453 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3454 let logger = test_utils::TestLogger::new();
3456 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
3458 let mut payment_event = {
3459 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3460 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3461 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
3462 check_added_monitors!(nodes[0], 1);
3464 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3465 assert_eq!(events.len(), 1);
3466 SendEvent::from_event(events.remove(0))
3469 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3470 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3472 expect_pending_htlcs_forwardable!(nodes[1]);
3474 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3475 assert_eq!(events_2.len(), 1);
3476 payment_event = SendEvent::from_event(events_2.remove(0));
3477 assert_eq!(payment_event.msgs.len(), 1);
3479 check_added_monitors!(nodes[1], 1);
3480 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3481 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3482 check_added_monitors!(nodes[2], 1);
3483 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3485 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3486 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3487 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3489 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3490 check_closed_broadcast!(nodes[2], true);
3491 check_added_monitors!(nodes[2], 1);
3493 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3494 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3495 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3496 // back to nodes[1] upon timeout otherwise.
3497 assert_eq!(node_txn.len(), 1);
3501 mine_transaction(&nodes[1], &tx);
3503 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3504 check_closed_broadcast!(nodes[1], true);
3505 check_added_monitors!(nodes[1], 1);
3507 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3509 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3510 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3511 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3513 mine_transaction(&nodes[2], &tx);
3514 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3515 assert_eq!(node_txn.len(), 1);
3516 assert_eq!(node_txn[0].input.len(), 1);
3517 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3518 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3519 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3521 check_spends!(node_txn[0], tx);
3525 fn test_dup_events_on_peer_disconnect() {
3526 // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3527 // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3528 // as we used to generate the event immediately upon receipt of the payment preimage in the
3529 // update_fulfill_htlc message.
3531 let chanmon_cfgs = create_chanmon_cfgs(2);
3532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3534 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3535 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3537 let payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 1000000).0;
3539 assert!(nodes[1].node.claim_funds(payment_preimage));
3540 check_added_monitors!(nodes[1], 1);
3541 let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3542 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3543 expect_payment_sent!(nodes[0], payment_preimage);
3545 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3546 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3548 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3549 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
3553 fn test_simple_peer_disconnect() {
3554 // Test that we can reconnect when there are no lost messages
3555 let chanmon_cfgs = create_chanmon_cfgs(3);
3556 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3557 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3558 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3559 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3560 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3562 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3566 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3567 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3568 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3569 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3577 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3578 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3584 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3586 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3588 let events = nodes[0].node.get_and_clear_pending_events();
3589 assert_eq!(events.len(), 2);
3591 Event::PaymentSent { payment_preimage } => {
3592 assert_eq!(payment_preimage, payment_preimage_3);
3594 _ => panic!("Unexpected event"),
3597 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3598 assert_eq!(payment_hash, payment_hash_5);
3599 assert!(rejected_by_dest);
3601 _ => panic!("Unexpected event"),
3605 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3606 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3609 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3610 // Test that we can reconnect when in-flight HTLC updates get dropped
3611 let chanmon_cfgs = create_chanmon_cfgs(2);
3612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3614 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3616 let mut as_funding_locked = None;
3617 if messages_delivered == 0 {
3618 let (funding_locked, _, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3619 as_funding_locked = Some(funding_locked);
3620 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3621 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3622 // it before the channel_reestablish message.
3624 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3627 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
3629 let logger = test_utils::TestLogger::new();
3630 let payment_event = {
3631 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3632 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3633 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3634 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3635 nodes[0].node.send_payment(&route, payment_hash_1, &Some(payment_secret_1)).unwrap();
3636 check_added_monitors!(nodes[0], 1);
3638 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3639 assert_eq!(events.len(), 1);
3640 SendEvent::from_event(events.remove(0))
3642 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3644 if messages_delivered < 2 {
3645 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3647 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3648 if messages_delivered >= 3 {
3649 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3650 check_added_monitors!(nodes[1], 1);
3651 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3653 if messages_delivered >= 4 {
3654 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3655 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3656 check_added_monitors!(nodes[0], 1);
3658 if messages_delivered >= 5 {
3659 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3660 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3661 // No commitment_signed so get_event_msg's assert(len == 1) passes
3662 check_added_monitors!(nodes[0], 1);
3664 if messages_delivered >= 6 {
3665 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3666 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3667 check_added_monitors!(nodes[1], 1);
3674 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3675 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3676 if messages_delivered < 3 {
3677 if simulate_broken_lnd {
3678 // lnd has a long-standing bug where they send a funding_locked prior to a
3679 // channel_reestablish if you reconnect prior to funding_locked time.
3681 // Here we simulate that behavior, delivering a funding_locked immediately on
3682 // reconnect. Note that we don't bother skipping the now-duplicate funding_locked sent
3683 // in `reconnect_nodes` but we currently don't fail based on that.
3685 // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3686 nodes[1].node.handle_funding_locked(&nodes[0].node.get_our_node_id(), &as_funding_locked.as_ref().unwrap().0);
3688 // Even if the funding_locked messages get exchanged, as long as nothing further was
3689 // received on either side, both sides will need to resend them.
3690 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3691 } else if messages_delivered == 3 {
3692 // nodes[0] still wants its RAA + commitment_signed
3693 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3694 } else if messages_delivered == 4 {
3695 // nodes[0] still wants its commitment_signed
3696 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3697 } else if messages_delivered == 5 {
3698 // nodes[1] still wants its final RAA
3699 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3700 } else if messages_delivered == 6 {
3701 // Everything was delivered...
3702 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3705 let events_1 = nodes[1].node.get_and_clear_pending_events();
3706 assert_eq!(events_1.len(), 1);
3708 Event::PendingHTLCsForwardable { .. } => { },
3709 _ => panic!("Unexpected event"),
3712 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3713 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3714 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3716 nodes[1].node.process_pending_htlc_forwards();
3718 let events_2 = nodes[1].node.get_and_clear_pending_events();
3719 assert_eq!(events_2.len(), 1);
3721 Event::PaymentReceived { ref payment_hash, ref payment_preimage, ref payment_secret, amt, user_payment_id: _ } => {
3722 assert_eq!(payment_hash_1, *payment_hash);
3723 assert!(payment_preimage.is_none());
3724 assert_eq!(payment_secret_1, *payment_secret);
3725 assert_eq!(amt, 1000000);
3727 _ => panic!("Unexpected event"),
3730 nodes[1].node.claim_funds(payment_preimage_1);
3731 check_added_monitors!(nodes[1], 1);
3733 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3734 assert_eq!(events_3.len(), 1);
3735 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3736 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3737 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3738 assert!(updates.update_add_htlcs.is_empty());
3739 assert!(updates.update_fail_htlcs.is_empty());
3740 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3741 assert!(updates.update_fail_malformed_htlcs.is_empty());
3742 assert!(updates.update_fee.is_none());
3743 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3745 _ => panic!("Unexpected event"),
3748 if messages_delivered >= 1 {
3749 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3751 let events_4 = nodes[0].node.get_and_clear_pending_events();
3752 assert_eq!(events_4.len(), 1);
3754 Event::PaymentSent { ref payment_preimage } => {
3755 assert_eq!(payment_preimage_1, *payment_preimage);
3757 _ => panic!("Unexpected event"),
3760 if messages_delivered >= 2 {
3761 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3762 check_added_monitors!(nodes[0], 1);
3763 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3765 if messages_delivered >= 3 {
3766 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3767 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3768 check_added_monitors!(nodes[1], 1);
3770 if messages_delivered >= 4 {
3771 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3772 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3773 // No commitment_signed so get_event_msg's assert(len == 1) passes
3774 check_added_monitors!(nodes[1], 1);
3776 if messages_delivered >= 5 {
3777 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3778 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3779 check_added_monitors!(nodes[0], 1);
3786 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3787 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3788 if messages_delivered < 2 {
3789 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3790 if messages_delivered < 1 {
3791 let events_4 = nodes[0].node.get_and_clear_pending_events();
3792 assert_eq!(events_4.len(), 1);
3794 Event::PaymentSent { ref payment_preimage } => {
3795 assert_eq!(payment_preimage_1, *payment_preimage);
3797 _ => panic!("Unexpected event"),
3800 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3802 } else if messages_delivered == 2 {
3803 // nodes[0] still wants its RAA + commitment_signed
3804 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3805 } else if messages_delivered == 3 {
3806 // nodes[0] still wants its commitment_signed
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3808 } else if messages_delivered == 4 {
3809 // nodes[1] still wants its final RAA
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3811 } else if messages_delivered == 5 {
3812 // Everything was delivered...
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820 // Channel should still work fine...
3821 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3822 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3823 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3824 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3825 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3826 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3830 fn test_drop_messages_peer_disconnect_a() {
3831 do_test_drop_messages_peer_disconnect(0, true);
3832 do_test_drop_messages_peer_disconnect(0, false);
3833 do_test_drop_messages_peer_disconnect(1, false);
3834 do_test_drop_messages_peer_disconnect(2, false);
3838 fn test_drop_messages_peer_disconnect_b() {
3839 do_test_drop_messages_peer_disconnect(3, false);
3840 do_test_drop_messages_peer_disconnect(4, false);
3841 do_test_drop_messages_peer_disconnect(5, false);
3842 do_test_drop_messages_peer_disconnect(6, false);
3846 fn test_funding_peer_disconnect() {
3847 // Test that we can lock in our funding tx while disconnected
3848 let chanmon_cfgs = create_chanmon_cfgs(2);
3849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3851 let persister: test_utils::TestPersister;
3852 let new_chain_monitor: test_utils::TestChainMonitor;
3853 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3854 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3855 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3857 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3858 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3860 confirm_transaction(&nodes[0], &tx);
3861 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3862 assert_eq!(events_1.len(), 1);
3864 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3865 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3867 _ => panic!("Unexpected event"),
3870 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3872 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3873 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3875 confirm_transaction(&nodes[1], &tx);
3876 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3877 assert_eq!(events_2.len(), 2);
3878 let funding_locked = match events_2[0] {
3879 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3880 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3883 _ => panic!("Unexpected event"),
3885 let bs_announcement_sigs = match events_2[1] {
3886 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3887 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3890 _ => panic!("Unexpected event"),
3893 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3895 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3896 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3897 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3898 assert_eq!(events_3.len(), 2);
3899 let as_announcement_sigs = match events_3[0] {
3900 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3901 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3904 _ => panic!("Unexpected event"),
3906 let (as_announcement, as_update) = match events_3[1] {
3907 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3908 (msg.clone(), update_msg.clone())
3910 _ => panic!("Unexpected event"),
3913 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3914 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3915 assert_eq!(events_4.len(), 1);
3916 let (_, bs_update) = match events_4[0] {
3917 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3918 (msg.clone(), update_msg.clone())
3920 _ => panic!("Unexpected event"),
3923 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3924 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3925 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3927 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3928 let logger = test_utils::TestLogger::new();
3929 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3930 let (payment_preimage, _, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3931 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3933 // Check that after deserialization and reconnection we can still generate an identical
3934 // channel_announcement from the cached signatures.
3935 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3937 let nodes_0_serialized = nodes[0].node.encode();
3938 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3939 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
3941 persister = test_utils::TestPersister::new();
3942 let keys_manager = &chanmon_cfgs[0].keys_manager;
3943 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);
3944 nodes[0].chain_monitor = &new_chain_monitor;
3945 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3946 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
3947 &mut chan_0_monitor_read, keys_manager).unwrap();
3948 assert!(chan_0_monitor_read.is_empty());
3950 let mut nodes_0_read = &nodes_0_serialized[..];
3951 let (_, nodes_0_deserialized_tmp) = {
3952 let mut channel_monitors = HashMap::new();
3953 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
3954 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3955 default_config: UserConfig::default(),
3957 fee_estimator: node_cfgs[0].fee_estimator,
3958 chain_monitor: nodes[0].chain_monitor,
3959 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3960 logger: nodes[0].logger,
3964 nodes_0_deserialized = nodes_0_deserialized_tmp;
3965 assert!(nodes_0_read.is_empty());
3967 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
3968 nodes[0].node = &nodes_0_deserialized;
3969 check_added_monitors!(nodes[0], 1);
3971 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3973 // as_announcement should be re-generated exactly by broadcast_node_announcement.
3974 nodes[0].node.broadcast_node_announcement([0, 0, 0], [0; 32], Vec::new());
3975 let msgs = nodes[0].node.get_and_clear_pending_msg_events();
3976 let mut found_announcement = false;
3977 for event in msgs.iter() {
3979 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, .. } => {
3980 if *msg == as_announcement { found_announcement = true; }
3982 MessageSendEvent::BroadcastNodeAnnouncement { .. } => {},
3983 _ => panic!("Unexpected event"),
3986 assert!(found_announcement);
3990 fn test_drop_messages_peer_disconnect_dual_htlc() {
3991 // Test that we can handle reconnecting when both sides of a channel have pending
3992 // commitment_updates when we disconnect.
3993 let chanmon_cfgs = create_chanmon_cfgs(2);
3994 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3995 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3996 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3997 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3998 let logger = test_utils::TestLogger::new();
4000 let (payment_preimage_1, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4002 // Now try to send a second payment which will fail to send
4003 let (payment_preimage_2, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
4004 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4005 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
4006 nodes[0].node.send_payment(&route, payment_hash_2, &Some(payment_secret_2)).unwrap();
4007 check_added_monitors!(nodes[0], 1);
4009 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4010 assert_eq!(events_1.len(), 1);
4012 MessageSendEvent::UpdateHTLCs { .. } => {},
4013 _ => panic!("Unexpected event"),
4016 assert!(nodes[1].node.claim_funds(payment_preimage_1));
4017 check_added_monitors!(nodes[1], 1);
4019 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4020 assert_eq!(events_2.len(), 1);
4022 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 } } => {
4023 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4024 assert!(update_add_htlcs.is_empty());
4025 assert_eq!(update_fulfill_htlcs.len(), 1);
4026 assert!(update_fail_htlcs.is_empty());
4027 assert!(update_fail_malformed_htlcs.is_empty());
4028 assert!(update_fee.is_none());
4030 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4031 let events_3 = nodes[0].node.get_and_clear_pending_events();
4032 assert_eq!(events_3.len(), 1);
4034 Event::PaymentSent { ref payment_preimage } => {
4035 assert_eq!(*payment_preimage, payment_preimage_1);
4037 _ => panic!("Unexpected event"),
4040 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4041 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4042 // No commitment_signed so get_event_msg's assert(len == 1) passes
4043 check_added_monitors!(nodes[0], 1);
4045 _ => panic!("Unexpected event"),
4048 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4049 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4051 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4052 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4053 assert_eq!(reestablish_1.len(), 1);
4054 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4055 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4056 assert_eq!(reestablish_2.len(), 1);
4058 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4059 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4060 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4061 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4063 assert!(as_resp.0.is_none());
4064 assert!(bs_resp.0.is_none());
4066 assert!(bs_resp.1.is_none());
4067 assert!(bs_resp.2.is_none());
4069 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4071 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4072 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4073 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4074 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4075 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4076 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4077 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4078 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4079 // No commitment_signed so get_event_msg's assert(len == 1) passes
4080 check_added_monitors!(nodes[1], 1);
4082 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4083 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4084 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4085 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4086 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4087 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4088 assert!(bs_second_commitment_signed.update_fee.is_none());
4089 check_added_monitors!(nodes[1], 1);
4091 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4092 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4093 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4094 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4095 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4096 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4097 assert!(as_commitment_signed.update_fee.is_none());
4098 check_added_monitors!(nodes[0], 1);
4100 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4101 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4102 // No commitment_signed so get_event_msg's assert(len == 1) passes
4103 check_added_monitors!(nodes[0], 1);
4105 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4106 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4107 // No commitment_signed so get_event_msg's assert(len == 1) passes
4108 check_added_monitors!(nodes[1], 1);
4110 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4111 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4112 check_added_monitors!(nodes[1], 1);
4114 expect_pending_htlcs_forwardable!(nodes[1]);
4116 let events_5 = nodes[1].node.get_and_clear_pending_events();
4117 assert_eq!(events_5.len(), 1);
4119 Event::PaymentReceived { ref payment_hash, ref payment_preimage, ref payment_secret, amt: _, user_payment_id: _ } => {
4120 assert_eq!(payment_hash_2, *payment_hash);
4121 assert!(payment_preimage.is_none());
4122 assert_eq!(payment_secret_2, *payment_secret);
4124 _ => panic!("Unexpected event"),
4127 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4128 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4129 check_added_monitors!(nodes[0], 1);
4131 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4134 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4135 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4136 // to avoid our counterparty failing the channel.
4137 let chanmon_cfgs = create_chanmon_cfgs(2);
4138 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4139 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4140 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4142 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4143 let logger = test_utils::TestLogger::new();
4145 let our_payment_hash = if send_partial_mpp {
4146 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4147 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4148 let (_, our_payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[1]);
4149 // Use the utility function send_payment_along_path to send the payment with MPP data which
4150 // indicates there are more HTLCs coming.
4151 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.
4152 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4153 check_added_monitors!(nodes[0], 1);
4154 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4155 assert_eq!(events.len(), 1);
4156 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4157 // hop should *not* yet generate any PaymentReceived event(s).
4158 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, payment_secret, events.drain(..).next().unwrap(), false);
4161 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4164 let mut block = Block {
4165 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4168 connect_block(&nodes[0], &block);
4169 connect_block(&nodes[1], &block);
4170 let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4171 for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4172 block.header.prev_blockhash = block.block_hash();
4173 connect_block(&nodes[0], &block);
4174 connect_block(&nodes[1], &block);
4177 expect_pending_htlcs_forwardable!(nodes[1]);
4179 check_added_monitors!(nodes[1], 1);
4180 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4181 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4182 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4183 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4184 assert!(htlc_timeout_updates.update_fee.is_none());
4186 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4187 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4188 // 100_000 msat as u64, followed by the height at which we failed back above
4189 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4190 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(block_count - 1));
4191 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4195 fn test_htlc_timeout() {
4196 do_test_htlc_timeout(true);
4197 do_test_htlc_timeout(false);
4200 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4201 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4202 let chanmon_cfgs = create_chanmon_cfgs(3);
4203 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4204 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4205 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4206 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4207 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4209 // Make sure all nodes are at the same starting height
4210 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4211 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4212 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4214 let logger = test_utils::TestLogger::new();
4216 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4217 let (_, first_payment_hash, first_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4219 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4220 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4221 nodes[1].node.send_payment(&route, first_payment_hash, &Some(first_payment_secret)).unwrap();
4223 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4224 check_added_monitors!(nodes[1], 1);
4226 // Now attempt to route a second payment, which should be placed in the holding cell
4227 let (_, second_payment_hash, second_payment_secret) = get_payment_preimage_hash!(nodes[2]);
4229 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4230 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4231 nodes[0].node.send_payment(&route, second_payment_hash, &Some(first_payment_secret)).unwrap();
4232 check_added_monitors!(nodes[0], 1);
4233 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4234 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4235 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4236 expect_pending_htlcs_forwardable!(nodes[1]);
4237 check_added_monitors!(nodes[1], 0);
4239 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4240 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4241 nodes[1].node.send_payment(&route, second_payment_hash, &Some(second_payment_secret)).unwrap();
4242 check_added_monitors!(nodes[1], 0);
4245 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4246 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4247 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4248 connect_blocks(&nodes[1], 1);
4251 expect_pending_htlcs_forwardable!(nodes[1]);
4252 check_added_monitors!(nodes[1], 1);
4253 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4254 assert_eq!(fail_commit.len(), 1);
4255 match fail_commit[0] {
4256 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4257 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4258 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4260 _ => unreachable!(),
4262 expect_payment_failed!(nodes[0], second_payment_hash, false);
4263 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4265 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4266 _ => panic!("Unexpected event"),
4269 panic!("Unexpected event");
4272 expect_payment_failed!(nodes[1], second_payment_hash, true);
4277 fn test_holding_cell_htlc_add_timeouts() {
4278 do_test_holding_cell_htlc_add_timeouts(false);
4279 do_test_holding_cell_htlc_add_timeouts(true);
4283 fn test_invalid_channel_announcement() {
4284 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4285 let secp_ctx = Secp256k1::new();
4286 let chanmon_cfgs = create_chanmon_cfgs(2);
4287 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4288 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4289 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4291 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4293 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4294 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4295 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4296 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4298 nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4300 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4301 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4303 let as_network_key = nodes[0].node.get_our_node_id();
4304 let bs_network_key = nodes[1].node.get_our_node_id();
4306 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4308 let mut chan_announcement;
4310 macro_rules! dummy_unsigned_msg {
4312 msgs::UnsignedChannelAnnouncement {
4313 features: ChannelFeatures::known(),
4314 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4315 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4316 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4317 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4318 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4319 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4320 excess_data: Vec::new(),
4325 macro_rules! sign_msg {
4326 ($unsigned_msg: expr) => {
4327 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4328 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4329 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4330 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4331 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4332 chan_announcement = msgs::ChannelAnnouncement {
4333 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4334 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4335 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4336 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4337 contents: $unsigned_msg
4342 let unsigned_msg = dummy_unsigned_msg!();
4343 sign_msg!(unsigned_msg);
4344 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4345 let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
4347 // Configured with Network::Testnet
4348 let mut unsigned_msg = dummy_unsigned_msg!();
4349 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4350 sign_msg!(unsigned_msg);
4351 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4353 let mut unsigned_msg = dummy_unsigned_msg!();
4354 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4355 sign_msg!(unsigned_msg);
4356 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4360 fn test_no_txn_manager_serialize_deserialize() {
4361 let chanmon_cfgs = create_chanmon_cfgs(2);
4362 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4363 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4364 let logger: test_utils::TestLogger;
4365 let fee_estimator: test_utils::TestFeeEstimator;
4366 let persister: test_utils::TestPersister;
4367 let new_chain_monitor: test_utils::TestChainMonitor;
4368 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4371 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4373 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4375 let nodes_0_serialized = nodes[0].node.encode();
4376 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4377 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4379 logger = test_utils::TestLogger::new();
4380 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4381 persister = test_utils::TestPersister::new();
4382 let keys_manager = &chanmon_cfgs[0].keys_manager;
4383 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4384 nodes[0].chain_monitor = &new_chain_monitor;
4385 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4386 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4387 &mut chan_0_monitor_read, keys_manager).unwrap();
4388 assert!(chan_0_monitor_read.is_empty());
4390 let mut nodes_0_read = &nodes_0_serialized[..];
4391 let config = UserConfig::default();
4392 let (_, nodes_0_deserialized_tmp) = {
4393 let mut channel_monitors = HashMap::new();
4394 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4395 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4396 default_config: config,
4398 fee_estimator: &fee_estimator,
4399 chain_monitor: nodes[0].chain_monitor,
4400 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4405 nodes_0_deserialized = nodes_0_deserialized_tmp;
4406 assert!(nodes_0_read.is_empty());
4408 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4409 nodes[0].node = &nodes_0_deserialized;
4410 assert_eq!(nodes[0].node.list_channels().len(), 1);
4411 check_added_monitors!(nodes[0], 1);
4413 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4414 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4415 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4416 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4418 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4419 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4420 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4421 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4423 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4424 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4425 for node in nodes.iter() {
4426 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4427 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4428 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4431 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4435 fn test_dup_htlc_onchain_fails_on_reload() {
4436 // When a Channel is closed, any outbound HTLCs which were relayed through it are simply
4437 // dropped when the Channel is. From there, the ChannelManager relies on the ChannelMonitor
4438 // having a copy of the relevant fail-/claim-back data and processes the HTLC fail/claim when
4439 // the ChannelMonitor tells it to.
4441 // If, due to an on-chain event, an HTLC is failed/claimed, and then we serialize the
4442 // ChannelManager, we generally expect there not to be a duplicate HTLC fail/claim (eg via a
4443 // PaymentFailed event appearing). However, because we may not serialize the relevant
4444 // ChannelMonitor at the same time, this isn't strictly guaranteed. In order to provide this
4445 // consistency, the ChannelManager explicitly tracks pending-onchain-resolution outbound HTLCs
4446 // and de-duplicates ChannelMonitor events.
4448 // This tests that explicit tracking behavior.
4449 let chanmon_cfgs = create_chanmon_cfgs(2);
4450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4451 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4452 let persister: test_utils::TestPersister;
4453 let new_chain_monitor: test_utils::TestChainMonitor;
4454 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4455 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4457 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4459 // Route a payment, but force-close the channel before the HTLC fulfill message arrives at
4461 let (payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 10000000);
4462 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
4463 check_closed_broadcast!(nodes[0], true);
4464 check_added_monitors!(nodes[0], 1);
4466 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4467 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4469 // Connect blocks until the CLTV timeout is up so that we get an HTLC-Timeout transaction
4470 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
4471 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4472 assert_eq!(node_txn.len(), 3);
4473 assert_eq!(node_txn[0], node_txn[1]);
4475 assert!(nodes[1].node.claim_funds(payment_preimage));
4476 check_added_monitors!(nodes[1], 1);
4478 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4479 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4480 check_closed_broadcast!(nodes[1], true);
4481 check_added_monitors!(nodes[1], 1);
4482 let claim_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4484 header.prev_blockhash = nodes[0].best_block_hash();
4485 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone(), node_txn[2].clone()]});
4487 // Serialize out the ChannelMonitor before connecting the on-chain claim transactions. This is
4488 // fairly normal behavior as ChannelMonitor(s) are often not re-serialized when on-chain events
4489 // happen, unlike ChannelManager which tends to be re-serialized after any relevant event(s).
4490 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4491 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4493 header.prev_blockhash = nodes[0].best_block_hash();
4494 let claim_block = Block { header, txdata: claim_txn};
4495 connect_block(&nodes[0], &claim_block);
4496 expect_payment_sent!(nodes[0], payment_preimage);
4498 // ChannelManagers generally get re-serialized after any relevant event(s). Since we just
4499 // connected a highly-relevant block, it likely gets serialized out now.
4500 let mut chan_manager_serialized = test_utils::TestVecWriter(Vec::new());
4501 nodes[0].node.write(&mut chan_manager_serialized).unwrap();
4503 // Now reload nodes[0]...
4504 persister = test_utils::TestPersister::new();
4505 let keys_manager = &chanmon_cfgs[0].keys_manager;
4506 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);
4507 nodes[0].chain_monitor = &new_chain_monitor;
4508 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4509 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4510 &mut chan_0_monitor_read, keys_manager).unwrap();
4511 assert!(chan_0_monitor_read.is_empty());
4513 let (_, nodes_0_deserialized_tmp) = {
4514 let mut channel_monitors = HashMap::new();
4515 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4516 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>
4517 ::read(&mut std::io::Cursor::new(&chan_manager_serialized.0[..]), ChannelManagerReadArgs {
4518 default_config: Default::default(),
4520 fee_estimator: node_cfgs[0].fee_estimator,
4521 chain_monitor: nodes[0].chain_monitor,
4522 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4523 logger: nodes[0].logger,
4527 nodes_0_deserialized = nodes_0_deserialized_tmp;
4529 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4530 check_added_monitors!(nodes[0], 1);
4531 nodes[0].node = &nodes_0_deserialized;
4533 // Note that if we re-connect the block which exposed nodes[0] to the payment preimage (but
4534 // which the current ChannelMonitor has not seen), the ChannelManager's de-duplication of
4535 // payment events should kick in, leaving us with no pending events here.
4536 let height = nodes[0].blocks.lock().unwrap().len() as u32 - 1;
4537 nodes[0].chain_monitor.chain_monitor.block_connected(&claim_block, height);
4538 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
4542 fn test_manager_serialize_deserialize_events() {
4543 // This test makes sure the events field in ChannelManager survives de/serialization
4544 let chanmon_cfgs = create_chanmon_cfgs(2);
4545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4547 let fee_estimator: test_utils::TestFeeEstimator;
4548 let persister: test_utils::TestPersister;
4549 let logger: test_utils::TestLogger;
4550 let new_chain_monitor: test_utils::TestChainMonitor;
4551 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4552 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4554 // Start creating a channel, but stop right before broadcasting the funding transaction
4555 let channel_value = 100000;
4556 let push_msat = 10001;
4557 let a_flags = InitFeatures::known();
4558 let b_flags = InitFeatures::known();
4559 let node_a = nodes.remove(0);
4560 let node_b = nodes.remove(0);
4561 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4562 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()));
4563 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()));
4565 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4567 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4568 check_added_monitors!(node_a, 0);
4570 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()));
4572 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4573 assert_eq!(added_monitors.len(), 1);
4574 assert_eq!(added_monitors[0].0, funding_output);
4575 added_monitors.clear();
4578 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()));
4580 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4581 assert_eq!(added_monitors.len(), 1);
4582 assert_eq!(added_monitors[0].0, funding_output);
4583 added_monitors.clear();
4585 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4590 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4591 let nodes_0_serialized = nodes[0].node.encode();
4592 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4593 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4595 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4596 logger = test_utils::TestLogger::new();
4597 persister = test_utils::TestPersister::new();
4598 let keys_manager = &chanmon_cfgs[0].keys_manager;
4599 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4600 nodes[0].chain_monitor = &new_chain_monitor;
4601 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4602 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4603 &mut chan_0_monitor_read, keys_manager).unwrap();
4604 assert!(chan_0_monitor_read.is_empty());
4606 let mut nodes_0_read = &nodes_0_serialized[..];
4607 let config = UserConfig::default();
4608 let (_, nodes_0_deserialized_tmp) = {
4609 let mut channel_monitors = HashMap::new();
4610 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4611 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4612 default_config: config,
4614 fee_estimator: &fee_estimator,
4615 chain_monitor: nodes[0].chain_monitor,
4616 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4621 nodes_0_deserialized = nodes_0_deserialized_tmp;
4622 assert!(nodes_0_read.is_empty());
4624 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4626 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4627 nodes[0].node = &nodes_0_deserialized;
4629 // After deserializing, make sure the funding_transaction is still held by the channel manager
4630 let events_4 = nodes[0].node.get_and_clear_pending_events();
4631 assert_eq!(events_4.len(), 0);
4632 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4633 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4635 // Make sure the channel is functioning as though the de/serialization never happened
4636 assert_eq!(nodes[0].node.list_channels().len(), 1);
4637 check_added_monitors!(nodes[0], 1);
4639 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4640 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4641 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4642 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4644 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4645 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4646 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4647 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4649 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4650 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4651 for node in nodes.iter() {
4652 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4653 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4654 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4657 send_payment(&nodes[0], &[&nodes[1]], 1000000);
4661 fn test_simple_manager_serialize_deserialize() {
4662 let chanmon_cfgs = create_chanmon_cfgs(2);
4663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4665 let logger: test_utils::TestLogger;
4666 let fee_estimator: test_utils::TestFeeEstimator;
4667 let persister: test_utils::TestPersister;
4668 let new_chain_monitor: test_utils::TestChainMonitor;
4669 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4670 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4671 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4673 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4674 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4676 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4678 let nodes_0_serialized = nodes[0].node.encode();
4679 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4680 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4682 logger = test_utils::TestLogger::new();
4683 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4684 persister = test_utils::TestPersister::new();
4685 let keys_manager = &chanmon_cfgs[0].keys_manager;
4686 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4687 nodes[0].chain_monitor = &new_chain_monitor;
4688 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4689 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4690 &mut chan_0_monitor_read, keys_manager).unwrap();
4691 assert!(chan_0_monitor_read.is_empty());
4693 let mut nodes_0_read = &nodes_0_serialized[..];
4694 let (_, nodes_0_deserialized_tmp) = {
4695 let mut channel_monitors = HashMap::new();
4696 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4697 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4698 default_config: UserConfig::default(),
4700 fee_estimator: &fee_estimator,
4701 chain_monitor: nodes[0].chain_monitor,
4702 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4707 nodes_0_deserialized = nodes_0_deserialized_tmp;
4708 assert!(nodes_0_read.is_empty());
4710 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4711 nodes[0].node = &nodes_0_deserialized;
4712 check_added_monitors!(nodes[0], 1);
4714 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4716 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4717 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
4721 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4722 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4723 let chanmon_cfgs = create_chanmon_cfgs(4);
4724 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4725 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4726 let logger: test_utils::TestLogger;
4727 let fee_estimator: test_utils::TestFeeEstimator;
4728 let persister: test_utils::TestPersister;
4729 let new_chain_monitor: test_utils::TestChainMonitor;
4730 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4731 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4732 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4733 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4734 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4736 let mut node_0_stale_monitors_serialized = Vec::new();
4737 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4738 let mut writer = test_utils::TestVecWriter(Vec::new());
4739 monitor.1.write(&mut writer).unwrap();
4740 node_0_stale_monitors_serialized.push(writer.0);
4743 let (our_payment_preimage, _, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4745 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4746 let nodes_0_serialized = nodes[0].node.encode();
4748 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4749 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4750 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4751 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4753 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4755 let mut node_0_monitors_serialized = Vec::new();
4756 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4757 let mut writer = test_utils::TestVecWriter(Vec::new());
4758 monitor.1.write(&mut writer).unwrap();
4759 node_0_monitors_serialized.push(writer.0);
4762 logger = test_utils::TestLogger::new();
4763 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4764 persister = test_utils::TestPersister::new();
4765 let keys_manager = &chanmon_cfgs[0].keys_manager;
4766 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4767 nodes[0].chain_monitor = &new_chain_monitor;
4770 let mut node_0_stale_monitors = Vec::new();
4771 for serialized in node_0_stale_monitors_serialized.iter() {
4772 let mut read = &serialized[..];
4773 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4774 assert!(read.is_empty());
4775 node_0_stale_monitors.push(monitor);
4778 let mut node_0_monitors = Vec::new();
4779 for serialized in node_0_monitors_serialized.iter() {
4780 let mut read = &serialized[..];
4781 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4782 assert!(read.is_empty());
4783 node_0_monitors.push(monitor);
4786 let mut nodes_0_read = &nodes_0_serialized[..];
4787 if let Err(msgs::DecodeError::InvalidValue) =
4788 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4789 default_config: UserConfig::default(),
4791 fee_estimator: &fee_estimator,
4792 chain_monitor: nodes[0].chain_monitor,
4793 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4795 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4797 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4800 let mut nodes_0_read = &nodes_0_serialized[..];
4801 let (_, nodes_0_deserialized_tmp) =
4802 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4803 default_config: UserConfig::default(),
4805 fee_estimator: &fee_estimator,
4806 chain_monitor: nodes[0].chain_monitor,
4807 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4809 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4811 nodes_0_deserialized = nodes_0_deserialized_tmp;
4812 assert!(nodes_0_read.is_empty());
4814 { // Channel close should result in a commitment tx
4815 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4816 assert_eq!(txn.len(), 1);
4817 check_spends!(txn[0], funding_tx);
4818 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4821 for monitor in node_0_monitors.drain(..) {
4822 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4823 check_added_monitors!(nodes[0], 1);
4825 nodes[0].node = &nodes_0_deserialized;
4827 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4828 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4829 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4830 //... and we can even still claim the payment!
4831 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
4833 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4834 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4835 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4836 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4837 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4838 assert_eq!(msg_events.len(), 1);
4839 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4841 &ErrorAction::SendErrorMessage { ref msg } => {
4842 assert_eq!(msg.channel_id, channel_id);
4844 _ => panic!("Unexpected event!"),
4849 macro_rules! check_spendable_outputs {
4850 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4852 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4853 let mut txn = Vec::new();
4854 let mut all_outputs = Vec::new();
4855 let secp_ctx = Secp256k1::new();
4856 for event in events.drain(..) {
4858 Event::SpendableOutputs { mut outputs } => {
4859 for outp in outputs.drain(..) {
4860 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4861 all_outputs.push(outp);
4864 _ => panic!("Unexpected event"),
4867 if all_outputs.len() > 1 {
4868 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) {
4878 fn test_claim_sizeable_push_msat() {
4879 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4880 let chanmon_cfgs = create_chanmon_cfgs(2);
4881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4883 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4885 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4886 nodes[1].node.force_close_channel(&chan.2).unwrap();
4887 check_closed_broadcast!(nodes[1], true);
4888 check_added_monitors!(nodes[1], 1);
4889 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4890 assert_eq!(node_txn.len(), 1);
4891 check_spends!(node_txn[0], chan.3);
4892 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
4894 mine_transaction(&nodes[1], &node_txn[0]);
4895 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4897 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4898 assert_eq!(spend_txn.len(), 1);
4899 assert_eq!(spend_txn[0].input.len(), 1);
4900 check_spends!(spend_txn[0], node_txn[0]);
4901 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
4905 fn test_claim_on_remote_sizeable_push_msat() {
4906 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4907 // to_remote output is encumbered by a P2WPKH
4908 let chanmon_cfgs = create_chanmon_cfgs(2);
4909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4911 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4913 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4914 nodes[0].node.force_close_channel(&chan.2).unwrap();
4915 check_closed_broadcast!(nodes[0], true);
4916 check_added_monitors!(nodes[0], 1);
4918 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4919 assert_eq!(node_txn.len(), 1);
4920 check_spends!(node_txn[0], chan.3);
4921 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
4923 mine_transaction(&nodes[1], &node_txn[0]);
4924 check_closed_broadcast!(nodes[1], true);
4925 check_added_monitors!(nodes[1], 1);
4926 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4928 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4929 assert_eq!(spend_txn.len(), 1);
4930 check_spends!(spend_txn[0], node_txn[0]);
4934 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4935 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4936 // to_remote output is encumbered by a P2WPKH
4938 let chanmon_cfgs = create_chanmon_cfgs(2);
4939 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4940 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4941 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4943 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4944 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4945 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4946 assert_eq!(revoked_local_txn[0].input.len(), 1);
4947 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4949 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4950 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4951 check_closed_broadcast!(nodes[1], true);
4952 check_added_monitors!(nodes[1], 1);
4954 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4955 mine_transaction(&nodes[1], &node_txn[0]);
4956 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4958 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4959 assert_eq!(spend_txn.len(), 3);
4960 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4961 check_spends!(spend_txn[1], node_txn[0]);
4962 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4966 fn test_static_spendable_outputs_preimage_tx() {
4967 let chanmon_cfgs = create_chanmon_cfgs(2);
4968 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4969 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4970 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4972 // Create some initial channels
4973 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4975 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4977 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4978 assert_eq!(commitment_tx[0].input.len(), 1);
4979 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4981 // Settle A's commitment tx on B's chain
4982 assert!(nodes[1].node.claim_funds(payment_preimage));
4983 check_added_monitors!(nodes[1], 1);
4984 mine_transaction(&nodes[1], &commitment_tx[0]);
4985 check_added_monitors!(nodes[1], 1);
4986 let events = nodes[1].node.get_and_clear_pending_msg_events();
4988 MessageSendEvent::UpdateHTLCs { .. } => {},
4989 _ => panic!("Unexpected event"),
4992 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4993 _ => panic!("Unexepected event"),
4996 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4997 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4998 assert_eq!(node_txn.len(), 3);
4999 check_spends!(node_txn[0], commitment_tx[0]);
5000 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5001 check_spends!(node_txn[1], chan_1.3);
5002 check_spends!(node_txn[2], node_txn[1]);
5004 mine_transaction(&nodes[1], &node_txn[0]);
5005 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5007 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5008 assert_eq!(spend_txn.len(), 1);
5009 check_spends!(spend_txn[0], node_txn[0]);
5013 fn test_static_spendable_outputs_timeout_tx() {
5014 let chanmon_cfgs = create_chanmon_cfgs(2);
5015 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5016 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5017 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5019 // Create some initial channels
5020 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5022 // Rebalance the network a bit by relaying one payment through all the channels ...
5023 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5025 let (_, our_payment_hash, _) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
5027 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5028 assert_eq!(commitment_tx[0].input.len(), 1);
5029 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
5031 // Settle A's commitment tx on B' chain
5032 mine_transaction(&nodes[1], &commitment_tx[0]);
5033 check_added_monitors!(nodes[1], 1);
5034 let events = nodes[1].node.get_and_clear_pending_msg_events();
5036 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5037 _ => panic!("Unexpected event"),
5039 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5041 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
5042 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
5043 assert_eq!(node_txn.len(), 2); // ChannelManager : 1 local commitent tx, ChannelMonitor: timeout tx
5044 check_spends!(node_txn[0], chan_1.3.clone());
5045 check_spends!(node_txn[1], commitment_tx[0].clone());
5046 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5048 mine_transaction(&nodes[1], &node_txn[1]);
5049 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5050 expect_payment_failed!(nodes[1], our_payment_hash, true);
5052 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5053 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
5054 check_spends!(spend_txn[0], commitment_tx[0]);
5055 check_spends!(spend_txn[1], node_txn[1]);
5056 check_spends!(spend_txn[2], node_txn[1], commitment_tx[0]); // All outputs
5060 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5061 let chanmon_cfgs = create_chanmon_cfgs(2);
5062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5064 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5066 // Create some initial channels
5067 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5069 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5070 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5071 assert_eq!(revoked_local_txn[0].input.len(), 1);
5072 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5074 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5076 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5077 check_closed_broadcast!(nodes[1], true);
5078 check_added_monitors!(nodes[1], 1);
5080 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5081 assert_eq!(node_txn.len(), 2);
5082 assert_eq!(node_txn[0].input.len(), 2);
5083 check_spends!(node_txn[0], revoked_local_txn[0]);
5085 mine_transaction(&nodes[1], &node_txn[0]);
5086 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5088 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5089 assert_eq!(spend_txn.len(), 1);
5090 check_spends!(spend_txn[0], node_txn[0]);
5094 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5095 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5096 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
5097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5099 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5101 // Create some initial channels
5102 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5104 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5105 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5106 assert_eq!(revoked_local_txn[0].input.len(), 1);
5107 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5109 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5111 // A will generate HTLC-Timeout from revoked commitment tx
5112 mine_transaction(&nodes[0], &revoked_local_txn[0]);
5113 check_closed_broadcast!(nodes[0], true);
5114 check_added_monitors!(nodes[0], 1);
5115 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5117 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5118 assert_eq!(revoked_htlc_txn.len(), 2);
5119 check_spends!(revoked_htlc_txn[0], chan_1.3);
5120 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
5121 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5122 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
5123 assert_ne!(revoked_htlc_txn[1].lock_time, 0); // HTLC-Timeout
5125 // B will generate justice tx from A's revoked commitment/HTLC tx
5126 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5127 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[1].clone()] });
5128 check_closed_broadcast!(nodes[1], true);
5129 check_added_monitors!(nodes[1], 1);
5131 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5132 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5133 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5134 // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
5135 // transactions next...
5136 assert_eq!(node_txn[0].input.len(), 3);
5137 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[1]);
5139 assert_eq!(node_txn[1].input.len(), 2);
5140 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[1]);
5141 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[1].txid() {
5142 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5144 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[1].txid());
5145 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[1].input[0].previous_output);
5148 assert_eq!(node_txn[2].input.len(), 1);
5149 check_spends!(node_txn[2], chan_1.3);
5151 mine_transaction(&nodes[1], &node_txn[1]);
5152 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5154 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5155 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5156 assert_eq!(spend_txn.len(), 1);
5157 assert_eq!(spend_txn[0].input.len(), 1);
5158 check_spends!(spend_txn[0], node_txn[1]);
5162 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5163 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5164 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5169 // Create some initial channels
5170 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5172 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5173 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5174 assert_eq!(revoked_local_txn[0].input.len(), 1);
5175 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5177 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5178 assert_eq!(revoked_local_txn[0].output.len(), 2);
5180 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
5182 // B will generate HTLC-Success from revoked commitment tx
5183 mine_transaction(&nodes[1], &revoked_local_txn[0]);
5184 check_closed_broadcast!(nodes[1], true);
5185 check_added_monitors!(nodes[1], 1);
5186 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5188 assert_eq!(revoked_htlc_txn.len(), 2);
5189 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5190 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5191 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5193 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5194 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5195 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5197 // A will generate justice tx from B's revoked commitment/HTLC tx
5198 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5199 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5200 check_closed_broadcast!(nodes[0], true);
5201 check_added_monitors!(nodes[0], 1);
5203 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5204 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5206 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5207 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5208 // transactions next...
5209 assert_eq!(node_txn[0].input.len(), 2);
5210 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5211 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5212 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5214 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5215 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5218 assert_eq!(node_txn[1].input.len(), 1);
5219 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5221 check_spends!(node_txn[2], chan_1.3);
5223 mine_transaction(&nodes[0], &node_txn[1]);
5224 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5226 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5227 // didn't try to generate any new transactions.
5229 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5230 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5231 assert_eq!(spend_txn.len(), 3);
5232 assert_eq!(spend_txn[0].input.len(), 1);
5233 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5234 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5235 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5236 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5240 fn test_onchain_to_onchain_claim() {
5241 // Test that in case of channel closure, we detect the state of output and claim HTLC
5242 // on downstream peer's remote commitment tx.
5243 // First, have C claim an HTLC against its own latest commitment transaction.
5244 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5246 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5249 let chanmon_cfgs = create_chanmon_cfgs(3);
5250 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5251 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5252 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5254 // Create some initial channels
5255 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5256 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5258 // Ensure all nodes are at the same height
5259 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5260 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5261 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5262 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5264 // Rebalance the network a bit by relaying one payment through all the channels ...
5265 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5266 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
5268 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5269 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5270 check_spends!(commitment_tx[0], chan_2.3);
5271 nodes[2].node.claim_funds(payment_preimage);
5272 check_added_monitors!(nodes[2], 1);
5273 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5274 assert!(updates.update_add_htlcs.is_empty());
5275 assert!(updates.update_fail_htlcs.is_empty());
5276 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5277 assert!(updates.update_fail_malformed_htlcs.is_empty());
5279 mine_transaction(&nodes[2], &commitment_tx[0]);
5280 check_closed_broadcast!(nodes[2], true);
5281 check_added_monitors!(nodes[2], 1);
5283 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5284 assert_eq!(c_txn.len(), 3);
5285 assert_eq!(c_txn[0], c_txn[2]);
5286 assert_eq!(commitment_tx[0], c_txn[1]);
5287 check_spends!(c_txn[1], chan_2.3);
5288 check_spends!(c_txn[2], c_txn[1]);
5289 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5290 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5291 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5292 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5294 // 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
5295 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5296 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5297 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5299 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5300 // ChannelMonitor: claim tx, ChannelManager: local commitment tx
5301 assert_eq!(b_txn.len(), 2);
5302 check_spends!(b_txn[0], chan_2.3); // B local commitment tx, issued by ChannelManager
5303 check_spends!(b_txn[1], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5304 assert_eq!(b_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5305 assert!(b_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5306 assert_ne!(b_txn[1].lock_time, 0); // Timeout tx
5309 check_added_monitors!(nodes[1], 1);
5310 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5311 assert_eq!(msg_events.len(), 3);
5312 check_added_monitors!(nodes[1], 1);
5313 match msg_events[0] {
5314 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5315 _ => panic!("Unexpected event"),
5317 match msg_events[1] {
5318 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5319 _ => panic!("Unexpected event"),
5321 match msg_events[2] {
5322 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, .. } } => {
5323 assert!(update_add_htlcs.is_empty());
5324 assert!(update_fail_htlcs.is_empty());
5325 assert_eq!(update_fulfill_htlcs.len(), 1);
5326 assert!(update_fail_malformed_htlcs.is_empty());
5327 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5329 _ => panic!("Unexpected event"),
5331 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5332 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5333 mine_transaction(&nodes[1], &commitment_tx[0]);
5334 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5335 // ChannelMonitor: HTLC-Success tx + HTLC-Timeout RBF Bump, ChannelManager: local commitment tx + HTLC-Success tx
5336 assert_eq!(b_txn.len(), 4);
5337 check_spends!(b_txn[2], chan_1.3);
5338 check_spends!(b_txn[3], b_txn[2]);
5339 let (htlc_success_claim, htlc_timeout_bumped) =
5340 if b_txn[0].input[0].previous_output.txid == commitment_tx[0].txid()
5341 { (&b_txn[0], &b_txn[1]) } else { (&b_txn[1], &b_txn[0]) };
5342 check_spends!(htlc_success_claim, commitment_tx[0]);
5343 assert_eq!(htlc_success_claim.input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5344 assert!(htlc_success_claim.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5345 assert_eq!(htlc_success_claim.lock_time, 0); // Success tx
5346 check_spends!(htlc_timeout_bumped, c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5347 assert_ne!(htlc_timeout_bumped.lock_time, 0); // Success tx
5349 check_closed_broadcast!(nodes[1], true);
5350 check_added_monitors!(nodes[1], 1);
5354 fn test_duplicate_payment_hash_one_failure_one_success() {
5355 // Topology : A --> B --> C --> D
5356 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5357 // Note that because C will refuse to generate two payment secrets for the same payment hash,
5358 // we forward one of the payments onwards to D.
5359 let chanmon_cfgs = create_chanmon_cfgs(4);
5360 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
5361 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
5362 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
5364 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5365 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5366 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5368 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5369 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5370 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5371 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5372 connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
5374 let (our_payment_preimage, duplicate_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5376 let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, 0).unwrap();
5377 // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
5378 // script push size limit so that the below script length checks match
5379 // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5380 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
5381 &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 900000, TEST_FINAL_CLTV - 40, nodes[0].logger).unwrap();
5382 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 900000, duplicate_payment_hash, payment_secret);
5384 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5385 assert_eq!(commitment_txn[0].input.len(), 1);
5386 check_spends!(commitment_txn[0], chan_2.3);
5388 mine_transaction(&nodes[1], &commitment_txn[0]);
5389 check_closed_broadcast!(nodes[1], true);
5390 check_added_monitors!(nodes[1], 1);
5391 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32 - 1); // Confirm blocks until the HTLC expires
5393 let htlc_timeout_tx;
5394 { // Extract one of the two HTLC-Timeout transaction
5395 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5396 // ChannelMonitor: timeout tx * 3, ChannelManager: local commitment tx
5397 assert_eq!(node_txn.len(), 4);
5398 check_spends!(node_txn[0], chan_2.3);
5400 check_spends!(node_txn[1], commitment_txn[0]);
5401 assert_eq!(node_txn[1].input.len(), 1);
5402 check_spends!(node_txn[2], commitment_txn[0]);
5403 assert_eq!(node_txn[2].input.len(), 1);
5404 assert_eq!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
5405 check_spends!(node_txn[3], commitment_txn[0]);
5406 assert_ne!(node_txn[1].input[0].previous_output, node_txn[3].input[0].previous_output);
5408 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5409 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5410 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5411 htlc_timeout_tx = node_txn[1].clone();
5414 nodes[2].node.claim_funds(our_payment_preimage);
5415 mine_transaction(&nodes[2], &commitment_txn[0]);
5416 check_added_monitors!(nodes[2], 2);
5417 let events = nodes[2].node.get_and_clear_pending_msg_events();
5419 MessageSendEvent::UpdateHTLCs { .. } => {},
5420 _ => panic!("Unexpected event"),
5423 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5424 _ => panic!("Unexepected event"),
5426 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5427 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)
5428 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5429 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5430 assert_eq!(htlc_success_txn[0].input.len(), 1);
5431 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5432 assert_eq!(htlc_success_txn[1].input.len(), 1);
5433 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5434 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5435 assert_eq!(htlc_success_txn[2], commitment_txn[0]);
5436 assert_eq!(htlc_success_txn[3], htlc_success_txn[0]);
5437 assert_eq!(htlc_success_txn[4], htlc_success_txn[1]);
5438 assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5440 mine_transaction(&nodes[1], &htlc_timeout_tx);
5441 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5442 expect_pending_htlcs_forwardable!(nodes[1]);
5443 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5444 assert!(htlc_updates.update_add_htlcs.is_empty());
5445 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5446 let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5447 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5448 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5449 check_added_monitors!(nodes[1], 1);
5451 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5452 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5454 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5455 let events = nodes[0].node.get_and_clear_pending_msg_events();
5456 assert_eq!(events.len(), 1);
5458 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5460 _ => { panic!("Unexpected event"); }
5463 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5465 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5466 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5467 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5468 assert!(updates.update_add_htlcs.is_empty());
5469 assert!(updates.update_fail_htlcs.is_empty());
5470 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5471 assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5472 assert!(updates.update_fail_malformed_htlcs.is_empty());
5473 check_added_monitors!(nodes[1], 1);
5475 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5476 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5478 let events = nodes[0].node.get_and_clear_pending_events();
5480 Event::PaymentSent { ref payment_preimage } => {
5481 assert_eq!(*payment_preimage, our_payment_preimage);
5483 _ => panic!("Unexpected event"),
5488 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5489 let chanmon_cfgs = create_chanmon_cfgs(2);
5490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5494 // Create some initial channels
5495 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5497 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5498 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5499 assert_eq!(local_txn.len(), 1);
5500 assert_eq!(local_txn[0].input.len(), 1);
5501 check_spends!(local_txn[0], chan_1.3);
5503 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5504 nodes[1].node.claim_funds(payment_preimage);
5505 check_added_monitors!(nodes[1], 1);
5506 mine_transaction(&nodes[1], &local_txn[0]);
5507 check_added_monitors!(nodes[1], 1);
5508 let events = nodes[1].node.get_and_clear_pending_msg_events();
5510 MessageSendEvent::UpdateHTLCs { .. } => {},
5511 _ => panic!("Unexpected event"),
5514 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5515 _ => panic!("Unexepected event"),
5518 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5519 assert_eq!(node_txn.len(), 3);
5520 assert_eq!(node_txn[0], node_txn[2]);
5521 assert_eq!(node_txn[1], local_txn[0]);
5522 assert_eq!(node_txn[0].input.len(), 1);
5523 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5524 check_spends!(node_txn[0], local_txn[0]);
5528 mine_transaction(&nodes[1], &node_tx);
5529 connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5531 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5532 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5533 assert_eq!(spend_txn.len(), 1);
5534 assert_eq!(spend_txn[0].input.len(), 1);
5535 check_spends!(spend_txn[0], node_tx);
5536 assert_eq!(spend_txn[0].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5539 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5540 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5541 // unrevoked commitment transaction.
5542 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5543 // a remote RAA before they could be failed backwards (and combinations thereof).
5544 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5545 // use the same payment hashes.
5546 // Thus, we use a six-node network:
5551 // And test where C fails back to A/B when D announces its latest commitment transaction
5552 let chanmon_cfgs = create_chanmon_cfgs(6);
5553 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5554 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5555 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5556 let logger = test_utils::TestLogger::new();
5558 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5559 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5560 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5561 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5562 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5564 // Rebalance and check output sanity...
5565 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5566 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5567 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5569 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5571 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
5573 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
5574 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5575 let our_node_id = &nodes[1].node.get_our_node_id();
5576 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5578 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
5580 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
5582 let (_, payment_hash_3, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5584 let (_, payment_hash_4, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5585 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5587 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());
5589 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());
5592 let (_, payment_hash_5, _) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5594 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5595 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
5598 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
5600 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5601 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());
5603 // Double-check that six of the new HTLC were added
5604 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5605 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5606 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5607 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5609 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5610 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5611 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
5612 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
5613 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
5614 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
5615 check_added_monitors!(nodes[4], 0);
5616 expect_pending_htlcs_forwardable!(nodes[4]);
5617 check_added_monitors!(nodes[4], 1);
5619 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5620 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5621 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5622 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5623 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5624 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5626 // Fail 3rd below-dust and 7th above-dust HTLCs
5627 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
5628 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
5629 check_added_monitors!(nodes[5], 0);
5630 expect_pending_htlcs_forwardable!(nodes[5]);
5631 check_added_monitors!(nodes[5], 1);
5633 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5634 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5635 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5636 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5638 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5640 expect_pending_htlcs_forwardable!(nodes[3]);
5641 check_added_monitors!(nodes[3], 1);
5642 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5643 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5644 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5645 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5646 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5647 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5648 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5649 if deliver_last_raa {
5650 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5652 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5655 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5656 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5657 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5658 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5660 // We now broadcast the latest commitment transaction, which *should* result in failures for
5661 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5662 // the non-broadcast above-dust HTLCs.
5664 // Alternatively, we may broadcast the previous commitment transaction, which should only
5665 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5666 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5668 if announce_latest {
5669 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5671 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5673 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5674 check_closed_broadcast!(nodes[2], true);
5675 expect_pending_htlcs_forwardable!(nodes[2]);
5676 check_added_monitors!(nodes[2], 3);
5678 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5679 assert_eq!(cs_msgs.len(), 2);
5680 let mut a_done = false;
5681 for msg in cs_msgs {
5683 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5684 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5685 // should be failed-backwards here.
5686 let target = if *node_id == nodes[0].node.get_our_node_id() {
5687 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5688 for htlc in &updates.update_fail_htlcs {
5689 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 });
5691 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5696 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5697 for htlc in &updates.update_fail_htlcs {
5698 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5700 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5701 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5704 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5705 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5706 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5707 if announce_latest {
5708 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5709 if *node_id == nodes[0].node.get_our_node_id() {
5710 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5713 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5715 _ => panic!("Unexpected event"),
5719 let as_events = nodes[0].node.get_and_clear_pending_events();
5720 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5721 let mut as_failds = HashSet::new();
5722 for event in as_events.iter() {
5723 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5724 assert!(as_failds.insert(*payment_hash));
5725 if *payment_hash != payment_hash_2 {
5726 assert_eq!(*rejected_by_dest, deliver_last_raa);
5728 assert!(!rejected_by_dest);
5730 } else { panic!("Unexpected event"); }
5732 assert!(as_failds.contains(&payment_hash_1));
5733 assert!(as_failds.contains(&payment_hash_2));
5734 if announce_latest {
5735 assert!(as_failds.contains(&payment_hash_3));
5736 assert!(as_failds.contains(&payment_hash_5));
5738 assert!(as_failds.contains(&payment_hash_6));
5740 let bs_events = nodes[1].node.get_and_clear_pending_events();
5741 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5742 let mut bs_failds = HashSet::new();
5743 for event in bs_events.iter() {
5744 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5745 assert!(bs_failds.insert(*payment_hash));
5746 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5747 assert_eq!(*rejected_by_dest, deliver_last_raa);
5749 assert!(!rejected_by_dest);
5751 } else { panic!("Unexpected event"); }
5753 assert!(bs_failds.contains(&payment_hash_1));
5754 assert!(bs_failds.contains(&payment_hash_2));
5755 if announce_latest {
5756 assert!(bs_failds.contains(&payment_hash_4));
5758 assert!(bs_failds.contains(&payment_hash_5));
5760 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5761 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5762 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5763 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5764 // PaymentFailureNetworkUpdates.
5765 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5766 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5767 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5768 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5769 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5771 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5772 _ => panic!("Unexpected event"),
5778 fn test_fail_backwards_latest_remote_announce_a() {
5779 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5783 fn test_fail_backwards_latest_remote_announce_b() {
5784 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5788 fn test_fail_backwards_previous_remote_announce() {
5789 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5790 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5791 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5795 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5796 let chanmon_cfgs = create_chanmon_cfgs(2);
5797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5799 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5801 // Create some initial channels
5802 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5804 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5805 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5806 assert_eq!(local_txn[0].input.len(), 1);
5807 check_spends!(local_txn[0], chan_1.3);
5809 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5810 mine_transaction(&nodes[0], &local_txn[0]);
5811 check_closed_broadcast!(nodes[0], true);
5812 check_added_monitors!(nodes[0], 1);
5813 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5815 let htlc_timeout = {
5816 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5817 assert_eq!(node_txn.len(), 2);
5818 check_spends!(node_txn[0], chan_1.3);
5819 assert_eq!(node_txn[1].input.len(), 1);
5820 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5821 check_spends!(node_txn[1], local_txn[0]);
5825 mine_transaction(&nodes[0], &htlc_timeout);
5826 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5827 expect_payment_failed!(nodes[0], our_payment_hash, true);
5829 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5830 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5831 assert_eq!(spend_txn.len(), 3);
5832 check_spends!(spend_txn[0], local_txn[0]);
5833 assert_eq!(spend_txn[1].input.len(), 1);
5834 check_spends!(spend_txn[1], htlc_timeout);
5835 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5836 assert_eq!(spend_txn[2].input.len(), 2);
5837 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5838 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5839 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5843 fn test_key_derivation_params() {
5844 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5845 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5846 // let us re-derive the channel key set to then derive a delayed_payment_key.
5848 let chanmon_cfgs = create_chanmon_cfgs(3);
5850 // We manually create the node configuration to backup the seed.
5851 let seed = [42; 32];
5852 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5853 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);
5854 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 };
5855 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5856 node_cfgs.remove(0);
5857 node_cfgs.insert(0, node);
5859 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5860 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5862 // Create some initial channels
5863 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5865 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5866 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5867 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5869 // Ensure all nodes are at the same height
5870 let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5871 connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5872 connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5873 connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5875 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5876 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5877 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5878 assert_eq!(local_txn_1[0].input.len(), 1);
5879 check_spends!(local_txn_1[0], chan_1.3);
5881 // We check funding pubkey are unique
5882 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]));
5883 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]));
5884 if from_0_funding_key_0 == from_1_funding_key_0
5885 || from_0_funding_key_0 == from_1_funding_key_1
5886 || from_0_funding_key_1 == from_1_funding_key_0
5887 || from_0_funding_key_1 == from_1_funding_key_1 {
5888 panic!("Funding pubkeys aren't unique");
5891 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5892 mine_transaction(&nodes[0], &local_txn_1[0]);
5893 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
5894 check_closed_broadcast!(nodes[0], true);
5895 check_added_monitors!(nodes[0], 1);
5897 let htlc_timeout = {
5898 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5899 assert_eq!(node_txn[1].input.len(), 1);
5900 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5901 check_spends!(node_txn[1], local_txn_1[0]);
5905 mine_transaction(&nodes[0], &htlc_timeout);
5906 connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5907 expect_payment_failed!(nodes[0], our_payment_hash, true);
5909 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5910 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5911 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5912 assert_eq!(spend_txn.len(), 3);
5913 check_spends!(spend_txn[0], local_txn_1[0]);
5914 assert_eq!(spend_txn[1].input.len(), 1);
5915 check_spends!(spend_txn[1], htlc_timeout);
5916 assert_eq!(spend_txn[1].input[0].sequence, BREAKDOWN_TIMEOUT as u32);
5917 assert_eq!(spend_txn[2].input.len(), 2);
5918 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5919 assert!(spend_txn[2].input[0].sequence == BREAKDOWN_TIMEOUT as u32 ||
5920 spend_txn[2].input[1].sequence == BREAKDOWN_TIMEOUT as u32);
5924 fn test_static_output_closing_tx() {
5925 let chanmon_cfgs = create_chanmon_cfgs(2);
5926 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5927 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5928 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5930 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5932 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5933 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5935 mine_transaction(&nodes[0], &closing_tx);
5936 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5938 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5939 assert_eq!(spend_txn.len(), 1);
5940 check_spends!(spend_txn[0], closing_tx);
5942 mine_transaction(&nodes[1], &closing_tx);
5943 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5945 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5946 assert_eq!(spend_txn.len(), 1);
5947 check_spends!(spend_txn[0], closing_tx);
5950 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5951 let chanmon_cfgs = create_chanmon_cfgs(2);
5952 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5953 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5954 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5955 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5957 let (our_payment_preimage, _, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5959 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5960 // present in B's local commitment transaction, but none of A's commitment transactions.
5961 assert!(nodes[1].node.claim_funds(our_payment_preimage));
5962 check_added_monitors!(nodes[1], 1);
5964 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5965 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5966 let events = nodes[0].node.get_and_clear_pending_events();
5967 assert_eq!(events.len(), 1);
5969 Event::PaymentSent { payment_preimage } => {
5970 assert_eq!(payment_preimage, our_payment_preimage);
5972 _ => panic!("Unexpected event"),
5975 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5976 check_added_monitors!(nodes[0], 1);
5977 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5978 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5979 check_added_monitors!(nodes[1], 1);
5981 let starting_block = nodes[1].best_block_info();
5982 let mut block = Block {
5983 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5986 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5987 connect_block(&nodes[1], &block);
5988 block.header.prev_blockhash = block.block_hash();
5990 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5991 check_closed_broadcast!(nodes[1], true);
5992 check_added_monitors!(nodes[1], 1);
5995 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5996 let chanmon_cfgs = create_chanmon_cfgs(2);
5997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5999 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6000 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6001 let logger = test_utils::TestLogger::new();
6003 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1]);
6004 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6005 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
6006 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
6007 check_added_monitors!(nodes[0], 1);
6009 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6011 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
6012 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
6013 // to "time out" the HTLC.
6015 let starting_block = nodes[1].best_block_info();
6016 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6018 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
6019 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
6020 header.prev_blockhash = header.block_hash();
6022 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6023 check_closed_broadcast!(nodes[0], true);
6024 check_added_monitors!(nodes[0], 1);
6027 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
6028 let chanmon_cfgs = create_chanmon_cfgs(3);
6029 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6030 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6031 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6032 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6034 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
6035 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
6036 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
6037 // actually revoked.
6038 let htlc_value = if use_dust { 50000 } else { 3000000 };
6039 let (_, our_payment_hash, _) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
6040 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
6041 expect_pending_htlcs_forwardable!(nodes[1]);
6042 check_added_monitors!(nodes[1], 1);
6044 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6045 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
6046 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
6047 check_added_monitors!(nodes[0], 1);
6048 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6049 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
6050 check_added_monitors!(nodes[1], 1);
6051 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
6052 check_added_monitors!(nodes[1], 1);
6053 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
6055 if check_revoke_no_close {
6056 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
6057 check_added_monitors!(nodes[0], 1);
6060 let starting_block = nodes[1].best_block_info();
6061 let mut block = Block {
6062 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
6065 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
6066 connect_block(&nodes[0], &block);
6067 block.header.prev_blockhash = block.block_hash();
6069 if !check_revoke_no_close {
6070 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
6071 check_closed_broadcast!(nodes[0], true);
6072 check_added_monitors!(nodes[0], 1);
6074 expect_payment_failed!(nodes[0], our_payment_hash, true);
6078 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
6079 // There are only a few cases to test here:
6080 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
6081 // broadcastable commitment transactions result in channel closure,
6082 // * its included in an unrevoked-but-previous remote commitment transaction,
6083 // * its included in the latest remote or local commitment transactions.
6084 // We test each of the three possible commitment transactions individually and use both dust and
6086 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
6087 // assume they are handled the same across all six cases, as both outbound and inbound failures are
6088 // tested for at least one of the cases in other tests.
6090 fn htlc_claim_single_commitment_only_a() {
6091 do_htlc_claim_local_commitment_only(true);
6092 do_htlc_claim_local_commitment_only(false);
6094 do_htlc_claim_current_remote_commitment_only(true);
6095 do_htlc_claim_current_remote_commitment_only(false);
6099 fn htlc_claim_single_commitment_only_b() {
6100 do_htlc_claim_previous_remote_commitment_only(true, false);
6101 do_htlc_claim_previous_remote_commitment_only(false, false);
6102 do_htlc_claim_previous_remote_commitment_only(true, true);
6103 do_htlc_claim_previous_remote_commitment_only(false, true);
6108 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
6109 let chanmon_cfgs = create_chanmon_cfgs(2);
6110 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6111 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6112 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6113 //Force duplicate channel ids
6114 for node in nodes.iter() {
6115 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6118 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6119 let channel_value_satoshis=10000;
6120 let push_msat=10001;
6121 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6122 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6123 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6125 //Create a second channel with a channel_id collision
6126 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6130 fn bolt2_open_channel_sending_node_checks_part2() {
6131 let chanmon_cfgs = create_chanmon_cfgs(2);
6132 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6133 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6134 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6136 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6137 let channel_value_satoshis=2^24;
6138 let push_msat=10001;
6139 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6141 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6142 let channel_value_satoshis=10000;
6143 // Test when push_msat is equal to 1000 * funding_satoshis.
6144 let push_msat=1000*channel_value_satoshis+1;
6145 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6147 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6148 let channel_value_satoshis=10000;
6149 let push_msat=10001;
6150 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
6151 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6152 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6154 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6155 // 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
6156 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6158 // 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.
6159 assert!(BREAKDOWN_TIMEOUT>0);
6160 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6162 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6163 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6164 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6166 // 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.
6167 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6168 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6169 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6170 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6171 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6175 fn bolt2_open_channel_sane_dust_limit() {
6176 let chanmon_cfgs = create_chanmon_cfgs(2);
6177 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6178 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6179 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6181 let channel_value_satoshis=1000000;
6182 let push_msat=10001;
6183 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6184 let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6185 node0_to_1_send_open_channel.dust_limit_satoshis = 661;
6186 node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
6188 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6189 let events = nodes[1].node.get_and_clear_pending_msg_events();
6190 let err_msg = match events[0] {
6191 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
6194 _ => panic!("Unexpected event"),
6196 assert_eq!(err_msg.data, "dust_limit_satoshis (661) is greater than the implementation limit (660)");
6199 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6200 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6201 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6202 // is no longer affordable once it's freed.
6204 fn test_fail_holding_cell_htlc_upon_free() {
6205 let chanmon_cfgs = create_chanmon_cfgs(2);
6206 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6207 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6208 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6209 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6210 let logger = test_utils::TestLogger::new();
6212 // First nodes[0] generates an update_fee, setting the channel's
6213 // pending_update_fee.
6214 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6215 check_added_monitors!(nodes[0], 1);
6217 let events = nodes[0].node.get_and_clear_pending_msg_events();
6218 assert_eq!(events.len(), 1);
6219 let (update_msg, commitment_signed) = match events[0] {
6220 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6221 (update_fee.as_ref(), commitment_signed)
6223 _ => panic!("Unexpected event"),
6226 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6228 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6229 let channel_reserve = chan_stat.channel_reserve_msat;
6230 let feerate = get_feerate!(nodes[0], chan.2);
6232 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6233 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6234 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6235 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6236 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6238 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6239 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6240 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6241 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6243 // Flush the pending fee update.
6244 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6245 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6246 check_added_monitors!(nodes[1], 1);
6247 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6248 check_added_monitors!(nodes[0], 1);
6250 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6251 // HTLC, but now that the fee has been raised the payment will now fail, causing
6252 // us to surface its failure to the user.
6253 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6254 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6255 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);
6256 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 {}",
6257 hex::encode(our_payment_hash.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6258 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6260 // Check that the payment failed to be sent out.
6261 let events = nodes[0].node.get_and_clear_pending_events();
6262 assert_eq!(events.len(), 1);
6264 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6265 assert_eq!(our_payment_hash.clone(), *payment_hash);
6266 assert_eq!(*rejected_by_dest, false);
6267 assert_eq!(*error_code, None);
6268 assert_eq!(*error_data, None);
6270 _ => panic!("Unexpected event"),
6274 // Test that if multiple HTLCs are released from the holding cell and one is
6275 // valid but the other is no longer valid upon release, the valid HTLC can be
6276 // successfully completed while the other one fails as expected.
6278 fn test_free_and_fail_holding_cell_htlcs() {
6279 let chanmon_cfgs = create_chanmon_cfgs(2);
6280 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6281 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6282 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6283 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6284 let logger = test_utils::TestLogger::new();
6286 // First nodes[0] generates an update_fee, setting the channel's
6287 // pending_update_fee.
6288 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6289 check_added_monitors!(nodes[0], 1);
6291 let events = nodes[0].node.get_and_clear_pending_msg_events();
6292 assert_eq!(events.len(), 1);
6293 let (update_msg, commitment_signed) = match events[0] {
6294 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6295 (update_fee.as_ref(), commitment_signed)
6297 _ => panic!("Unexpected event"),
6300 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6302 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6303 let channel_reserve = chan_stat.channel_reserve_msat;
6304 let feerate = get_feerate!(nodes[0], chan.2);
6306 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6307 let (payment_preimage_1, payment_hash_1, payment_secret_1) = get_payment_preimage_hash!(nodes[1]);
6309 let (_, payment_hash_2, payment_secret_2) = get_payment_preimage_hash!(nodes[1]);
6310 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6311 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6312 let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6313 let route_2 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6315 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6316 nodes[0].node.send_payment(&route_1, payment_hash_1, &Some(payment_secret_1)).unwrap();
6317 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6318 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6319 nodes[0].node.send_payment(&route_2, payment_hash_2, &Some(payment_secret_2)).unwrap();
6320 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6321 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6323 // Flush the pending fee update.
6324 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6325 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6326 check_added_monitors!(nodes[1], 1);
6327 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6328 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6329 check_added_monitors!(nodes[0], 2);
6331 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6332 // but now that the fee has been raised the second payment will now fail, causing us
6333 // to surface its failure to the user. The first payment should succeed.
6334 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6335 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6336 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);
6337 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 {}",
6338 hex::encode(payment_hash_2.0), chan_stat.channel_reserve_msat, hex::encode(chan.2));
6339 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6341 // Check that the second payment failed to be sent out.
6342 let events = nodes[0].node.get_and_clear_pending_events();
6343 assert_eq!(events.len(), 1);
6345 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6346 assert_eq!(payment_hash_2.clone(), *payment_hash);
6347 assert_eq!(*rejected_by_dest, false);
6348 assert_eq!(*error_code, None);
6349 assert_eq!(*error_data, None);
6351 _ => panic!("Unexpected event"),
6354 // Complete the first payment and the RAA from the fee update.
6355 let (payment_event, send_raa_event) = {
6356 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6357 assert_eq!(msgs.len(), 2);
6358 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6360 let raa = match send_raa_event {
6361 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6362 _ => panic!("Unexpected event"),
6364 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6365 check_added_monitors!(nodes[1], 1);
6366 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6367 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6368 let events = nodes[1].node.get_and_clear_pending_events();
6369 assert_eq!(events.len(), 1);
6371 Event::PendingHTLCsForwardable { .. } => {},
6372 _ => panic!("Unexpected event"),
6374 nodes[1].node.process_pending_htlc_forwards();
6375 let events = nodes[1].node.get_and_clear_pending_events();
6376 assert_eq!(events.len(), 1);
6378 Event::PaymentReceived { .. } => {},
6379 _ => panic!("Unexpected event"),
6381 nodes[1].node.claim_funds(payment_preimage_1);
6382 check_added_monitors!(nodes[1], 1);
6383 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6384 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6385 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6386 let events = nodes[0].node.get_and_clear_pending_events();
6387 assert_eq!(events.len(), 1);
6389 Event::PaymentSent { ref payment_preimage } => {
6390 assert_eq!(*payment_preimage, payment_preimage_1);
6392 _ => panic!("Unexpected event"),
6396 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6397 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6398 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6401 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6402 let chanmon_cfgs = create_chanmon_cfgs(3);
6403 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6404 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6405 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6406 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6407 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6408 let logger = test_utils::TestLogger::new();
6410 // First nodes[1] generates an update_fee, setting the channel's
6411 // pending_update_fee.
6412 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6413 check_added_monitors!(nodes[1], 1);
6415 let events = nodes[1].node.get_and_clear_pending_msg_events();
6416 assert_eq!(events.len(), 1);
6417 let (update_msg, commitment_signed) = match events[0] {
6418 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6419 (update_fee.as_ref(), commitment_signed)
6421 _ => panic!("Unexpected event"),
6424 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6426 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6427 let channel_reserve = chan_stat.channel_reserve_msat;
6428 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6430 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6432 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6433 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
6434 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6435 let payment_event = {
6436 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6437 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6438 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6439 check_added_monitors!(nodes[0], 1);
6441 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6442 assert_eq!(events.len(), 1);
6444 SendEvent::from_event(events.remove(0))
6446 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6447 check_added_monitors!(nodes[1], 0);
6448 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6449 expect_pending_htlcs_forwardable!(nodes[1]);
6451 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6452 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6454 // Flush the pending fee update.
6455 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6456 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6457 check_added_monitors!(nodes[2], 1);
6458 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6459 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6460 check_added_monitors!(nodes[1], 2);
6462 // A final RAA message is generated to finalize the fee update.
6463 let events = nodes[1].node.get_and_clear_pending_msg_events();
6464 assert_eq!(events.len(), 1);
6466 let raa_msg = match &events[0] {
6467 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6470 _ => panic!("Unexpected event"),
6473 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6474 check_added_monitors!(nodes[2], 1);
6475 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6477 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6478 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6479 assert_eq!(process_htlc_forwards_event.len(), 1);
6480 match &process_htlc_forwards_event[0] {
6481 &Event::PendingHTLCsForwardable { .. } => {},
6482 _ => panic!("Unexpected event"),
6485 // In response, we call ChannelManager's process_pending_htlc_forwards
6486 nodes[1].node.process_pending_htlc_forwards();
6487 check_added_monitors!(nodes[1], 1);
6489 // This causes the HTLC to be failed backwards.
6490 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6491 assert_eq!(fail_event.len(), 1);
6492 let (fail_msg, commitment_signed) = match &fail_event[0] {
6493 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6494 assert_eq!(updates.update_add_htlcs.len(), 0);
6495 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6496 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6497 assert_eq!(updates.update_fail_htlcs.len(), 1);
6498 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6500 _ => panic!("Unexpected event"),
6503 // Pass the failure messages back to nodes[0].
6504 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6505 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6507 // Complete the HTLC failure+removal process.
6508 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6509 check_added_monitors!(nodes[0], 1);
6510 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6511 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6512 check_added_monitors!(nodes[1], 2);
6513 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6514 assert_eq!(final_raa_event.len(), 1);
6515 let raa = match &final_raa_event[0] {
6516 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6517 _ => panic!("Unexpected event"),
6519 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6520 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6521 assert_eq!(fail_msg_event.len(), 1);
6522 match &fail_msg_event[0] {
6523 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6524 _ => panic!("Unexpected event"),
6526 let failure_event = nodes[0].node.get_and_clear_pending_events();
6527 assert_eq!(failure_event.len(), 1);
6528 match &failure_event[0] {
6529 &Event::PaymentFailed { rejected_by_dest, .. } => {
6530 assert!(!rejected_by_dest);
6532 _ => panic!("Unexpected event"),
6534 check_added_monitors!(nodes[0], 1);
6537 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6538 // 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.
6539 //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.
6542 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6543 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6544 let chanmon_cfgs = create_chanmon_cfgs(2);
6545 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6546 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6547 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6548 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6550 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6551 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6552 let logger = test_utils::TestLogger::new();
6553 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6554 route.paths[0][0].fee_msat = 100;
6556 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6557 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6558 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6559 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6563 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6564 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6565 let chanmon_cfgs = create_chanmon_cfgs(2);
6566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6568 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6569 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6570 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6572 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6573 let logger = test_utils::TestLogger::new();
6574 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6575 route.paths[0][0].fee_msat = 0;
6576 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6577 assert_eq!(err, "Cannot send 0-msat HTLC"));
6579 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6580 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6584 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6585 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6586 let chanmon_cfgs = create_chanmon_cfgs(2);
6587 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6588 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6589 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6590 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6592 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6593 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6594 let logger = test_utils::TestLogger::new();
6595 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6596 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6597 check_added_monitors!(nodes[0], 1);
6598 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6599 updates.update_add_htlcs[0].amount_msat = 0;
6601 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6602 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6603 check_closed_broadcast!(nodes[1], true).unwrap();
6604 check_added_monitors!(nodes[1], 1);
6608 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6609 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6610 //It is enforced when constructing a route.
6611 let chanmon_cfgs = create_chanmon_cfgs(2);
6612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6614 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6615 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6616 let logger = test_utils::TestLogger::new();
6618 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6620 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6621 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000000, 500000001, &logger).unwrap();
6622 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::RouteError { ref err },
6623 assert_eq!(err, &"Channel CLTV overflowed?"));
6627 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6628 //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.
6629 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6630 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6631 let chanmon_cfgs = create_chanmon_cfgs(2);
6632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6634 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6635 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6636 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6638 let logger = test_utils::TestLogger::new();
6639 for i in 0..max_accepted_htlcs {
6640 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6641 let payment_event = {
6642 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6643 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6644 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6645 check_added_monitors!(nodes[0], 1);
6647 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6648 assert_eq!(events.len(), 1);
6649 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6650 assert_eq!(htlcs[0].htlc_id, i);
6654 SendEvent::from_event(events.remove(0))
6656 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6657 check_added_monitors!(nodes[1], 0);
6658 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6660 expect_pending_htlcs_forwardable!(nodes[1]);
6661 expect_payment_received!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6663 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6664 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6665 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6666 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6667 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6669 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6670 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6674 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6675 //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.
6676 let chanmon_cfgs = create_chanmon_cfgs(2);
6677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6679 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6680 let channel_value = 100000;
6681 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6682 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6684 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6686 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6687 // Manually create a route over our max in flight (which our router normally automatically
6689 let route = Route { paths: vec![vec![RouteHop {
6690 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6691 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6692 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6694 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)), true, APIError::ChannelUnavailable { ref err },
6695 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)));
6697 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6698 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);
6700 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6703 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6705 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6706 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6707 let chanmon_cfgs = create_chanmon_cfgs(2);
6708 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6709 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6710 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6711 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6712 let htlc_minimum_msat: u64;
6714 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6715 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6716 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6719 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6720 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6721 let logger = test_utils::TestLogger::new();
6722 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6723 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6724 check_added_monitors!(nodes[0], 1);
6725 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6726 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6727 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6728 assert!(nodes[1].node.list_channels().is_empty());
6729 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6730 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()));
6731 check_added_monitors!(nodes[1], 1);
6735 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6736 //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
6737 let chanmon_cfgs = create_chanmon_cfgs(2);
6738 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6739 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6740 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6741 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6742 let logger = test_utils::TestLogger::new();
6744 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6745 let channel_reserve = chan_stat.channel_reserve_msat;
6746 let feerate = get_feerate!(nodes[0], chan.2);
6747 // The 2* and +1 are for the fee spike reserve.
6748 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6750 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6751 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6752 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6753 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6754 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6755 check_added_monitors!(nodes[0], 1);
6756 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6758 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6759 // at this time channel-initiatee receivers are not required to enforce that senders
6760 // respect the fee_spike_reserve.
6761 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6762 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6764 assert!(nodes[1].node.list_channels().is_empty());
6765 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6766 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6767 check_added_monitors!(nodes[1], 1);
6771 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6772 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6773 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6774 let chanmon_cfgs = create_chanmon_cfgs(2);
6775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6777 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6778 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6779 let logger = test_utils::TestLogger::new();
6781 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6782 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6784 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6785 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6787 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6788 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6789 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &Some(our_payment_secret), cur_height).unwrap();
6790 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6792 let mut msg = msgs::UpdateAddHTLC {
6796 payment_hash: our_payment_hash,
6797 cltv_expiry: htlc_cltv,
6798 onion_routing_packet: onion_packet.clone(),
6801 for i in 0..super::channel::OUR_MAX_HTLCS {
6802 msg.htlc_id = i as u64;
6803 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6805 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6806 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6808 assert!(nodes[1].node.list_channels().is_empty());
6809 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6810 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6811 check_added_monitors!(nodes[1], 1);
6815 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6816 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6817 let chanmon_cfgs = create_chanmon_cfgs(2);
6818 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6819 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6820 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6821 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6822 let logger = test_utils::TestLogger::new();
6824 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6825 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6826 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6827 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6828 check_added_monitors!(nodes[0], 1);
6829 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6830 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6831 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6833 assert!(nodes[1].node.list_channels().is_empty());
6834 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6835 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6836 check_added_monitors!(nodes[1], 1);
6840 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6841 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6842 let chanmon_cfgs = create_chanmon_cfgs(2);
6843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6845 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6846 let logger = test_utils::TestLogger::new();
6848 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6849 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6850 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6851 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6852 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6853 check_added_monitors!(nodes[0], 1);
6854 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6855 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6856 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6858 assert!(nodes[1].node.list_channels().is_empty());
6859 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6860 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6861 check_added_monitors!(nodes[1], 1);
6865 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6866 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6867 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6868 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6869 let chanmon_cfgs = create_chanmon_cfgs(2);
6870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6872 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6873 let logger = test_utils::TestLogger::new();
6875 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6876 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6877 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6878 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6879 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6880 check_added_monitors!(nodes[0], 1);
6881 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6882 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6884 //Disconnect and Reconnect
6885 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6886 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6887 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6888 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6889 assert_eq!(reestablish_1.len(), 1);
6890 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6891 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6892 assert_eq!(reestablish_2.len(), 1);
6893 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6894 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6895 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6896 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6900 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6901 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6902 check_added_monitors!(nodes[1], 1);
6903 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6905 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6907 assert!(nodes[1].node.list_channels().is_empty());
6908 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6909 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6910 check_added_monitors!(nodes[1], 1);
6914 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6915 //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.
6917 let chanmon_cfgs = create_chanmon_cfgs(2);
6918 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6919 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6920 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6921 let logger = test_utils::TestLogger::new();
6922 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6923 let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6924 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6925 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6926 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6928 check_added_monitors!(nodes[0], 1);
6929 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6930 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6932 let update_msg = msgs::UpdateFulfillHTLC{
6935 payment_preimage: our_payment_preimage,
6938 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6940 assert!(nodes[0].node.list_channels().is_empty());
6941 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6942 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()));
6943 check_added_monitors!(nodes[0], 1);
6947 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6948 //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.
6950 let chanmon_cfgs = create_chanmon_cfgs(2);
6951 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6952 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6953 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6954 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6955 let logger = test_utils::TestLogger::new();
6957 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6958 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6959 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6960 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6961 check_added_monitors!(nodes[0], 1);
6962 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6963 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6965 let update_msg = msgs::UpdateFailHTLC{
6968 reason: msgs::OnionErrorPacket { data: Vec::new()},
6971 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6973 assert!(nodes[0].node.list_channels().is_empty());
6974 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6975 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()));
6976 check_added_monitors!(nodes[0], 1);
6980 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6981 //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.
6983 let chanmon_cfgs = create_chanmon_cfgs(2);
6984 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6985 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6986 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6987 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6988 let logger = test_utils::TestLogger::new();
6990 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
6991 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6992 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6993 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
6994 check_added_monitors!(nodes[0], 1);
6995 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6996 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6997 let update_msg = msgs::UpdateFailMalformedHTLC{
7000 sha256_of_onion: [1; 32],
7001 failure_code: 0x8000,
7004 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7006 assert!(nodes[0].node.list_channels().is_empty());
7007 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7008 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()));
7009 check_added_monitors!(nodes[0], 1);
7013 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
7014 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
7016 let chanmon_cfgs = create_chanmon_cfgs(2);
7017 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7018 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7019 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7020 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7022 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
7024 nodes[1].node.claim_funds(our_payment_preimage);
7025 check_added_monitors!(nodes[1], 1);
7027 let events = nodes[1].node.get_and_clear_pending_msg_events();
7028 assert_eq!(events.len(), 1);
7029 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7031 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, .. } } => {
7032 assert!(update_add_htlcs.is_empty());
7033 assert_eq!(update_fulfill_htlcs.len(), 1);
7034 assert!(update_fail_htlcs.is_empty());
7035 assert!(update_fail_malformed_htlcs.is_empty());
7036 assert!(update_fee.is_none());
7037 update_fulfill_htlcs[0].clone()
7039 _ => panic!("Unexpected event"),
7043 update_fulfill_msg.htlc_id = 1;
7045 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7047 assert!(nodes[0].node.list_channels().is_empty());
7048 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7049 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
7050 check_added_monitors!(nodes[0], 1);
7054 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
7055 //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.
7057 let chanmon_cfgs = create_chanmon_cfgs(2);
7058 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7059 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7060 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7061 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7063 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
7065 nodes[1].node.claim_funds(our_payment_preimage);
7066 check_added_monitors!(nodes[1], 1);
7068 let events = nodes[1].node.get_and_clear_pending_msg_events();
7069 assert_eq!(events.len(), 1);
7070 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
7072 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, .. } } => {
7073 assert!(update_add_htlcs.is_empty());
7074 assert_eq!(update_fulfill_htlcs.len(), 1);
7075 assert!(update_fail_htlcs.is_empty());
7076 assert!(update_fail_malformed_htlcs.is_empty());
7077 assert!(update_fee.is_none());
7078 update_fulfill_htlcs[0].clone()
7080 _ => panic!("Unexpected event"),
7084 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
7086 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
7088 assert!(nodes[0].node.list_channels().is_empty());
7089 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7090 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
7091 check_added_monitors!(nodes[0], 1);
7095 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
7096 //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.
7098 let chanmon_cfgs = create_chanmon_cfgs(2);
7099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7101 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7102 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7103 let logger = test_utils::TestLogger::new();
7105 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[1]);
7106 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7107 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
7108 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7109 check_added_monitors!(nodes[0], 1);
7111 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
7112 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7114 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
7115 check_added_monitors!(nodes[1], 0);
7116 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
7118 let events = nodes[1].node.get_and_clear_pending_msg_events();
7120 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
7122 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, .. } } => {
7123 assert!(update_add_htlcs.is_empty());
7124 assert!(update_fulfill_htlcs.is_empty());
7125 assert!(update_fail_htlcs.is_empty());
7126 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7127 assert!(update_fee.is_none());
7128 update_fail_malformed_htlcs[0].clone()
7130 _ => panic!("Unexpected event"),
7133 update_msg.failure_code &= !0x8000;
7134 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
7136 assert!(nodes[0].node.list_channels().is_empty());
7137 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7138 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7139 check_added_monitors!(nodes[0], 1);
7143 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7144 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7145 // * 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.
7147 let chanmon_cfgs = create_chanmon_cfgs(3);
7148 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7149 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7150 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7151 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7152 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7153 let logger = test_utils::TestLogger::new();
7155 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
7158 let mut payment_event = {
7159 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7160 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
7161 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7162 check_added_monitors!(nodes[0], 1);
7163 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7164 assert_eq!(events.len(), 1);
7165 SendEvent::from_event(events.remove(0))
7167 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7168 check_added_monitors!(nodes[1], 0);
7169 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7170 expect_pending_htlcs_forwardable!(nodes[1]);
7171 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7172 assert_eq!(events_2.len(), 1);
7173 check_added_monitors!(nodes[1], 1);
7174 payment_event = SendEvent::from_event(events_2.remove(0));
7175 assert_eq!(payment_event.msgs.len(), 1);
7178 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7179 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7180 check_added_monitors!(nodes[2], 0);
7181 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7183 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7184 assert_eq!(events_3.len(), 1);
7185 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7187 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 } } => {
7188 assert!(update_add_htlcs.is_empty());
7189 assert!(update_fulfill_htlcs.is_empty());
7190 assert!(update_fail_htlcs.is_empty());
7191 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7192 assert!(update_fee.is_none());
7193 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7195 _ => panic!("Unexpected event"),
7199 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7201 check_added_monitors!(nodes[1], 0);
7202 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7203 expect_pending_htlcs_forwardable!(nodes[1]);
7204 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7205 assert_eq!(events_4.len(), 1);
7207 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7209 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, .. } } => {
7210 assert!(update_add_htlcs.is_empty());
7211 assert!(update_fulfill_htlcs.is_empty());
7212 assert_eq!(update_fail_htlcs.len(), 1);
7213 assert!(update_fail_malformed_htlcs.is_empty());
7214 assert!(update_fee.is_none());
7216 _ => panic!("Unexpected event"),
7219 check_added_monitors!(nodes[1], 1);
7222 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7223 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7224 // 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
7225 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7227 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7228 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7229 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7230 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7231 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7232 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7234 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7236 // We route 2 dust-HTLCs between A and B
7237 let (_, payment_hash_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7238 let (_, payment_hash_2, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7239 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7241 // Cache one local commitment tx as previous
7242 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7244 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7245 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
7246 check_added_monitors!(nodes[1], 0);
7247 expect_pending_htlcs_forwardable!(nodes[1]);
7248 check_added_monitors!(nodes[1], 1);
7250 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7251 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7252 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7253 check_added_monitors!(nodes[0], 1);
7255 // Cache one local commitment tx as lastest
7256 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7258 let events = nodes[0].node.get_and_clear_pending_msg_events();
7260 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7261 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7263 _ => panic!("Unexpected event"),
7266 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7267 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7269 _ => panic!("Unexpected event"),
7272 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7273 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7274 if announce_latest {
7275 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7277 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7280 check_closed_broadcast!(nodes[0], true);
7281 check_added_monitors!(nodes[0], 1);
7283 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7284 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7285 let events = nodes[0].node.get_and_clear_pending_events();
7286 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7287 assert_eq!(events.len(), 2);
7288 let mut first_failed = false;
7289 for event in events {
7291 Event::PaymentFailed { payment_hash, .. } => {
7292 if payment_hash == payment_hash_1 {
7293 assert!(!first_failed);
7294 first_failed = true;
7296 assert_eq!(payment_hash, payment_hash_2);
7299 _ => panic!("Unexpected event"),
7305 fn test_failure_delay_dust_htlc_local_commitment() {
7306 do_test_failure_delay_dust_htlc_local_commitment(true);
7307 do_test_failure_delay_dust_htlc_local_commitment(false);
7310 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7311 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7312 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7313 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7314 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7315 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7316 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7318 let chanmon_cfgs = create_chanmon_cfgs(3);
7319 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7320 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7321 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7322 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7324 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7326 let (_payment_preimage_1, dust_hash, _payment_secret_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7327 let (_payment_preimage_2, non_dust_hash, _payment_secret_2) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7329 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7330 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7332 // We revoked bs_commitment_tx
7334 let (payment_preimage_3, _, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7335 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7338 let mut timeout_tx = Vec::new();
7340 // We fail dust-HTLC 1 by broadcast of local commitment tx
7341 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7342 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7343 expect_payment_failed!(nodes[0], dust_hash, true);
7345 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7346 check_closed_broadcast!(nodes[0], true);
7347 check_added_monitors!(nodes[0], 1);
7348 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7349 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7350 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7351 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7352 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7353 mine_transaction(&nodes[0], &timeout_tx[0]);
7354 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7355 expect_payment_failed!(nodes[0], non_dust_hash, true);
7357 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7358 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7359 check_closed_broadcast!(nodes[0], true);
7360 check_added_monitors!(nodes[0], 1);
7361 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7362 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
7363 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[1].clone());
7365 expect_payment_failed!(nodes[0], dust_hash, true);
7366 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7367 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7368 mine_transaction(&nodes[0], &timeout_tx[0]);
7369 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7370 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7371 expect_payment_failed!(nodes[0], non_dust_hash, true);
7373 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7375 let events = nodes[0].node.get_and_clear_pending_events();
7376 assert_eq!(events.len(), 2);
7379 Event::PaymentFailed { payment_hash, .. } => {
7380 if payment_hash == dust_hash { first = true; }
7381 else { first = false; }
7383 _ => panic!("Unexpected event"),
7386 Event::PaymentFailed { payment_hash, .. } => {
7387 if first { assert_eq!(payment_hash, non_dust_hash); }
7388 else { assert_eq!(payment_hash, dust_hash); }
7390 _ => panic!("Unexpected event"),
7397 fn test_sweep_outbound_htlc_failure_update() {
7398 do_test_sweep_outbound_htlc_failure_update(false, true);
7399 do_test_sweep_outbound_htlc_failure_update(false, false);
7400 do_test_sweep_outbound_htlc_failure_update(true, false);
7404 fn test_upfront_shutdown_script() {
7405 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7406 // enforce it at shutdown message
7408 let mut config = UserConfig::default();
7409 config.channel_options.announced_channel = true;
7410 config.peer_channel_config_limits.force_announced_channel_preference = false;
7411 config.channel_options.commit_upfront_shutdown_pubkey = false;
7412 let user_cfgs = [None, Some(config), None];
7413 let chanmon_cfgs = create_chanmon_cfgs(3);
7414 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7415 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7416 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7418 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7419 let flags = InitFeatures::known();
7420 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7421 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7422 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7423 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7424 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7425 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7426 assert!(regex::Regex::new(r"Got shutdown request with a scriptpubkey \([A-Fa-f0-9]+\) which did not match their previous scriptpubkey.").unwrap().is_match(check_closed_broadcast!(nodes[2], true).unwrap().data.as_str()));
7427 check_added_monitors!(nodes[2], 1);
7429 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7430 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7431 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7432 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7433 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7434 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7435 let events = nodes[2].node.get_and_clear_pending_msg_events();
7436 assert_eq!(events.len(), 1);
7438 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7439 _ => panic!("Unexpected event"),
7442 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7443 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7444 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7445 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7446 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7447 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7448 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7449 let events = nodes[1].node.get_and_clear_pending_msg_events();
7450 assert_eq!(events.len(), 1);
7452 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7453 _ => panic!("Unexpected event"),
7456 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7457 // channel smoothly, opt-out is from channel initiator here
7458 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7459 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7460 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7461 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7462 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7463 let events = nodes[0].node.get_and_clear_pending_msg_events();
7464 assert_eq!(events.len(), 1);
7466 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7467 _ => panic!("Unexpected event"),
7470 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7471 //// channel smoothly
7472 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7473 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7474 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7475 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7476 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7477 let events = nodes[0].node.get_and_clear_pending_msg_events();
7478 assert_eq!(events.len(), 2);
7480 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7481 _ => panic!("Unexpected event"),
7484 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7485 _ => panic!("Unexpected event"),
7490 fn test_upfront_shutdown_script_unsupport_segwit() {
7491 // We test that channel is closed early
7492 // if a segwit program is passed as upfront shutdown script,
7493 // but the peer does not support segwit.
7494 let chanmon_cfgs = create_chanmon_cfgs(2);
7495 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7496 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7497 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7499 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7501 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7502 open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7503 .push_slice(&[0, 0])
7506 let features = InitFeatures::known().clear_shutdown_anysegwit();
7507 nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7509 let events = nodes[0].node.get_and_clear_pending_msg_events();
7510 assert_eq!(events.len(), 1);
7512 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7513 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7514 assert!(regex::Regex::new(r"Peer is signaling upfront_shutdown but has provided a non-accepted scriptpubkey format. script: (\([A-Fa-f0-9]+\))").unwrap().is_match(&*msg.data));
7516 _ => panic!("Unexpected event"),
7521 fn test_shutdown_script_any_segwit_allowed() {
7522 let mut config = UserConfig::default();
7523 config.channel_options.announced_channel = true;
7524 config.peer_channel_config_limits.force_announced_channel_preference = false;
7525 config.channel_options.commit_upfront_shutdown_pubkey = false;
7526 let user_cfgs = [None, Some(config), None];
7527 let chanmon_cfgs = create_chanmon_cfgs(3);
7528 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7529 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7530 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7532 //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7533 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7534 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7535 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7536 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7537 .push_slice(&[0, 0])
7539 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7540 let events = nodes[0].node.get_and_clear_pending_msg_events();
7541 assert_eq!(events.len(), 2);
7543 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7544 _ => panic!("Unexpected event"),
7547 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7548 _ => panic!("Unexpected event"),
7553 fn test_shutdown_script_any_segwit_not_allowed() {
7554 let mut config = UserConfig::default();
7555 config.channel_options.announced_channel = true;
7556 config.peer_channel_config_limits.force_announced_channel_preference = false;
7557 config.channel_options.commit_upfront_shutdown_pubkey = false;
7558 let user_cfgs = [None, Some(config), None];
7559 let chanmon_cfgs = create_chanmon_cfgs(3);
7560 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7561 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7562 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7564 //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7565 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7566 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7567 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7568 // Make an any segwit version script
7569 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7570 .push_slice(&[0, 0])
7572 let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7573 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7574 let events = nodes[0].node.get_and_clear_pending_msg_events();
7575 assert_eq!(events.len(), 2);
7577 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7578 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7579 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7581 _ => panic!("Unexpected event"),
7583 check_added_monitors!(nodes[0], 1);
7587 fn test_shutdown_script_segwit_but_not_anysegwit() {
7588 let mut config = UserConfig::default();
7589 config.channel_options.announced_channel = true;
7590 config.peer_channel_config_limits.force_announced_channel_preference = false;
7591 config.channel_options.commit_upfront_shutdown_pubkey = false;
7592 let user_cfgs = [None, Some(config), None];
7593 let chanmon_cfgs = create_chanmon_cfgs(3);
7594 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7595 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7596 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7598 //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7599 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7600 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7601 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7602 // Make a segwit script that is not a valid as any segwit
7603 node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7604 .push_slice(&[0, 0])
7606 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7607 let events = nodes[0].node.get_and_clear_pending_msg_events();
7608 assert_eq!(events.len(), 2);
7610 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7611 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7612 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7614 _ => panic!("Unexpected event"),
7616 check_added_monitors!(nodes[0], 1);
7620 fn test_user_configurable_csv_delay() {
7621 // We test our channel constructors yield errors when we pass them absurd csv delay
7623 let mut low_our_to_self_config = UserConfig::default();
7624 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7625 let mut high_their_to_self_config = UserConfig::default();
7626 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7627 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7628 let chanmon_cfgs = create_chanmon_cfgs(2);
7629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7633 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7634 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7636 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())); },
7637 _ => panic!("Unexpected event"),
7639 } else { assert!(false) }
7641 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7642 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7643 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7644 open_channel.to_self_delay = 200;
7645 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7647 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())); },
7648 _ => panic!("Unexpected event"),
7650 } else { assert!(false); }
7652 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7653 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7654 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()));
7655 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7656 accept_channel.to_self_delay = 200;
7657 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7658 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7660 &ErrorAction::SendErrorMessage { ref msg } => {
7661 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()));
7663 _ => { assert!(false); }
7665 } else { assert!(false); }
7667 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7668 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7669 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7670 open_channel.to_self_delay = 200;
7671 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7673 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())); },
7674 _ => panic!("Unexpected event"),
7676 } else { assert!(false); }
7680 fn test_data_loss_protect() {
7681 // We want to be sure that :
7682 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7683 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7684 // * we close channel in case of detecting other being fallen behind
7685 // * we are able to claim our own outputs thanks to to_remote being static
7686 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7692 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7693 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7694 // during signing due to revoked tx
7695 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7696 let keys_manager = &chanmon_cfgs[0].keys_manager;
7699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7701 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7703 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7705 // Cache node A state before any channel update
7706 let previous_node_state = nodes[0].node.encode();
7707 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7708 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7710 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7711 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
7713 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7714 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7716 // Restore node A from previous state
7717 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7718 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7719 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7720 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new()), blocks: Arc::new(Mutex::new(Vec::new()))};
7721 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7722 persister = test_utils::TestPersister::new();
7723 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7725 let mut channel_monitors = HashMap::new();
7726 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7727 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7728 keys_manager: keys_manager,
7729 fee_estimator: &fee_estimator,
7730 chain_monitor: &monitor,
7732 tx_broadcaster: &tx_broadcaster,
7733 default_config: UserConfig::default(),
7737 nodes[0].node = &node_state_0;
7738 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7739 nodes[0].chain_monitor = &monitor;
7740 nodes[0].chain_source = &chain_source;
7742 check_added_monitors!(nodes[0], 1);
7744 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7745 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7747 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7749 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7750 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7751 check_added_monitors!(nodes[0], 1);
7754 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7755 assert_eq!(node_txn.len(), 0);
7758 let mut reestablish_1 = Vec::with_capacity(1);
7759 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7760 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7761 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7762 reestablish_1.push(msg.clone());
7763 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7764 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7766 &ErrorAction::SendErrorMessage { ref msg } => {
7767 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");
7769 _ => panic!("Unexpected event!"),
7772 panic!("Unexpected event")
7776 // Check we close channel detecting A is fallen-behind
7777 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7778 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7779 check_added_monitors!(nodes[1], 1);
7782 // Check A is able to claim to_remote output
7783 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7784 assert_eq!(node_txn.len(), 1);
7785 check_spends!(node_txn[0], chan.3);
7786 assert_eq!(node_txn[0].output.len(), 2);
7787 mine_transaction(&nodes[0], &node_txn[0]);
7788 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7789 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7790 assert_eq!(spend_txn.len(), 1);
7791 check_spends!(spend_txn[0], node_txn[0]);
7795 fn test_check_htlc_underpaying() {
7796 // Send payment through A -> B but A is maliciously
7797 // sending a probe payment (i.e less than expected value0
7798 // to B, B should refuse payment.
7800 let chanmon_cfgs = create_chanmon_cfgs(2);
7801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7803 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7805 // Create some initial channels
7806 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7808 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 10_000, TEST_FINAL_CLTV, nodes[0].logger).unwrap();
7809 let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7810 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, 0).unwrap();
7811 nodes[0].node.send_payment(&route, our_payment_hash, &Some(our_payment_secret)).unwrap();
7812 check_added_monitors!(nodes[0], 1);
7814 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7815 assert_eq!(events.len(), 1);
7816 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7817 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7818 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7820 // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7821 // and then will wait a second random delay before failing the HTLC back:
7822 expect_pending_htlcs_forwardable!(nodes[1]);
7823 expect_pending_htlcs_forwardable!(nodes[1]);
7825 // Node 3 is expecting payment of 100_000 but received 10_000,
7826 // it should fail htlc like we didn't know the preimage.
7827 nodes[1].node.process_pending_htlc_forwards();
7829 let events = nodes[1].node.get_and_clear_pending_msg_events();
7830 assert_eq!(events.len(), 1);
7831 let (update_fail_htlc, commitment_signed) = match events[0] {
7832 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 } } => {
7833 assert!(update_add_htlcs.is_empty());
7834 assert!(update_fulfill_htlcs.is_empty());
7835 assert_eq!(update_fail_htlcs.len(), 1);
7836 assert!(update_fail_malformed_htlcs.is_empty());
7837 assert!(update_fee.is_none());
7838 (update_fail_htlcs[0].clone(), commitment_signed)
7840 _ => panic!("Unexpected event"),
7842 check_added_monitors!(nodes[1], 1);
7844 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7845 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7847 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7848 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7849 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7850 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7854 fn test_announce_disable_channels() {
7855 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7856 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7858 let chanmon_cfgs = create_chanmon_cfgs(2);
7859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7863 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7864 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7865 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7868 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7869 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7871 nodes[0].node.timer_tick_occurred(); // Enabled -> DisabledStaged
7872 nodes[0].node.timer_tick_occurred(); // DisabledStaged -> Disabled
7873 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7874 assert_eq!(msg_events.len(), 3);
7875 let mut chans_disabled: HashSet<u64> = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7876 for e in msg_events {
7878 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7879 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7880 // Check that each channel gets updated exactly once
7881 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7882 panic!("Generated ChannelUpdate for wrong chan!");
7885 _ => panic!("Unexpected event"),
7889 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7890 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7891 assert_eq!(reestablish_1.len(), 3);
7892 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7893 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7894 assert_eq!(reestablish_2.len(), 3);
7896 // Reestablish chan_1
7897 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7898 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7899 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7900 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7901 // Reestablish chan_2
7902 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7903 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7904 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7905 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7906 // Reestablish chan_3
7907 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7908 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7909 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7910 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7912 nodes[0].node.timer_tick_occurred();
7913 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7914 nodes[0].node.timer_tick_occurred();
7915 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7916 assert_eq!(msg_events.len(), 3);
7917 chans_disabled = [short_id_1, short_id_2, short_id_3].iter().map(|a| *a).collect();
7918 for e in msg_events {
7920 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7921 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7922 // Check that each channel gets updated exactly once
7923 if !chans_disabled.remove(&msg.contents.short_channel_id) {
7924 panic!("Generated ChannelUpdate for wrong chan!");
7927 _ => panic!("Unexpected event"),
7933 fn test_bump_penalty_txn_on_revoked_commitment() {
7934 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7935 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7937 let chanmon_cfgs = create_chanmon_cfgs(2);
7938 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7939 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7940 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7942 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7943 let logger = test_utils::TestLogger::new();
7945 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7946 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7947 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7948 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7950 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7951 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7952 assert_eq!(revoked_txn[0].output.len(), 4);
7953 assert_eq!(revoked_txn[0].input.len(), 1);
7954 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7955 let revoked_txid = revoked_txn[0].txid();
7957 let mut penalty_sum = 0;
7958 for outp in revoked_txn[0].output.iter() {
7959 if outp.script_pubkey.is_v0_p2wsh() {
7960 penalty_sum += outp.value;
7964 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7965 let header_114 = connect_blocks(&nodes[1], 14);
7967 // Actually revoke tx by claiming a HTLC
7968 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7969 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7970 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7971 check_added_monitors!(nodes[1], 1);
7973 // One or more justice tx should have been broadcast, check it
7977 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7978 assert_eq!(node_txn.len(), 2); // justice tx (broadcasted from ChannelMonitor) + local commitment tx
7979 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7980 assert_eq!(node_txn[0].output.len(), 1);
7981 check_spends!(node_txn[0], revoked_txn[0]);
7982 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7983 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7984 penalty_1 = node_txn[0].txid();
7988 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7989 connect_blocks(&nodes[1], 15);
7990 let mut penalty_2 = penalty_1;
7991 let mut feerate_2 = 0;
7993 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7994 assert_eq!(node_txn.len(), 1);
7995 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7996 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7997 assert_eq!(node_txn[0].output.len(), 1);
7998 check_spends!(node_txn[0], revoked_txn[0]);
7999 penalty_2 = node_txn[0].txid();
8000 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
8001 assert_ne!(penalty_2, penalty_1);
8002 let fee_2 = penalty_sum - node_txn[0].output[0].value;
8003 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
8004 // Verify 25% bump heuristic
8005 assert!(feerate_2 * 100 >= feerate_1 * 125);
8009 assert_ne!(feerate_2, 0);
8011 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
8012 connect_blocks(&nodes[1], 1);
8014 let mut feerate_3 = 0;
8016 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8017 assert_eq!(node_txn.len(), 1);
8018 if node_txn[0].input[0].previous_output.txid == revoked_txid {
8019 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
8020 assert_eq!(node_txn[0].output.len(), 1);
8021 check_spends!(node_txn[0], revoked_txn[0]);
8022 penalty_3 = node_txn[0].txid();
8023 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
8024 assert_ne!(penalty_3, penalty_2);
8025 let fee_3 = penalty_sum - node_txn[0].output[0].value;
8026 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
8027 // Verify 25% bump heuristic
8028 assert!(feerate_3 * 100 >= feerate_2 * 125);
8032 assert_ne!(feerate_3, 0);
8034 nodes[1].node.get_and_clear_pending_events();
8035 nodes[1].node.get_and_clear_pending_msg_events();
8039 fn test_bump_penalty_txn_on_revoked_htlcs() {
8040 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
8041 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
8043 let mut chanmon_cfgs = create_chanmon_cfgs(2);
8044 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
8045 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8046 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8047 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8049 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8050 // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
8051 let route = get_route(&nodes[0].node.get_our_node_id(), &nodes[0].net_graph_msg_handler.network_graph.read().unwrap(),
8052 &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
8053 let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
8054 let route = get_route(&nodes[1].node.get_our_node_id(), &nodes[1].net_graph_msg_handler.network_graph.read().unwrap(),
8055 &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3_000_000, 50, nodes[0].logger).unwrap();
8056 send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
8058 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8059 assert_eq!(revoked_local_txn[0].input.len(), 1);
8060 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8062 // Revoke local commitment tx
8063 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8065 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8066 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
8067 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
8068 check_closed_broadcast!(nodes[1], true);
8069 check_added_monitors!(nodes[1], 1);
8070 connect_blocks(&nodes[1], 49); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
8072 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8073 assert_eq!(revoked_htlc_txn.len(), 3);
8074 check_spends!(revoked_htlc_txn[1], chan.3);
8076 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
8077 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
8078 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
8080 assert_eq!(revoked_htlc_txn[2].input.len(), 1);
8081 assert_eq!(revoked_htlc_txn[2].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8082 assert_eq!(revoked_htlc_txn[2].output.len(), 1);
8083 check_spends!(revoked_htlc_txn[2], revoked_local_txn[0]);
8085 // Broadcast set of revoked txn on A
8086 let hash_128 = connect_blocks(&nodes[0], 40);
8087 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8088 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
8089 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8090 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[2].clone()] });
8091 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8096 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8097 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
8098 // Verify claim tx are spending revoked HTLC txn
8100 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
8101 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
8102 // which are included in the same block (they are broadcasted because we scan the
8103 // transactions linearly and generate claims as we go, they likely should be removed in the
8105 assert_eq!(node_txn[0].input.len(), 1);
8106 check_spends!(node_txn[0], revoked_local_txn[0]);
8107 assert_eq!(node_txn[1].input.len(), 1);
8108 check_spends!(node_txn[1], revoked_local_txn[0]);
8109 assert_eq!(node_txn[2].input.len(), 1);
8110 check_spends!(node_txn[2], revoked_local_txn[0]);
8112 // Each of the three justice transactions claim a separate (single) output of the three
8113 // available, which we check here:
8114 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
8115 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
8116 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
8118 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8119 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8121 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
8122 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
8123 // a remote commitment tx has already been confirmed).
8124 check_spends!(node_txn[3], chan.3);
8126 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
8127 // output, checked above).
8128 assert_eq!(node_txn[4].input.len(), 2);
8129 assert_eq!(node_txn[4].output.len(), 1);
8130 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8132 first = node_txn[4].txid();
8133 // Store both feerates for later comparison
8134 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[4].output[0].value;
8135 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
8136 penalty_txn = vec![node_txn[2].clone()];
8140 // Connect one more block to see if bumped penalty are issued for HTLC txn
8141 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8142 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8143 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8144 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
8146 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8147 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
8149 check_spends!(node_txn[0], revoked_local_txn[0]);
8150 check_spends!(node_txn[1], revoked_local_txn[0]);
8151 // Note that these are both bogus - they spend outputs already claimed in block 129:
8152 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
8153 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8155 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[2].input[0].previous_output);
8156 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
8162 // Few more blocks to confirm penalty txn
8163 connect_blocks(&nodes[0], 4);
8164 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
8165 let header_144 = connect_blocks(&nodes[0], 9);
8167 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8168 assert_eq!(node_txn.len(), 1);
8170 assert_eq!(node_txn[0].input.len(), 2);
8171 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[2]);
8172 // Verify bumped tx is different and 25% bump heuristic
8173 assert_ne!(first, node_txn[0].txid());
8174 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[2].output[0].value - node_txn[0].output[0].value;
8175 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
8176 assert!(feerate_2 * 100 > feerate_1 * 125);
8177 let txn = vec![node_txn[0].clone()];
8181 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
8182 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8183 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
8184 connect_blocks(&nodes[0], 20);
8186 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8187 // We verify than no new transaction has been broadcast because previously
8188 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
8189 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
8190 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
8191 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
8192 // up bumped justice generation.
8193 assert_eq!(node_txn.len(), 0);
8196 check_closed_broadcast!(nodes[0], true);
8197 check_added_monitors!(nodes[0], 1);
8201 fn test_bump_penalty_txn_on_remote_commitment() {
8202 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
8203 // we're able to claim outputs on remote commitment transaction before timelocks expiration
8206 // Provide preimage for one
8207 // Check aggregation
8209 let chanmon_cfgs = create_chanmon_cfgs(2);
8210 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8211 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8212 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8214 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8215 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
8216 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
8218 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
8219 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
8220 assert_eq!(remote_txn[0].output.len(), 4);
8221 assert_eq!(remote_txn[0].input.len(), 1);
8222 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8224 // Claim a HTLC without revocation (provide B monitor with preimage)
8225 nodes[1].node.claim_funds(payment_preimage);
8226 mine_transaction(&nodes[1], &remote_txn[0]);
8227 check_added_monitors!(nodes[1], 2);
8228 connect_blocks(&nodes[1], TEST_FINAL_CLTV - 1); // Confirm blocks until the HTLC expires
8230 // One or more claim tx should have been broadcast, check it
8234 let feerate_timeout;
8235 let feerate_preimage;
8237 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8238 // 9 transactions including:
8239 // 1*2 ChannelManager local broadcasts of commitment + HTLC-Success
8240 // 1*3 ChannelManager local broadcasts of commitment + HTLC-Success + HTLC-Timeout
8241 // 2 * HTLC-Success (one RBF bump we'll check later)
8243 assert_eq!(node_txn.len(), 8);
8244 assert_eq!(node_txn[0].input.len(), 1);
8245 assert_eq!(node_txn[6].input.len(), 1);
8246 check_spends!(node_txn[0], remote_txn[0]);
8247 check_spends!(node_txn[6], remote_txn[0]);
8248 assert_eq!(node_txn[0].input[0].previous_output, node_txn[3].input[0].previous_output);
8249 preimage_bump = node_txn[3].clone();
8251 check_spends!(node_txn[1], chan.3);
8252 check_spends!(node_txn[2], node_txn[1]);
8253 assert_eq!(node_txn[1], node_txn[4]);
8254 assert_eq!(node_txn[2], node_txn[5]);
8256 timeout = node_txn[6].txid();
8257 let index = node_txn[6].input[0].previous_output.vout;
8258 let fee = remote_txn[0].output[index as usize].value - node_txn[6].output[0].value;
8259 feerate_timeout = fee * 1000 / node_txn[6].get_weight() as u64;
8261 preimage = node_txn[0].txid();
8262 let index = node_txn[0].input[0].previous_output.vout;
8263 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8264 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8268 assert_ne!(feerate_timeout, 0);
8269 assert_ne!(feerate_preimage, 0);
8271 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8272 connect_blocks(&nodes[1], 15);
8274 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8275 assert_eq!(node_txn.len(), 1);
8276 assert_eq!(node_txn[0].input.len(), 1);
8277 assert_eq!(preimage_bump.input.len(), 1);
8278 check_spends!(node_txn[0], remote_txn[0]);
8279 check_spends!(preimage_bump, remote_txn[0]);
8281 let index = preimage_bump.input[0].previous_output.vout;
8282 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
8283 let new_feerate = fee * 1000 / preimage_bump.get_weight() as u64;
8284 assert!(new_feerate * 100 > feerate_timeout * 125);
8285 assert_ne!(timeout, preimage_bump.txid());
8287 let index = node_txn[0].input[0].previous_output.vout;
8288 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8289 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8290 assert!(new_feerate * 100 > feerate_preimage * 125);
8291 assert_ne!(preimage, node_txn[0].txid());
8296 nodes[1].node.get_and_clear_pending_events();
8297 nodes[1].node.get_and_clear_pending_msg_events();
8301 fn test_counterparty_raa_skip_no_crash() {
8302 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8303 // commitment transaction, we would have happily carried on and provided them the next
8304 // commitment transaction based on one RAA forward. This would probably eventually have led to
8305 // channel closure, but it would not have resulted in funds loss. Still, our
8306 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8307 // check simply that the channel is closed in response to such an RAA, but don't check whether
8308 // we decide to punish our counterparty for revoking their funds (as we don't currently
8310 let chanmon_cfgs = create_chanmon_cfgs(2);
8311 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8312 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8313 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8314 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8316 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8317 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8318 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8319 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8320 // Must revoke without gaps
8321 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8322 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8323 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8325 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8326 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8327 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8328 check_added_monitors!(nodes[1], 1);
8332 fn test_bump_txn_sanitize_tracking_maps() {
8333 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8334 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8336 let chanmon_cfgs = create_chanmon_cfgs(2);
8337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8339 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8341 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8342 // Lock HTLC in both directions
8343 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8344 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8346 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8347 assert_eq!(revoked_local_txn[0].input.len(), 1);
8348 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8350 // Revoke local commitment tx
8351 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
8353 // Broadcast set of revoked txn on A
8354 connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
8355 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8356 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8358 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8359 check_closed_broadcast!(nodes[0], true);
8360 check_added_monitors!(nodes[0], 1);
8362 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8363 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8364 check_spends!(node_txn[0], revoked_local_txn[0]);
8365 check_spends!(node_txn[1], revoked_local_txn[0]);
8366 check_spends!(node_txn[2], revoked_local_txn[0]);
8367 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8371 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8372 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8373 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8375 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8376 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8377 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8378 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8384 fn test_override_channel_config() {
8385 let chanmon_cfgs = create_chanmon_cfgs(2);
8386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8390 // Node0 initiates a channel to node1 using the override config.
8391 let mut override_config = UserConfig::default();
8392 override_config.own_channel_config.our_to_self_delay = 200;
8394 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8396 // Assert the channel created by node0 is using the override config.
8397 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8398 assert_eq!(res.channel_flags, 0);
8399 assert_eq!(res.to_self_delay, 200);
8403 fn test_override_0msat_htlc_minimum() {
8404 let mut zero_config = UserConfig::default();
8405 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8406 let chanmon_cfgs = create_chanmon_cfgs(2);
8407 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8408 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8409 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8411 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8412 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8413 assert_eq!(res.htlc_minimum_msat, 1);
8415 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8416 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8417 assert_eq!(res.htlc_minimum_msat, 1);
8421 fn test_simple_mpp() {
8422 // Simple test of sending a multi-path payment.
8423 let chanmon_cfgs = create_chanmon_cfgs(4);
8424 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8425 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8426 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8428 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8429 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8430 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8431 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8432 let logger = test_utils::TestLogger::new();
8434 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(&nodes[3]);
8435 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8436 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8437 let path = route.paths[0].clone();
8438 route.paths.push(path);
8439 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8440 route.paths[0][0].short_channel_id = chan_1_id;
8441 route.paths[0][1].short_channel_id = chan_3_id;
8442 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8443 route.paths[1][0].short_channel_id = chan_2_id;
8444 route.paths[1][1].short_channel_id = chan_4_id;
8445 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8446 claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8450 fn test_preimage_storage() {
8451 // Simple test of payment preimage storage allowing no client-side storage to claim payments
8452 let chanmon_cfgs = create_chanmon_cfgs(2);
8453 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8454 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8455 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8457 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8460 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, 42);
8462 let logger = test_utils::TestLogger::new();
8463 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8464 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8465 nodes[0].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8466 check_added_monitors!(nodes[0], 1);
8467 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8468 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8469 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8470 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8472 // Note that after leaving the above scope we have no knowledge of any arguments or return
8473 // values from previous calls.
8474 expect_pending_htlcs_forwardable!(nodes[1]);
8475 let events = nodes[1].node.get_and_clear_pending_events();
8476 assert_eq!(events.len(), 1);
8478 Event::PaymentReceived { payment_preimage, user_payment_id, .. } => {
8479 assert_eq!(user_payment_id, 42);
8480 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8482 _ => panic!("Unexpected event"),
8487 fn test_secret_timeout() {
8488 // Simple test of payment secret storage time outs
8489 let chanmon_cfgs = create_chanmon_cfgs(2);
8490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8494 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8496 let (payment_hash, payment_secret_1) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8498 // We should fail to register the same payment hash twice, at least until we've connected a
8499 // block with time 7200 + CHAN_CONFIRM_DEPTH + 1.
8500 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8501 assert_eq!(err, "Duplicate payment hash");
8502 } else { panic!(); }
8504 let node_1_blocks = nodes[1].blocks.lock().unwrap();
8506 header: BlockHeader {
8508 prev_blockhash: node_1_blocks.last().unwrap().0.block_hash(),
8509 merkle_root: Default::default(),
8510 time: node_1_blocks.len() as u32 + 7200, bits: 42, nonce: 42 },
8514 connect_block(&nodes[1], &block);
8515 if let Err(APIError::APIMisuseError { err }) = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 0) {
8516 assert_eq!(err, "Duplicate payment hash");
8517 } else { panic!(); }
8519 // If we then connect the second block, we should be able to register the same payment hash
8520 // again with a different user_payment_id (this time getting a new payment secret).
8521 block.header.prev_blockhash = block.header.block_hash();
8522 block.header.time += 1;
8523 connect_block(&nodes[1], &block);
8524 let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(payment_hash, Some(100_000), 2, 42).unwrap();
8525 assert_ne!(payment_secret_1, our_payment_secret);
8528 let logger = test_utils::TestLogger::new();
8529 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8530 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8531 nodes[0].node.send_payment(&route, payment_hash, &Some(our_payment_secret)).unwrap();
8532 check_added_monitors!(nodes[0], 1);
8533 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8534 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8535 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8536 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8538 // Note that after leaving the above scope we have no knowledge of any arguments or return
8539 // values from previous calls.
8540 expect_pending_htlcs_forwardable!(nodes[1]);
8541 let events = nodes[1].node.get_and_clear_pending_events();
8542 assert_eq!(events.len(), 1);
8544 Event::PaymentReceived { payment_preimage, payment_secret, user_payment_id, .. } => {
8545 assert!(payment_preimage.is_none());
8546 assert_eq!(user_payment_id, 42);
8547 assert_eq!(payment_secret, our_payment_secret);
8548 // We don't actually have the payment preimage with which to claim this payment!
8550 _ => panic!("Unexpected event"),
8555 fn test_bad_secret_hash() {
8556 // Simple test of unregistered payment hash/invalid payment secret handling
8557 let chanmon_cfgs = create_chanmon_cfgs(2);
8558 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8559 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8560 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8562 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8564 let random_payment_hash = PaymentHash([42; 32]);
8565 let random_payment_secret = PaymentSecret([43; 32]);
8566 let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, 0);
8568 let logger = test_utils::TestLogger::new();
8569 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8570 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &[], 100_000, TEST_FINAL_CLTV, &logger).unwrap();
8572 // All the below cases should end up being handled exactly identically, so we macro the
8573 // resulting events.
8574 macro_rules! handle_unknown_invalid_payment_data {
8576 check_added_monitors!(nodes[0], 1);
8577 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8578 let payment_event = SendEvent::from_event(events.pop().unwrap());
8579 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8580 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8582 // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8583 // again to process the pending backwards-failure of the HTLC
8584 expect_pending_htlcs_forwardable!(nodes[1]);
8585 expect_pending_htlcs_forwardable!(nodes[1]);
8586 check_added_monitors!(nodes[1], 1);
8588 // We should fail the payment back
8589 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8590 match events.pop().unwrap() {
8591 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8592 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8593 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8595 _ => panic!("Unexpected event"),
8600 let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8601 // Error data is the HTLC value (100,000) and current block height
8602 let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8604 // Send a payment with the right payment hash but the wrong payment secret
8605 nodes[0].node.send_payment(&route, our_payment_hash, &Some(random_payment_secret)).unwrap();
8606 handle_unknown_invalid_payment_data!();
8607 expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8609 // Send a payment with a random payment hash, but the right payment secret
8610 nodes[0].node.send_payment(&route, random_payment_hash, &Some(our_payment_secret)).unwrap();
8611 handle_unknown_invalid_payment_data!();
8612 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8614 // Send a payment with a random payment hash and random payment secret
8615 nodes[0].node.send_payment(&route, random_payment_hash, &Some(random_payment_secret)).unwrap();
8616 handle_unknown_invalid_payment_data!();
8617 expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8621 fn test_update_err_monitor_lockdown() {
8622 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8623 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8624 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8626 // This scenario may happen in a watchtower setup, where watchtower process a block height
8627 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8628 // commitment at same time.
8630 let chanmon_cfgs = create_chanmon_cfgs(2);
8631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8633 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8635 // Create some initial channel
8636 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8637 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8639 // Rebalance the network to generate htlc in the two directions
8640 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8642 // Route a HTLC from node 0 to node 1 (but don't settle)
8643 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8645 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8646 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8647 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8648 let persister = test_utils::TestPersister::new();
8650 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8651 let monitor = monitors.get(&outpoint).unwrap();
8652 let mut w = test_utils::TestVecWriter(Vec::new());
8653 monitor.write(&mut w).unwrap();
8654 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8655 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8656 assert!(new_monitor == *monitor);
8657 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);
8658 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8661 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8662 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8663 // transaction lock time requirements here.
8664 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (header, 0));
8665 watchtower.chain_monitor.block_connected(&Block { header, txdata: vec![] }, 200);
8667 // Try to update ChannelMonitor
8668 assert!(nodes[1].node.claim_funds(preimage));
8669 check_added_monitors!(nodes[1], 1);
8670 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8671 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8672 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8673 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8674 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8675 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8676 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8677 } else { assert!(false); }
8678 } else { assert!(false); };
8679 // Our local monitor is in-sync and hasn't processed yet timeout
8680 check_added_monitors!(nodes[0], 1);
8681 let events = nodes[0].node.get_and_clear_pending_events();
8682 assert_eq!(events.len(), 1);
8686 fn test_concurrent_monitor_claim() {
8687 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8688 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8689 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8690 // state N+1 confirms. Alice claims output from state N+1.
8692 let chanmon_cfgs = create_chanmon_cfgs(2);
8693 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8694 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8695 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8697 // Create some initial channel
8698 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8699 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8701 // Rebalance the network to generate htlc in the two directions
8702 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8704 // Route a HTLC from node 0 to node 1 (but don't settle)
8705 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8707 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8708 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8709 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8710 let persister = test_utils::TestPersister::new();
8711 let watchtower_alice = {
8712 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8713 let monitor = monitors.get(&outpoint).unwrap();
8714 let mut w = test_utils::TestVecWriter(Vec::new());
8715 monitor.write(&mut w).unwrap();
8716 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8717 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8718 assert!(new_monitor == *monitor);
8719 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);
8720 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8723 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8724 // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8725 // transaction lock time requirements here.
8726 chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize((CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS) as usize, (header, 0));
8727 watchtower_alice.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8729 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8731 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8732 assert_eq!(txn.len(), 2);
8736 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8737 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8738 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8739 let persister = test_utils::TestPersister::new();
8740 let watchtower_bob = {
8741 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8742 let monitor = monitors.get(&outpoint).unwrap();
8743 let mut w = test_utils::TestVecWriter(Vec::new());
8744 monitor.write(&mut w).unwrap();
8745 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8746 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8747 assert!(new_monitor == *monitor);
8748 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);
8749 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8752 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8753 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8755 // Route another payment to generate another update with still previous HTLC pending
8756 let (_, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[0]);
8758 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8759 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), Some(InvoiceFeatures::known()), None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8760 nodes[1].node.send_payment(&route, payment_hash, &Some(payment_secret)).unwrap();
8762 check_added_monitors!(nodes[1], 1);
8764 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8765 assert_eq!(updates.update_add_htlcs.len(), 1);
8766 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8767 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8768 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8769 // Watchtower Alice should already have seen the block and reject the update
8770 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8771 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8772 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8773 } else { assert!(false); }
8774 } else { assert!(false); };
8775 // Our local monitor is in-sync and hasn't processed yet timeout
8776 check_added_monitors!(nodes[0], 1);
8778 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8779 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8780 watchtower_bob.chain_monitor.block_connected(&Block { header, txdata: vec![] }, CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8782 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8785 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8786 assert_eq!(txn.len(), 2);
8787 bob_state_y = txn[0].clone();
8791 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8792 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8793 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);
8795 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8796 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8797 // the onchain detection of the HTLC output
8798 assert_eq!(htlc_txn.len(), 2);
8799 check_spends!(htlc_txn[0], bob_state_y);
8800 check_spends!(htlc_txn[1], bob_state_y);
8805 fn test_pre_lockin_no_chan_closed_update() {
8806 // Test that if a peer closes a channel in response to a funding_created message we don't
8807 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8810 // Doing so would imply a channel monitor update before the initial channel monitor
8811 // registration, violating our API guarantees.
8813 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8814 // then opening a second channel with the same funding output as the first (which is not
8815 // rejected because the first channel does not exist in the ChannelManager) and closing it
8816 // before receiving funding_signed.
8817 let chanmon_cfgs = create_chanmon_cfgs(2);
8818 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8819 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8820 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8822 // Create an initial channel
8823 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8824 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8825 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8826 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8827 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8829 // Move the first channel through the funding flow...
8830 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8832 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8833 check_added_monitors!(nodes[0], 0);
8835 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8836 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8837 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8838 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8842 fn test_htlc_no_detection() {
8843 // This test is a mutation to underscore the detection logic bug we had
8844 // before #653. HTLC value routed is above the remaining balance, thus
8845 // inverting HTLC and `to_remote` output. HTLC will come second and
8846 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8847 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8848 // outputs order detection for correct spending children filtring.
8850 let chanmon_cfgs = create_chanmon_cfgs(2);
8851 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8852 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8853 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8855 // Create some initial channels
8856 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8858 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8859 let (_, our_payment_hash, _) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8860 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8861 assert_eq!(local_txn[0].input.len(), 1);
8862 assert_eq!(local_txn[0].output.len(), 3);
8863 check_spends!(local_txn[0], chan_1.3);
8865 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8866 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8867 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8868 // We deliberately connect the local tx twice as this should provoke a failure calling
8869 // this test before #653 fix.
8870 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);
8871 check_closed_broadcast!(nodes[0], true);
8872 check_added_monitors!(nodes[0], 1);
8873 connect_blocks(&nodes[0], TEST_FINAL_CLTV - 1);
8875 let htlc_timeout = {
8876 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8877 assert_eq!(node_txn[1].input.len(), 1);
8878 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8879 check_spends!(node_txn[1], local_txn[0]);
8883 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8884 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8885 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8886 expect_payment_failed!(nodes[0], our_payment_hash, true);
8889 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8890 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8891 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8892 // Carol, Alice would be the upstream node, and Carol the downstream.)
8894 // Steps of the test:
8895 // 1) Alice sends a HTLC to Carol through Bob.
8896 // 2) Carol doesn't settle the HTLC.
8897 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8898 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8899 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8900 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8901 // 5) Carol release the preimage to Bob off-chain.
8902 // 6) Bob claims the offered output on the broadcasted commitment.
8903 let chanmon_cfgs = create_chanmon_cfgs(3);
8904 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8905 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8906 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8908 // Create some initial channels
8909 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8910 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8912 // Steps (1) and (2):
8913 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8914 let (payment_preimage, _payment_hash, _payment_secret) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8916 // Check that Alice's commitment transaction now contains an output for this HTLC.
8917 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8918 check_spends!(alice_txn[0], chan_ab.3);
8919 assert_eq!(alice_txn[0].output.len(), 2);
8920 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8921 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8922 assert_eq!(alice_txn.len(), 2);
8924 // Steps (3) and (4):
8925 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8926 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8927 let mut force_closing_node = 0; // Alice force-closes
8928 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8929 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8930 check_closed_broadcast!(nodes[force_closing_node], true);
8931 check_added_monitors!(nodes[force_closing_node], 1);
8932 if go_onchain_before_fulfill {
8933 let txn_to_broadcast = match broadcast_alice {
8934 true => alice_txn.clone(),
8935 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8937 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8938 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8939 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8940 if broadcast_alice {
8941 check_closed_broadcast!(nodes[1], true);
8942 check_added_monitors!(nodes[1], 1);
8944 assert_eq!(bob_txn.len(), 1);
8945 check_spends!(bob_txn[0], chan_ab.3);
8949 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8950 // process of removing the HTLC from their commitment transactions.
8951 assert!(nodes[2].node.claim_funds(payment_preimage));
8952 check_added_monitors!(nodes[2], 1);
8953 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8954 assert!(carol_updates.update_add_htlcs.is_empty());
8955 assert!(carol_updates.update_fail_htlcs.is_empty());
8956 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8957 assert!(carol_updates.update_fee.is_none());
8958 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8960 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8961 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8962 if !go_onchain_before_fulfill && broadcast_alice {
8963 let events = nodes[1].node.get_and_clear_pending_msg_events();
8964 assert_eq!(events.len(), 1);
8966 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8967 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8969 _ => panic!("Unexpected event"),
8972 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8973 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8974 // Carol<->Bob's updated commitment transaction info.
8975 check_added_monitors!(nodes[1], 2);
8977 let events = nodes[1].node.get_and_clear_pending_msg_events();
8978 assert_eq!(events.len(), 2);
8979 let bob_revocation = match events[0] {
8980 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8981 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8984 _ => panic!("Unexpected event"),
8986 let bob_updates = match events[1] {
8987 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8988 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8991 _ => panic!("Unexpected event"),
8994 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8995 check_added_monitors!(nodes[2], 1);
8996 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8997 check_added_monitors!(nodes[2], 1);
8999 let events = nodes[2].node.get_and_clear_pending_msg_events();
9000 assert_eq!(events.len(), 1);
9001 let carol_revocation = match events[0] {
9002 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
9003 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
9006 _ => panic!("Unexpected event"),
9008 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
9009 check_added_monitors!(nodes[1], 1);
9011 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
9012 // here's where we put said channel's commitment tx on-chain.
9013 let mut txn_to_broadcast = alice_txn.clone();
9014 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
9015 if !go_onchain_before_fulfill {
9016 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
9017 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
9018 // If Bob was the one to force-close, he will have already passed these checks earlier.
9019 if broadcast_alice {
9020 check_closed_broadcast!(nodes[1], true);
9021 check_added_monitors!(nodes[1], 1);
9023 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
9024 if broadcast_alice {
9025 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
9026 // new block being connected. The ChannelManager being notified triggers a monitor update,
9027 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
9028 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
9030 assert_eq!(bob_txn.len(), 3);
9031 check_spends!(bob_txn[1], chan_ab.3);
9033 assert_eq!(bob_txn.len(), 2);
9034 check_spends!(bob_txn[0], chan_ab.3);
9039 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
9040 // broadcasted commitment transaction.
9042 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
9043 if go_onchain_before_fulfill {
9044 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
9045 assert_eq!(bob_txn.len(), 2);
9047 let script_weight = match broadcast_alice {
9048 true => OFFERED_HTLC_SCRIPT_WEIGHT,
9049 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
9051 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
9052 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
9053 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
9054 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
9055 if broadcast_alice && !go_onchain_before_fulfill {
9056 check_spends!(bob_txn[0], txn_to_broadcast[0]);
9057 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
9059 check_spends!(bob_txn[1], txn_to_broadcast[0]);
9060 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
9066 fn test_onchain_htlc_settlement_after_close() {
9067 do_test_onchain_htlc_settlement_after_close(true, true);
9068 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
9069 do_test_onchain_htlc_settlement_after_close(true, false);
9070 do_test_onchain_htlc_settlement_after_close(false, false);
9074 fn test_duplicate_chan_id() {
9075 // Test that if a given peer tries to open a channel with the same channel_id as one that is
9076 // already open we reject it and keep the old channel.
9078 // Previously, full_stack_target managed to figure out that if you tried to open two channels
9079 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9080 // the existing channel when we detect the duplicate new channel, screwing up our monitor
9081 // updating logic for the existing channel.
9082 let chanmon_cfgs = create_chanmon_cfgs(2);
9083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9087 // Create an initial channel
9088 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9089 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9090 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9091 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9093 // Try to create a second channel with the same temporary_channel_id as the first and check
9094 // that it is rejected.
9095 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9097 let events = nodes[1].node.get_and_clear_pending_msg_events();
9098 assert_eq!(events.len(), 1);
9100 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9101 // Technically, at this point, nodes[1] would be justified in thinking both the
9102 // first (valid) and second (invalid) channels are closed, given they both have
9103 // the same non-temporary channel_id. However, currently we do not, so we just
9104 // move forward with it.
9105 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9106 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9108 _ => panic!("Unexpected event"),
9112 // Move the first channel through the funding flow...
9113 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
9115 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
9116 check_added_monitors!(nodes[0], 0);
9118 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9119 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9121 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9122 assert_eq!(added_monitors.len(), 1);
9123 assert_eq!(added_monitors[0].0, funding_output);
9124 added_monitors.clear();
9126 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9128 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9129 let channel_id = funding_outpoint.to_channel_id();
9131 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9134 // First try to open a second channel with a temporary channel id equal to the txid-based one.
9135 // Technically this is allowed by the spec, but we don't support it and there's little reason
9136 // to. Still, it shouldn't cause any other issues.
9137 open_chan_msg.temporary_channel_id = channel_id;
9138 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
9140 let events = nodes[1].node.get_and_clear_pending_msg_events();
9141 assert_eq!(events.len(), 1);
9143 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9144 // Technically, at this point, nodes[1] would be justified in thinking both
9145 // channels are closed, but currently we do not, so we just move forward with it.
9146 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9147 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9149 _ => panic!("Unexpected event"),
9153 // Now try to create a second channel which has a duplicate funding output.
9154 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
9155 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9156 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
9157 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()));
9158 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
9160 let funding_created = {
9161 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
9162 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
9163 let logger = test_utils::TestLogger::new();
9164 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
9166 check_added_monitors!(nodes[0], 0);
9167 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9168 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
9169 // still needs to be cleared here.
9170 check_added_monitors!(nodes[1], 1);
9172 // ...still, nodes[1] will reject the duplicate channel.
9174 let events = nodes[1].node.get_and_clear_pending_msg_events();
9175 assert_eq!(events.len(), 1);
9177 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9178 // Technically, at this point, nodes[1] would be justified in thinking both
9179 // channels are closed, but currently we do not, so we just move forward with it.
9180 assert_eq!(msg.channel_id, channel_id);
9181 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9183 _ => panic!("Unexpected event"),
9187 // finally, finish creating the original channel and send a payment over it to make sure
9188 // everything is functional.
9189 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9191 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9192 assert_eq!(added_monitors.len(), 1);
9193 assert_eq!(added_monitors[0].0, funding_output);
9194 added_monitors.clear();
9197 let events_4 = nodes[0].node.get_and_clear_pending_events();
9198 assert_eq!(events_4.len(), 0);
9199 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9200 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
9202 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9203 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
9204 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9205 send_payment(&nodes[0], &[&nodes[1]], 8000000);
9209 fn test_error_chans_closed() {
9210 // Test that we properly handle error messages, closing appropriate channels.
9212 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9213 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9214 // we can test various edge cases around it to ensure we don't regress.
9215 let chanmon_cfgs = create_chanmon_cfgs(3);
9216 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9217 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9218 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9220 // Create some initial channels
9221 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9222 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9223 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9225 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9226 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9227 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9229 // Closing a channel from a different peer has no effect
9230 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9231 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9233 // Closing one channel doesn't impact others
9234 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9235 check_added_monitors!(nodes[0], 1);
9236 check_closed_broadcast!(nodes[0], false);
9237 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9238 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9239 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);
9240 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);
9242 // A null channel ID should close all channels
9243 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
9244 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
9245 check_added_monitors!(nodes[0], 2);
9246 let events = nodes[0].node.get_and_clear_pending_msg_events();
9247 assert_eq!(events.len(), 2);
9249 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9250 assert_eq!(msg.contents.flags & 2, 2);
9252 _ => panic!("Unexpected event"),
9255 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9256 assert_eq!(msg.contents.flags & 2, 2);
9258 _ => panic!("Unexpected event"),
9260 // Note that at this point users of a standard PeerHandler will end up calling
9261 // peer_disconnected with no_connection_possible set to false, duplicating the
9262 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
9263 // users with their own peer handling logic. We duplicate the call here, however.
9264 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9265 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9267 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
9268 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9269 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9273 fn test_invalid_funding_tx() {
9274 // Test that we properly handle invalid funding transactions sent to us from a peer.
9276 // Previously, all other major lightning implementations had failed to properly sanitize
9277 // funding transactions from their counterparties, leading to a multi-implementation critical
9278 // security vulnerability (though we always sanitized properly, we've previously had
9279 // un-released crashes in the sanitization process).
9280 let chanmon_cfgs = create_chanmon_cfgs(2);
9281 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9282 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9283 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9285 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None).unwrap();
9286 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()));
9287 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()));
9289 let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], 100_000, 42);
9290 for output in tx.output.iter_mut() {
9291 // Make the confirmed funding transaction have a bogus script_pubkey
9292 output.script_pubkey = bitcoin::Script::new();
9295 nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, tx.clone(), 0).unwrap();
9296 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()));
9297 check_added_monitors!(nodes[1], 1);
9299 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()));
9300 check_added_monitors!(nodes[0], 1);
9302 let events_1 = nodes[0].node.get_and_clear_pending_events();
9303 assert_eq!(events_1.len(), 0);
9305 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9306 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9307 nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9309 confirm_transaction_at(&nodes[1], &tx, 1);
9310 check_added_monitors!(nodes[1], 1);
9311 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9312 assert_eq!(events_2.len(), 1);
9313 if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9314 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9315 if let msgs::ErrorAction::SendErrorMessage { msg } = action {
9316 assert_eq!(msg.data, "funding tx had wrong script/value or output index");
9317 } else { panic!(); }
9318 } else { panic!(); }
9319 assert_eq!(nodes[1].node.list_channels().len(), 0);