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.
16 use chain::channelmonitor;
17 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
18 use chain::transaction::OutPoint;
19 use chain::keysinterface::{KeysInterface, BaseSign};
20 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
21 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingSigner;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs};
33 use util::config::UserConfig;
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hash_types::{Txid, BlockHash};
37 use bitcoin::blockdata::block::{Block, BlockHeader};
38 use bitcoin::blockdata::script::Builder;
39 use bitcoin::blockdata::opcodes;
40 use bitcoin::blockdata::constants::genesis_block;
41 use bitcoin::network::constants::Network;
43 use bitcoin::hashes::sha256::Hash as Sha256;
44 use bitcoin::hashes::Hash;
46 use bitcoin::secp256k1::{Secp256k1, Message};
47 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
51 use std::collections::{BTreeSet, HashMap, HashSet};
52 use std::default::Default;
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57 use ln::msgs::OptionalField::Present;
60 fn test_insane_channel_opens() {
61 // Stand up a network of 2 nodes
62 let chanmon_cfgs = create_chanmon_cfgs(2);
63 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
64 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
65 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67 // Instantiate channel parameters where we push the maximum msats given our
69 let channel_value_sat = 31337; // same as funding satoshis
70 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
71 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73 // Have node0 initiate a channel to node1 with aforementioned parameters
74 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76 // Extract the channel open message from node0 to node1
77 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79 // Test helper that asserts we get the correct error string given a mutator
80 // that supposedly makes the channel open message insane
81 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
82 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
83 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
84 assert_eq!(msg_events.len(), 1);
85 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
86 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88 &ErrorAction::SendErrorMessage { .. } => {
89 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91 _ => panic!("unexpected event!"),
93 } else { assert!(false); }
96 use ln::channel::MAX_FUNDING_SATOSHIS;
97 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99 // Test all mutations that would make the channel open message insane
100 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 });
102 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104 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 });
106 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108 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 });
110 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 });
112 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 });
114 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 fn test_async_inbound_update_fee() {
121 let chanmon_cfgs = create_chanmon_cfgs(2);
122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
125 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
126 let logger = test_utils::TestLogger::new();
127 let channel_id = chan.2;
130 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
134 // send (1) commitment_signed -.
135 // <- update_add_htlc/commitment_signed
136 // send (2) RAA (awaiting remote revoke) -.
137 // (1) commitment_signed is delivered ->
138 // .- send (3) RAA (awaiting remote revoke)
139 // (2) RAA is delivered ->
140 // .- send (4) commitment_signed
141 // <- (3) RAA is delivered
142 // send (5) commitment_signed -.
143 // <- (4) commitment_signed is delivered
145 // (5) commitment_signed is delivered ->
147 // (6) RAA is delivered ->
149 // First nodes[0] generates an update_fee
150 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
151 check_added_monitors!(nodes[0], 1);
153 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
154 assert_eq!(events_0.len(), 1);
155 let (update_msg, commitment_signed) = match events_0[0] { // (1)
156 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
157 (update_fee.as_ref(), commitment_signed)
159 _ => panic!("Unexpected event"),
162 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
165 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
166 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
167 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(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
168 check_added_monitors!(nodes[1], 1);
170 let payment_event = {
171 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
172 assert_eq!(events_1.len(), 1);
173 SendEvent::from_event(events_1.remove(0))
175 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
176 assert_eq!(payment_event.msgs.len(), 1);
178 // ...now when the messages get delivered everyone should be happy
179 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
180 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
181 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
182 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
183 check_added_monitors!(nodes[0], 1);
185 // deliver(1), generate (3):
186 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
187 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
188 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
189 check_added_monitors!(nodes[1], 1);
191 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
192 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
193 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
194 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
195 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
196 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
197 assert!(bs_update.update_fee.is_none()); // (4)
198 check_added_monitors!(nodes[1], 1);
200 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
201 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
202 assert!(as_update.update_add_htlcs.is_empty()); // (5)
203 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
204 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
205 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
206 assert!(as_update.update_fee.is_none()); // (5)
207 check_added_monitors!(nodes[0], 1);
209 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
210 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
211 // only (6) so get_event_msg's assert(len == 1) passes
212 check_added_monitors!(nodes[0], 1);
214 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
215 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
216 check_added_monitors!(nodes[1], 1);
218 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
219 check_added_monitors!(nodes[0], 1);
221 let events_2 = nodes[0].node.get_and_clear_pending_events();
222 assert_eq!(events_2.len(), 1);
224 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
225 _ => panic!("Unexpected event"),
228 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
229 check_added_monitors!(nodes[1], 1);
233 fn test_update_fee_unordered_raa() {
234 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
235 // crash in an earlier version of the update_fee patch)
236 let chanmon_cfgs = create_chanmon_cfgs(2);
237 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
238 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
239 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
240 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
241 let channel_id = chan.2;
242 let logger = test_utils::TestLogger::new();
245 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247 // First nodes[0] generates an update_fee
248 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
249 check_added_monitors!(nodes[0], 1);
251 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
252 assert_eq!(events_0.len(), 1);
253 let update_msg = match events_0[0] { // (1)
254 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
257 _ => panic!("Unexpected event"),
260 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
263 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
264 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
265 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(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
266 check_added_monitors!(nodes[1], 1);
268 let payment_event = {
269 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
270 assert_eq!(events_1.len(), 1);
271 SendEvent::from_event(events_1.remove(0))
273 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
274 assert_eq!(payment_event.msgs.len(), 1);
276 // ...now when the messages get delivered everyone should be happy
277 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
278 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
279 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
280 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
281 check_added_monitors!(nodes[0], 1);
283 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
284 check_added_monitors!(nodes[1], 1);
286 // We can't continue, sadly, because our (1) now has a bogus signature
290 fn test_multi_flight_update_fee() {
291 let chanmon_cfgs = create_chanmon_cfgs(2);
292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
294 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
295 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
296 let channel_id = chan.2;
299 // update_fee/commitment_signed ->
300 // .- send (1) RAA and (2) commitment_signed
301 // update_fee (never committed) ->
303 // We have to manually generate the above update_fee, it is allowed by the protocol but we
304 // don't track which updates correspond to which revoke_and_ack responses so we're in
305 // AwaitingRAA mode and will not generate the update_fee yet.
306 // <- (1) RAA delivered
307 // (3) is generated and send (4) CS -.
308 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
309 // know the per_commitment_point to use for it.
310 // <- (2) commitment_signed delivered
312 // B should send no response here
313 // (4) commitment_signed delivered ->
314 // <- RAA/commitment_signed delivered
317 // First nodes[0] generates an update_fee
318 let initial_feerate = get_feerate!(nodes[0], channel_id);
319 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
320 check_added_monitors!(nodes[0], 1);
322 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
323 assert_eq!(events_0.len(), 1);
324 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
325 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
326 (update_fee.as_ref().unwrap(), commitment_signed)
328 _ => panic!("Unexpected event"),
331 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
332 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
333 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
334 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
335 check_added_monitors!(nodes[1], 1);
337 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
340 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
341 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343 // Create the (3) update_fee message that nodes[0] will generate before it does...
344 let mut update_msg_2 = msgs::UpdateFee {
345 channel_id: update_msg_1.channel_id.clone(),
346 feerate_per_kw: (initial_feerate + 30) as u32,
349 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355 // Deliver (1), generating (3) and (4)
356 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
357 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
358 check_added_monitors!(nodes[0], 1);
359 assert!(as_second_update.update_add_htlcs.is_empty());
360 assert!(as_second_update.update_fulfill_htlcs.is_empty());
361 assert!(as_second_update.update_fail_htlcs.is_empty());
362 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
363 // Check that the update_fee newly generated matches what we delivered:
364 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
365 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367 // Deliver (2) commitment_signed
368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
369 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370 check_added_monitors!(nodes[0], 1);
371 // No commitment_signed so get_event_msg's assert(len == 1) passes
373 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
374 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
375 check_added_monitors!(nodes[1], 1);
378 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
379 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
380 check_added_monitors!(nodes[1], 1);
382 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
383 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
384 check_added_monitors!(nodes[0], 1);
386 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
387 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
388 // No commitment_signed so get_event_msg's assert(len == 1) passes
389 check_added_monitors!(nodes[0], 1);
391 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
392 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
393 check_added_monitors!(nodes[1], 1);
396 fn do_test_1_conf_open(connect_style: ConnectStyle) {
397 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
398 // tests that we properly send one in that case.
399 let mut alice_config = UserConfig::default();
400 alice_config.own_channel_config.minimum_depth = 1;
401 alice_config.channel_options.announced_channel = true;
402 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
403 let mut bob_config = UserConfig::default();
404 bob_config.own_channel_config.minimum_depth = 1;
405 bob_config.channel_options.announced_channel = true;
406 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
407 let chanmon_cfgs = create_chanmon_cfgs(2);
408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
410 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
411 *nodes[0].connect_style.borrow_mut() = connect_style;
413 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
414 mine_transaction(&nodes[1], &tx);
415 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()));
417 mine_transaction(&nodes[0], &tx);
418 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
419 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
422 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
423 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
424 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
428 fn test_1_conf_open() {
429 do_test_1_conf_open(ConnectStyle::BestBlockFirst);
430 do_test_1_conf_open(ConnectStyle::TransactionsFirst);
431 do_test_1_conf_open(ConnectStyle::FullBlockViaListen);
434 fn do_test_sanity_on_in_flight_opens(steps: u8) {
435 // Previously, we had issues deserializing channels when we hadn't connected the first block
436 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
437 // serialization round-trips and simply do steps towards opening a channel and then drop the
440 let chanmon_cfgs = create_chanmon_cfgs(2);
441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
443 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
445 if steps & 0b1000_0000 != 0{
447 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
450 connect_block(&nodes[0], &block);
451 connect_block(&nodes[1], &block);
454 if steps & 0x0f == 0 { return; }
455 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
456 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
458 if steps & 0x0f == 1 { return; }
459 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
460 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
462 if steps & 0x0f == 2 { return; }
463 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
465 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
467 if steps & 0x0f == 3 { return; }
468 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
469 check_added_monitors!(nodes[0], 0);
470 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
472 if steps & 0x0f == 4 { return; }
473 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
475 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
476 assert_eq!(added_monitors.len(), 1);
477 assert_eq!(added_monitors[0].0, funding_output);
478 added_monitors.clear();
480 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
482 if steps & 0x0f == 5 { return; }
483 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
485 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
486 assert_eq!(added_monitors.len(), 1);
487 assert_eq!(added_monitors[0].0, funding_output);
488 added_monitors.clear();
491 let events_4 = nodes[0].node.get_and_clear_pending_events();
492 assert_eq!(events_4.len(), 0);
494 if steps & 0x0f == 6 { return; }
495 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
497 if steps & 0x0f == 7 { return; }
498 confirm_transaction_at(&nodes[0], &tx, 2);
499 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
500 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
504 fn test_sanity_on_in_flight_opens() {
505 do_test_sanity_on_in_flight_opens(0);
506 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
507 do_test_sanity_on_in_flight_opens(1);
508 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
509 do_test_sanity_on_in_flight_opens(2);
510 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
511 do_test_sanity_on_in_flight_opens(3);
512 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
513 do_test_sanity_on_in_flight_opens(4);
514 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
515 do_test_sanity_on_in_flight_opens(5);
516 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
517 do_test_sanity_on_in_flight_opens(6);
518 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
519 do_test_sanity_on_in_flight_opens(7);
520 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
521 do_test_sanity_on_in_flight_opens(8);
522 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
526 fn test_update_fee_vanilla() {
527 let chanmon_cfgs = create_chanmon_cfgs(2);
528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
531 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
532 let channel_id = chan.2;
534 let feerate = get_feerate!(nodes[0], channel_id);
535 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
536 check_added_monitors!(nodes[0], 1);
538 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
539 assert_eq!(events_0.len(), 1);
540 let (update_msg, commitment_signed) = match events_0[0] {
541 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 } } => {
542 (update_fee.as_ref(), commitment_signed)
544 _ => panic!("Unexpected event"),
546 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
548 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
549 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
550 check_added_monitors!(nodes[1], 1);
552 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
553 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
554 check_added_monitors!(nodes[0], 1);
556 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
557 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
558 // No commitment_signed so get_event_msg's assert(len == 1) passes
559 check_added_monitors!(nodes[0], 1);
561 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
562 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
563 check_added_monitors!(nodes[1], 1);
567 fn test_update_fee_that_funder_cannot_afford() {
568 let chanmon_cfgs = create_chanmon_cfgs(2);
569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
572 let channel_value = 1888;
573 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
574 let channel_id = chan.2;
577 nodes[0].node.update_fee(channel_id, feerate).unwrap();
578 check_added_monitors!(nodes[0], 1);
579 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
581 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
583 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
585 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
586 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
588 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
590 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
591 let num_htlcs = commitment_tx.output.len() - 2;
592 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
593 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
594 actual_fee = channel_value - actual_fee;
595 assert_eq!(total_fee, actual_fee);
598 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
599 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
600 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
601 check_added_monitors!(nodes[0], 1);
603 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
605 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
607 //While producing the commitment_signed response after handling a received update_fee request the
608 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
609 //Should produce and error.
610 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
611 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
612 check_added_monitors!(nodes[1], 1);
613 check_closed_broadcast!(nodes[1], true);
617 fn test_update_fee_with_fundee_update_add_htlc() {
618 let chanmon_cfgs = create_chanmon_cfgs(2);
619 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
620 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
621 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
622 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
623 let channel_id = chan.2;
624 let logger = test_utils::TestLogger::new();
627 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
629 let feerate = get_feerate!(nodes[0], channel_id);
630 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
631 check_added_monitors!(nodes[0], 1);
633 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
634 assert_eq!(events_0.len(), 1);
635 let (update_msg, commitment_signed) = match events_0[0] {
636 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 } } => {
637 (update_fee.as_ref(), commitment_signed)
639 _ => panic!("Unexpected event"),
641 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
642 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
643 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
644 check_added_monitors!(nodes[1], 1);
646 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
647 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
648 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(), None, None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
650 // nothing happens since node[1] is in AwaitingRemoteRevoke
651 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
653 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
654 assert_eq!(added_monitors.len(), 0);
655 added_monitors.clear();
657 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
658 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
659 // node[1] has nothing to do
661 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
662 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
663 check_added_monitors!(nodes[0], 1);
665 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
666 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
667 // No commitment_signed so get_event_msg's assert(len == 1) passes
668 check_added_monitors!(nodes[0], 1);
669 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
670 check_added_monitors!(nodes[1], 1);
671 // AwaitingRemoteRevoke ends here
673 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
674 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
675 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
676 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
677 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
678 assert_eq!(commitment_update.update_fee.is_none(), true);
680 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
681 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
682 check_added_monitors!(nodes[0], 1);
683 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
685 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
686 check_added_monitors!(nodes[1], 1);
687 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
689 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
690 check_added_monitors!(nodes[1], 1);
691 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
692 // No commitment_signed so get_event_msg's assert(len == 1) passes
694 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
695 check_added_monitors!(nodes[0], 1);
696 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
698 expect_pending_htlcs_forwardable!(nodes[0]);
700 let events = nodes[0].node.get_and_clear_pending_events();
701 assert_eq!(events.len(), 1);
703 Event::PaymentReceived { .. } => { },
704 _ => panic!("Unexpected event"),
707 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
709 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
710 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
711 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
715 fn test_update_fee() {
716 let chanmon_cfgs = create_chanmon_cfgs(2);
717 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
718 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
719 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
720 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
721 let channel_id = chan.2;
724 // (1) update_fee/commitment_signed ->
725 // <- (2) revoke_and_ack
726 // .- send (3) commitment_signed
727 // (4) update_fee/commitment_signed ->
728 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
729 // <- (3) commitment_signed delivered
730 // send (6) revoke_and_ack -.
731 // <- (5) deliver revoke_and_ack
732 // (6) deliver revoke_and_ack ->
733 // .- send (7) commitment_signed in response to (4)
734 // <- (7) deliver commitment_signed
737 // Create and deliver (1)...
738 let feerate = get_feerate!(nodes[0], channel_id);
739 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
740 check_added_monitors!(nodes[0], 1);
742 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
743 assert_eq!(events_0.len(), 1);
744 let (update_msg, commitment_signed) = match events_0[0] {
745 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 } } => {
746 (update_fee.as_ref(), commitment_signed)
748 _ => panic!("Unexpected event"),
750 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
752 // Generate (2) and (3):
753 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
754 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
755 check_added_monitors!(nodes[1], 1);
758 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
759 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
760 check_added_monitors!(nodes[0], 1);
762 // Create and deliver (4)...
763 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
764 check_added_monitors!(nodes[0], 1);
765 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
766 assert_eq!(events_0.len(), 1);
767 let (update_msg, commitment_signed) = match events_0[0] {
768 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 } } => {
769 (update_fee.as_ref(), commitment_signed)
771 _ => panic!("Unexpected event"),
774 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
776 check_added_monitors!(nodes[1], 1);
778 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
779 // No commitment_signed so get_event_msg's assert(len == 1) passes
781 // Handle (3), creating (6):
782 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
783 check_added_monitors!(nodes[0], 1);
784 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
785 // No commitment_signed so get_event_msg's assert(len == 1) passes
788 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
789 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
790 check_added_monitors!(nodes[0], 1);
792 // Deliver (6), creating (7):
793 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
794 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
795 assert!(commitment_update.update_add_htlcs.is_empty());
796 assert!(commitment_update.update_fulfill_htlcs.is_empty());
797 assert!(commitment_update.update_fail_htlcs.is_empty());
798 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
799 assert!(commitment_update.update_fee.is_none());
800 check_added_monitors!(nodes[1], 1);
803 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
804 check_added_monitors!(nodes[0], 1);
805 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
806 // No commitment_signed so get_event_msg's assert(len == 1) passes
808 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
809 check_added_monitors!(nodes[1], 1);
810 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
812 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
813 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
814 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
818 fn pre_funding_lock_shutdown_test() {
819 // Test sending a shutdown prior to funding_locked after funding generation
820 let chanmon_cfgs = create_chanmon_cfgs(2);
821 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
822 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
823 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
824 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
825 mine_transaction(&nodes[0], &tx);
826 mine_transaction(&nodes[1], &tx);
828 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
829 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
831 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
832 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
834 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
835 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
836 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
837 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
838 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
839 assert!(node_0_none.is_none());
841 assert!(nodes[0].node.list_channels().is_empty());
842 assert!(nodes[1].node.list_channels().is_empty());
846 fn updates_shutdown_wait() {
847 // Test sending a shutdown with outstanding updates pending
848 let chanmon_cfgs = create_chanmon_cfgs(3);
849 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
850 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
851 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
852 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
853 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
854 let logger = test_utils::TestLogger::new();
856 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
858 nodes[0].node.close_channel(&chan_1.2).unwrap();
859 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
860 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
861 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
862 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
864 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
865 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
867 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
869 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
870 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
871 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
872 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
873 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
874 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
876 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
877 check_added_monitors!(nodes[2], 1);
878 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
879 assert!(updates.update_add_htlcs.is_empty());
880 assert!(updates.update_fail_htlcs.is_empty());
881 assert!(updates.update_fail_malformed_htlcs.is_empty());
882 assert!(updates.update_fee.is_none());
883 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
884 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
885 check_added_monitors!(nodes[1], 1);
886 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
889 assert!(updates_2.update_add_htlcs.is_empty());
890 assert!(updates_2.update_fail_htlcs.is_empty());
891 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
892 assert!(updates_2.update_fee.is_none());
893 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
894 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
895 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
897 let events = nodes[0].node.get_and_clear_pending_events();
898 assert_eq!(events.len(), 1);
900 Event::PaymentSent { ref payment_preimage } => {
901 assert_eq!(our_payment_preimage, *payment_preimage);
903 _ => panic!("Unexpected event"),
906 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
907 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
908 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
909 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
910 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
911 assert!(node_0_none.is_none());
913 assert!(nodes[0].node.list_channels().is_empty());
915 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
916 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
917 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
918 assert!(nodes[1].node.list_channels().is_empty());
919 assert!(nodes[2].node.list_channels().is_empty());
923 fn htlc_fail_async_shutdown() {
924 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
925 let chanmon_cfgs = create_chanmon_cfgs(3);
926 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
927 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
928 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
929 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
930 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
931 let logger = test_utils::TestLogger::new();
933 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
934 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
935 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
936 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
937 check_added_monitors!(nodes[0], 1);
938 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
939 assert_eq!(updates.update_add_htlcs.len(), 1);
940 assert!(updates.update_fulfill_htlcs.is_empty());
941 assert!(updates.update_fail_htlcs.is_empty());
942 assert!(updates.update_fail_malformed_htlcs.is_empty());
943 assert!(updates.update_fee.is_none());
945 nodes[1].node.close_channel(&chan_1.2).unwrap();
946 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
947 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
948 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
951 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
952 check_added_monitors!(nodes[1], 1);
953 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
954 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
956 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
957 assert!(updates_2.update_add_htlcs.is_empty());
958 assert!(updates_2.update_fulfill_htlcs.is_empty());
959 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
960 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
961 assert!(updates_2.update_fee.is_none());
963 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
964 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
966 expect_payment_failed!(nodes[0], our_payment_hash, false);
968 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
969 assert_eq!(msg_events.len(), 2);
970 let node_0_closing_signed = match msg_events[0] {
971 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
972 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
975 _ => panic!("Unexpected event"),
977 match msg_events[1] {
978 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
979 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
981 _ => panic!("Unexpected event"),
984 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
985 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
986 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
987 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
988 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
989 assert!(node_0_none.is_none());
991 assert!(nodes[0].node.list_channels().is_empty());
993 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
994 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
995 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
996 assert!(nodes[1].node.list_channels().is_empty());
997 assert!(nodes[2].node.list_channels().is_empty());
1000 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1001 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1002 // messages delivered prior to disconnect
1003 let chanmon_cfgs = create_chanmon_cfgs(3);
1004 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1005 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1006 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1007 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1008 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1010 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1012 nodes[1].node.close_channel(&chan_1.2).unwrap();
1013 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1015 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1016 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1018 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1022 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1023 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1025 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1026 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1027 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1030 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1031 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1032 assert!(node_1_shutdown == node_1_2nd_shutdown);
1034 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1035 let node_0_2nd_shutdown = if recv_count > 0 {
1036 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1037 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1041 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1042 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1044 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1046 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1047 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1049 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1050 check_added_monitors!(nodes[2], 1);
1051 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1052 assert!(updates.update_add_htlcs.is_empty());
1053 assert!(updates.update_fail_htlcs.is_empty());
1054 assert!(updates.update_fail_malformed_htlcs.is_empty());
1055 assert!(updates.update_fee.is_none());
1056 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1057 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1058 check_added_monitors!(nodes[1], 1);
1059 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1060 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1062 assert!(updates_2.update_add_htlcs.is_empty());
1063 assert!(updates_2.update_fail_htlcs.is_empty());
1064 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1065 assert!(updates_2.update_fee.is_none());
1066 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1067 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1068 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1070 let events = nodes[0].node.get_and_clear_pending_events();
1071 assert_eq!(events.len(), 1);
1073 Event::PaymentSent { ref payment_preimage } => {
1074 assert_eq!(our_payment_preimage, *payment_preimage);
1076 _ => panic!("Unexpected event"),
1079 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1081 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1082 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1083 assert!(node_1_closing_signed.is_some());
1086 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1087 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1089 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1090 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1091 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092 if recv_count == 0 {
1093 // If all closing_signeds weren't delivered we can just resume where we left off...
1094 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1096 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1097 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1098 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1100 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1101 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1102 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1104 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1105 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1108 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1109 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1111 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1112 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1113 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1114 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1115 assert!(node_0_none.is_none());
1117 // If one node, however, received + responded with an identical closing_signed we end
1118 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1119 // There isn't really anything better we can do simply, but in the future we might
1120 // explore storing a set of recently-closed channels that got disconnected during
1121 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1122 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1124 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1126 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1127 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1128 assert_eq!(msg_events.len(), 1);
1129 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1131 &ErrorAction::SendErrorMessage { ref msg } => {
1132 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1133 assert_eq!(msg.channel_id, chan_1.2);
1135 _ => panic!("Unexpected event!"),
1137 } else { panic!("Needed SendErrorMessage close"); }
1139 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1140 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1141 // closing_signed so we do it ourselves
1142 check_closed_broadcast!(nodes[0], false);
1143 check_added_monitors!(nodes[0], 1);
1146 assert!(nodes[0].node.list_channels().is_empty());
1148 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1149 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1150 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1151 assert!(nodes[1].node.list_channels().is_empty());
1152 assert!(nodes[2].node.list_channels().is_empty());
1156 fn test_shutdown_rebroadcast() {
1157 do_test_shutdown_rebroadcast(0);
1158 do_test_shutdown_rebroadcast(1);
1159 do_test_shutdown_rebroadcast(2);
1163 fn fake_network_test() {
1164 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1165 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1166 let chanmon_cfgs = create_chanmon_cfgs(4);
1167 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1168 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1169 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1171 // Create some initial channels
1172 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1173 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1174 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1176 // Rebalance the network a bit by relaying one payment through all the channels...
1177 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1179 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1182 // Send some more payments
1183 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1184 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1185 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1187 // Test failure packets
1188 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1189 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1191 // Add a new channel that skips 3
1192 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1195 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1196 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202 // Do some rebalance loop payments, simultaneously
1203 let mut hops = Vec::with_capacity(3);
1204 hops.push(RouteHop {
1205 pubkey: nodes[2].node.get_our_node_id(),
1206 node_features: NodeFeatures::empty(),
1207 short_channel_id: chan_2.0.contents.short_channel_id,
1208 channel_features: ChannelFeatures::empty(),
1210 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1212 hops.push(RouteHop {
1213 pubkey: nodes[3].node.get_our_node_id(),
1214 node_features: NodeFeatures::empty(),
1215 short_channel_id: chan_3.0.contents.short_channel_id,
1216 channel_features: ChannelFeatures::empty(),
1218 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1220 hops.push(RouteHop {
1221 pubkey: nodes[1].node.get_our_node_id(),
1222 node_features: NodeFeatures::empty(),
1223 short_channel_id: chan_4.0.contents.short_channel_id,
1224 channel_features: ChannelFeatures::empty(),
1226 cltv_expiry_delta: TEST_FINAL_CLTV,
1228 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;
1229 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;
1230 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1232 let mut hops = Vec::with_capacity(3);
1233 hops.push(RouteHop {
1234 pubkey: nodes[3].node.get_our_node_id(),
1235 node_features: NodeFeatures::empty(),
1236 short_channel_id: chan_4.0.contents.short_channel_id,
1237 channel_features: ChannelFeatures::empty(),
1239 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1241 hops.push(RouteHop {
1242 pubkey: nodes[2].node.get_our_node_id(),
1243 node_features: NodeFeatures::empty(),
1244 short_channel_id: chan_3.0.contents.short_channel_id,
1245 channel_features: ChannelFeatures::empty(),
1247 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1249 hops.push(RouteHop {
1250 pubkey: nodes[1].node.get_our_node_id(),
1251 node_features: NodeFeatures::empty(),
1252 short_channel_id: chan_2.0.contents.short_channel_id,
1253 channel_features: ChannelFeatures::empty(),
1255 cltv_expiry_delta: TEST_FINAL_CLTV,
1257 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;
1258 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;
1259 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1261 // Claim the rebalances...
1262 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1263 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1265 // Add a duplicate new channel from 2 to 4
1266 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1268 // Send some payments across both channels
1269 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1270 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1271 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1274 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1275 let events = nodes[0].node.get_and_clear_pending_msg_events();
1276 assert_eq!(events.len(), 0);
1277 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);
1279 //TODO: Test that routes work again here as we've been notified that the channel is full
1281 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1282 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1283 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1285 // Close down the channels...
1286 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1287 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1288 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1289 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1290 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1294 fn holding_cell_htlc_counting() {
1295 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1296 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1297 // commitment dance rounds.
1298 let chanmon_cfgs = create_chanmon_cfgs(3);
1299 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1300 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1301 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1302 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1303 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1304 let logger = test_utils::TestLogger::new();
1306 let mut payments = Vec::new();
1307 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1308 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1309 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1310 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1311 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1312 payments.push((payment_preimage, payment_hash));
1314 check_added_monitors!(nodes[1], 1);
1316 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1317 assert_eq!(events.len(), 1);
1318 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1319 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1321 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1322 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1324 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1326 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1327 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1328 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1329 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1330 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1331 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1334 // This should also be true if we try to forward a payment.
1335 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1337 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1338 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1339 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1340 check_added_monitors!(nodes[0], 1);
1343 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1344 assert_eq!(events.len(), 1);
1345 let payment_event = SendEvent::from_event(events.pop().unwrap());
1346 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1348 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1349 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1350 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1351 // fails), the second will process the resulting failure and fail the HTLC backward.
1352 expect_pending_htlcs_forwardable!(nodes[1]);
1353 expect_pending_htlcs_forwardable!(nodes[1]);
1354 check_added_monitors!(nodes[1], 1);
1356 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1357 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1358 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1360 let events = nodes[0].node.get_and_clear_pending_msg_events();
1361 assert_eq!(events.len(), 1);
1363 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1364 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1366 _ => panic!("Unexpected event"),
1369 expect_payment_failed!(nodes[0], payment_hash_2, false);
1371 // Now forward all the pending HTLCs and claim them back
1372 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1373 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1374 check_added_monitors!(nodes[2], 1);
1376 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1377 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1378 check_added_monitors!(nodes[1], 1);
1379 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1381 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1382 check_added_monitors!(nodes[1], 1);
1383 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1385 for ref update in as_updates.update_add_htlcs.iter() {
1386 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1388 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1389 check_added_monitors!(nodes[2], 1);
1390 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1391 check_added_monitors!(nodes[2], 1);
1392 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1394 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1395 check_added_monitors!(nodes[1], 1);
1396 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1397 check_added_monitors!(nodes[1], 1);
1398 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1400 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1401 check_added_monitors!(nodes[2], 1);
1403 expect_pending_htlcs_forwardable!(nodes[2]);
1405 let events = nodes[2].node.get_and_clear_pending_events();
1406 assert_eq!(events.len(), payments.len());
1407 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1409 &Event::PaymentReceived { ref payment_hash, .. } => {
1410 assert_eq!(*payment_hash, *hash);
1412 _ => panic!("Unexpected event"),
1416 for (preimage, _) in payments.drain(..) {
1417 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1420 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1424 fn duplicate_htlc_test() {
1425 // Test that we accept duplicate payment_hash HTLCs across the network and that
1426 // claiming/failing them are all separate and don't affect each other
1427 let chanmon_cfgs = create_chanmon_cfgs(6);
1428 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1429 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1430 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1432 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1433 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1434 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1435 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1436 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1437 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1439 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1441 *nodes[0].network_payment_count.borrow_mut() -= 1;
1442 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1444 *nodes[0].network_payment_count.borrow_mut() -= 1;
1445 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1447 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1448 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1449 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1453 fn test_duplicate_htlc_different_direction_onchain() {
1454 // Test that ChannelMonitor doesn't generate 2 preimage txn
1455 // when we have 2 HTLCs with same preimage that go across a node
1456 // in opposite directions.
1457 let chanmon_cfgs = create_chanmon_cfgs(2);
1458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1460 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1462 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1463 let logger = test_utils::TestLogger::new();
1466 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1468 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1470 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1471 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(), None, None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1472 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1474 // Provide preimage to node 0 by claiming payment
1475 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1476 check_added_monitors!(nodes[0], 1);
1478 // Broadcast node 1 commitment txn
1479 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1481 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1482 let mut has_both_htlcs = 0; // check htlcs match ones committed
1483 for outp in remote_txn[0].output.iter() {
1484 if outp.value == 800_000 / 1000 {
1485 has_both_htlcs += 1;
1486 } else if outp.value == 900_000 / 1000 {
1487 has_both_htlcs += 1;
1490 assert_eq!(has_both_htlcs, 2);
1492 mine_transaction(&nodes[0], &remote_txn[0]);
1493 check_added_monitors!(nodes[0], 1);
1495 // Check we only broadcast 1 timeout tx
1496 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1497 let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1498 assert_eq!(claim_txn.len(), 5);
1499 check_spends!(claim_txn[2], chan_1.3);
1500 check_spends!(claim_txn[3], claim_txn[2]);
1501 assert_eq!(htlc_pair.0.input.len(), 1);
1502 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1503 check_spends!(htlc_pair.0, remote_txn[0]);
1504 assert_eq!(htlc_pair.1.input.len(), 1);
1505 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1506 check_spends!(htlc_pair.1, remote_txn[0]);
1508 let events = nodes[0].node.get_and_clear_pending_msg_events();
1509 assert_eq!(events.len(), 3);
1512 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1513 MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::SendErrorMessage { ref msg } } => {
1514 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1515 assert_eq!(msg.data, "Commitment or closing transaction was confirmed on chain.");
1517 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, .. } } => {
1518 assert!(update_add_htlcs.is_empty());
1519 assert!(update_fail_htlcs.is_empty());
1520 assert_eq!(update_fulfill_htlcs.len(), 1);
1521 assert!(update_fail_malformed_htlcs.is_empty());
1522 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1524 _ => panic!("Unexpected event"),
1530 fn test_basic_channel_reserve() {
1531 let chanmon_cfgs = create_chanmon_cfgs(2);
1532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1534 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1535 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1536 let logger = test_utils::TestLogger::new();
1538 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1539 let channel_reserve = chan_stat.channel_reserve_msat;
1541 // The 2* and +1 are for the fee spike reserve.
1542 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1543 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1544 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1545 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1546 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(), None, None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1547 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1549 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1551 &APIError::ChannelUnavailable{ref err} =>
1552 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1553 _ => panic!("Unexpected error variant"),
1556 _ => panic!("Unexpected error variant"),
1558 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1559 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);
1561 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1565 fn test_fee_spike_violation_fails_htlc() {
1566 let chanmon_cfgs = create_chanmon_cfgs(2);
1567 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1568 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1569 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1570 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1571 let logger = test_utils::TestLogger::new();
1573 macro_rules! get_route_and_payment_hash {
1574 ($recv_value: expr) => {{
1575 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1576 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1577 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1578 (route, payment_hash, payment_preimage)
1582 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1583 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1584 let secp_ctx = Secp256k1::new();
1585 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1587 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1589 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1590 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1591 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1592 let msg = msgs::UpdateAddHTLC {
1595 amount_msat: htlc_msat,
1596 payment_hash: payment_hash,
1597 cltv_expiry: htlc_cltv,
1598 onion_routing_packet: onion_packet,
1601 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1603 // Now manually create the commitment_signed message corresponding to the update_add
1604 // nodes[0] just sent. In the code for construction of this message, "local" refers
1605 // to the sender of the message, and "remote" refers to the receiver.
1607 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1609 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1611 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1612 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1613 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1614 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1615 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1616 let chan_signer = local_chan.get_signer();
1617 let pubkeys = chan_signer.pubkeys();
1618 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1619 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1620 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1622 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1623 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1624 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1625 let chan_signer = remote_chan.get_signer();
1626 let pubkeys = chan_signer.pubkeys();
1627 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1628 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1631 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1632 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1633 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1635 // Build the remote commitment transaction so we can sign it, and then later use the
1636 // signature for the commitment_signed message.
1637 let local_chan_balance = 1313;
1639 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1641 amount_msat: 3460001,
1642 cltv_expiry: htlc_cltv,
1644 transaction_output_index: Some(1),
1647 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1650 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1651 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1652 let local_chan_signer = local_chan.get_signer();
1653 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1657 commit_tx_keys.clone(),
1659 &mut vec![(accepted_htlc_info, ())],
1660 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1662 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1665 let commit_signed_msg = msgs::CommitmentSigned {
1668 htlc_signatures: res.1
1671 // Send the commitment_signed message to the nodes[1].
1672 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1673 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1675 // Send the RAA to nodes[1].
1676 let raa_msg = msgs::RevokeAndACK {
1678 per_commitment_secret: local_secret,
1679 next_per_commitment_point: next_local_point
1681 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1683 let events = nodes[1].node.get_and_clear_pending_msg_events();
1684 assert_eq!(events.len(), 1);
1685 // Make sure the HTLC failed in the way we expect.
1687 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1688 assert_eq!(update_fail_htlcs.len(), 1);
1689 update_fail_htlcs[0].clone()
1691 _ => panic!("Unexpected event"),
1693 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1695 check_added_monitors!(nodes[1], 2);
1699 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1700 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1701 // Set the fee rate for the channel very high, to the point where the fundee
1702 // sending any above-dust amount would result in a channel reserve violation.
1703 // In this test we check that we would be prevented from sending an HTLC in
1705 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1706 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1707 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1708 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1709 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1710 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1711 let logger = test_utils::TestLogger::new();
1713 macro_rules! get_route_and_payment_hash {
1714 ($recv_value: expr) => {{
1715 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1716 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1717 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1718 (route, payment_hash, payment_preimage)
1722 let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1723 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1724 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1725 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1726 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);
1730 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1731 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1732 // Set the fee rate for the channel very high, to the point where the funder
1733 // receiving 1 update_add_htlc would result in them closing the channel due
1734 // to channel reserve violation. This close could also happen if the fee went
1735 // up a more realistic amount, but many HTLCs were outstanding at the time of
1736 // the update_add_htlc.
1737 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1738 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1741 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1742 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1743 let logger = test_utils::TestLogger::new();
1745 macro_rules! get_route_and_payment_hash {
1746 ($recv_value: expr) => {{
1747 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1748 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1749 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1750 (route, payment_hash, payment_preimage)
1754 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1755 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1756 let secp_ctx = Secp256k1::new();
1757 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1758 let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1759 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1760 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1761 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1762 let msg = msgs::UpdateAddHTLC {
1765 amount_msat: htlc_msat + 1,
1766 payment_hash: payment_hash,
1767 cltv_expiry: htlc_cltv,
1768 onion_routing_packet: onion_packet,
1771 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1772 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1773 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);
1774 assert_eq!(nodes[0].node.list_channels().len(), 0);
1775 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1776 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1777 check_added_monitors!(nodes[0], 1);
1781 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1782 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1783 // calculating our commitment transaction fee (this was previously broken).
1784 let chanmon_cfgs = create_chanmon_cfgs(2);
1785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1787 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1789 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1790 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1791 // transaction fee with 0 HTLCs (183 sats)).
1792 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1794 let dust_amt = 546000; // Dust amount
1795 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1796 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1797 // commitment transaction fee.
1798 let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1802 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1803 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1804 // calculating our counterparty's commitment transaction fee (this was previously broken).
1805 let chanmon_cfgs = create_chanmon_cfgs(2);
1806 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1807 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1808 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1809 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1811 let payment_amt = 46000; // Dust amount
1812 // In the previous code, these first four payments would succeed.
1813 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1814 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1815 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1819 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1820 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1821 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1823 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1825 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1826 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1827 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1828 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1832 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1833 let chanmon_cfgs = create_chanmon_cfgs(3);
1834 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1835 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1836 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1837 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1838 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1839 let logger = test_utils::TestLogger::new();
1841 macro_rules! get_route_and_payment_hash {
1842 ($recv_value: expr) => {{
1843 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1844 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1845 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(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1846 (route, payment_hash, payment_preimage)
1851 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1852 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1853 let feerate = get_feerate!(nodes[0], chan.2);
1855 // Add a 2* and +1 for the fee spike reserve.
1856 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1857 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;
1858 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1860 // Add a pending HTLC.
1861 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1862 let payment_event_1 = {
1863 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1864 check_added_monitors!(nodes[0], 1);
1866 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1867 assert_eq!(events.len(), 1);
1868 SendEvent::from_event(events.remove(0))
1870 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1872 // Attempt to trigger a channel reserve violation --> payment failure.
1873 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1874 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;
1875 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1876 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1878 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1879 let secp_ctx = Secp256k1::new();
1880 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1881 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1882 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1883 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1884 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1885 let msg = msgs::UpdateAddHTLC {
1888 amount_msat: htlc_msat + 1,
1889 payment_hash: our_payment_hash_1,
1890 cltv_expiry: htlc_cltv,
1891 onion_routing_packet: onion_packet,
1894 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1895 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1896 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1897 assert_eq!(nodes[1].node.list_channels().len(), 1);
1898 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1899 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1900 check_added_monitors!(nodes[1], 1);
1904 fn test_inbound_outbound_capacity_is_not_zero() {
1905 let chanmon_cfgs = create_chanmon_cfgs(2);
1906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1908 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1909 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1910 let channels0 = node_chanmgrs[0].list_channels();
1911 let channels1 = node_chanmgrs[1].list_channels();
1912 assert_eq!(channels0.len(), 1);
1913 assert_eq!(channels1.len(), 1);
1915 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1916 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1918 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1919 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1922 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1923 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1927 fn test_channel_reserve_holding_cell_htlcs() {
1928 let chanmon_cfgs = create_chanmon_cfgs(3);
1929 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1930 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1931 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1932 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1933 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1934 let logger = test_utils::TestLogger::new();
1936 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1937 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1939 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1940 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1942 macro_rules! get_route_and_payment_hash {
1943 ($recv_value: expr) => {{
1944 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1945 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1946 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(), None, None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1947 (route, payment_hash, payment_preimage)
1951 macro_rules! expect_forward {
1953 let mut events = $node.node.get_and_clear_pending_msg_events();
1954 assert_eq!(events.len(), 1);
1955 check_added_monitors!($node, 1);
1956 let payment_event = SendEvent::from_event(events.remove(0));
1961 let feemsat = 239; // somehow we know?
1962 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1963 let feerate = get_feerate!(nodes[0], chan_1.2);
1965 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1967 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1969 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1970 route.paths[0].last_mut().unwrap().fee_msat += 1;
1971 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1972 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1973 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)));
1974 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1975 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);
1978 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1979 // nodes[0]'s wealth
1981 let amt_msat = recv_value_0 + total_fee_msat;
1982 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1983 // Also, ensure that each payment has enough to be over the dust limit to
1984 // ensure it'll be included in each commit tx fee calculation.
1985 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1986 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1987 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1990 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1992 let (stat01_, stat11_, stat12_, stat22_) = (
1993 get_channel_value_stat!(nodes[0], chan_1.2),
1994 get_channel_value_stat!(nodes[1], chan_1.2),
1995 get_channel_value_stat!(nodes[1], chan_2.2),
1996 get_channel_value_stat!(nodes[2], chan_2.2),
1999 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2000 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2001 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2002 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2003 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2006 // adding pending output.
2007 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2008 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2009 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2010 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2011 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2012 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2013 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2014 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2015 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2017 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2018 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2019 let amt_msat_1 = recv_value_1 + total_fee_msat;
2021 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2022 let payment_event_1 = {
2023 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2024 check_added_monitors!(nodes[0], 1);
2026 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2027 assert_eq!(events.len(), 1);
2028 SendEvent::from_event(events.remove(0))
2030 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2032 // channel reserve test with htlc pending output > 0
2033 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2035 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2036 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2037 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2038 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2041 // split the rest to test holding cell
2042 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2043 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2044 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2045 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2047 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2048 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);
2051 // now see if they go through on both sides
2052 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2053 // but this will stuck in the holding cell
2054 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2055 check_added_monitors!(nodes[0], 0);
2056 let events = nodes[0].node.get_and_clear_pending_events();
2057 assert_eq!(events.len(), 0);
2059 // test with outbound holding cell amount > 0
2061 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2062 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2063 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2064 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2065 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);
2068 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2069 // this will also stuck in the holding cell
2070 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2071 check_added_monitors!(nodes[0], 0);
2072 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2073 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2075 // flush the pending htlc
2076 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2077 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2078 check_added_monitors!(nodes[1], 1);
2080 // the pending htlc should be promoted to committed
2081 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2082 check_added_monitors!(nodes[0], 1);
2083 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2085 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2086 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2087 // No commitment_signed so get_event_msg's assert(len == 1) passes
2088 check_added_monitors!(nodes[0], 1);
2090 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2091 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2092 check_added_monitors!(nodes[1], 1);
2094 expect_pending_htlcs_forwardable!(nodes[1]);
2096 let ref payment_event_11 = expect_forward!(nodes[1]);
2097 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2098 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2100 expect_pending_htlcs_forwardable!(nodes[2]);
2101 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2103 // flush the htlcs in the holding cell
2104 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2105 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2106 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2107 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2108 expect_pending_htlcs_forwardable!(nodes[1]);
2110 let ref payment_event_3 = expect_forward!(nodes[1]);
2111 assert_eq!(payment_event_3.msgs.len(), 2);
2112 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2113 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2115 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2116 expect_pending_htlcs_forwardable!(nodes[2]);
2118 let events = nodes[2].node.get_and_clear_pending_events();
2119 assert_eq!(events.len(), 2);
2121 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2122 assert_eq!(our_payment_hash_21, *payment_hash);
2123 assert_eq!(*payment_secret, None);
2124 assert_eq!(recv_value_21, amt);
2126 _ => panic!("Unexpected event"),
2129 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2130 assert_eq!(our_payment_hash_22, *payment_hash);
2131 assert_eq!(None, *payment_secret);
2132 assert_eq!(recv_value_22, amt);
2134 _ => panic!("Unexpected event"),
2137 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2138 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2139 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2141 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2142 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2143 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2145 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2146 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);
2147 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2148 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2149 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2151 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2152 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2156 fn channel_reserve_in_flight_removes() {
2157 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2158 // can send to its counterparty, but due to update ordering, the other side may not yet have
2159 // considered those HTLCs fully removed.
2160 // This tests that we don't count HTLCs which will not be included in the next remote
2161 // commitment transaction towards the reserve value (as it implies no commitment transaction
2162 // will be generated which violates the remote reserve value).
2163 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2165 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2166 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2167 // you only consider the value of the first HTLC, it may not),
2168 // * start routing a third HTLC from A to B,
2169 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2170 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2171 // * deliver the first fulfill from B
2172 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2174 // * deliver A's response CS and RAA.
2175 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2176 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2177 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2178 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2179 let chanmon_cfgs = create_chanmon_cfgs(2);
2180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2182 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2183 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2184 let logger = test_utils::TestLogger::new();
2186 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2187 // Route the first two HTLCs.
2188 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2189 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2191 // Start routing the third HTLC (this is just used to get everyone in the right state).
2192 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2194 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2195 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2196 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2197 check_added_monitors!(nodes[0], 1);
2198 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2199 assert_eq!(events.len(), 1);
2200 SendEvent::from_event(events.remove(0))
2203 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2204 // initial fulfill/CS.
2205 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2206 check_added_monitors!(nodes[1], 1);
2207 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2209 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2210 // remove the second HTLC when we send the HTLC back from B to A.
2211 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2212 check_added_monitors!(nodes[1], 1);
2213 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2215 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2216 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2217 check_added_monitors!(nodes[0], 1);
2218 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2219 expect_payment_sent!(nodes[0], payment_preimage_1);
2221 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2222 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2223 check_added_monitors!(nodes[1], 1);
2224 // B is already AwaitingRAA, so cant generate a CS here
2225 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2227 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2228 check_added_monitors!(nodes[1], 1);
2229 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2231 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2232 check_added_monitors!(nodes[0], 1);
2233 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2235 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2236 check_added_monitors!(nodes[1], 1);
2237 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2239 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2240 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2241 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2242 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2243 // on-chain as necessary).
2244 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2245 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2246 check_added_monitors!(nodes[0], 1);
2247 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2248 expect_payment_sent!(nodes[0], payment_preimage_2);
2250 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2251 check_added_monitors!(nodes[1], 1);
2252 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2254 expect_pending_htlcs_forwardable!(nodes[1]);
2255 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2257 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2258 // resolve the second HTLC from A's point of view.
2259 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2260 check_added_monitors!(nodes[0], 1);
2261 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2263 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2264 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2265 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2267 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2268 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(), None, None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2269 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2270 check_added_monitors!(nodes[1], 1);
2271 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2272 assert_eq!(events.len(), 1);
2273 SendEvent::from_event(events.remove(0))
2276 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2277 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2278 check_added_monitors!(nodes[0], 1);
2279 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2281 // Now just resolve all the outstanding messages/HTLCs for completeness...
2283 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2284 check_added_monitors!(nodes[1], 1);
2285 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2287 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2288 check_added_monitors!(nodes[1], 1);
2290 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2291 check_added_monitors!(nodes[0], 1);
2292 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2294 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2295 check_added_monitors!(nodes[1], 1);
2296 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2298 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2299 check_added_monitors!(nodes[0], 1);
2301 expect_pending_htlcs_forwardable!(nodes[0]);
2302 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2304 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2305 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2309 fn channel_monitor_network_test() {
2310 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2311 // tests that ChannelMonitor is able to recover from various states.
2312 let chanmon_cfgs = create_chanmon_cfgs(5);
2313 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2314 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2315 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2317 // Create some initial channels
2318 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2319 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2320 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2321 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2323 // Make sure all nodes are at the same starting height
2324 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2325 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2326 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2327 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2328 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2330 // Rebalance the network a bit by relaying one payment through all the channels...
2331 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2332 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336 // Simple case with no pending HTLCs:
2337 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2338 check_added_monitors!(nodes[1], 1);
2339 check_closed_broadcast!(nodes[1], false);
2341 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2342 assert_eq!(node_txn.len(), 1);
2343 mine_transaction(&nodes[0], &node_txn[0]);
2344 check_added_monitors!(nodes[0], 1);
2345 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2347 check_closed_broadcast!(nodes[0], true);
2348 assert_eq!(nodes[0].node.list_channels().len(), 0);
2349 assert_eq!(nodes[1].node.list_channels().len(), 1);
2351 // One pending HTLC is discarded by the force-close:
2352 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2354 // Simple case of one pending HTLC to HTLC-Timeout
2355 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2356 check_closed_broadcast!(nodes[1], false);
2357 check_added_monitors!(nodes[1], 1);
2359 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2360 mine_transaction(&nodes[2], &node_txn[0]);
2361 check_added_monitors!(nodes[2], 1);
2362 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2364 check_closed_broadcast!(nodes[2], true);
2365 assert_eq!(nodes[1].node.list_channels().len(), 0);
2366 assert_eq!(nodes[2].node.list_channels().len(), 1);
2368 macro_rules! claim_funds {
2369 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2371 assert!($node.node.claim_funds($preimage, &None, $amount));
2372 check_added_monitors!($node, 1);
2374 let events = $node.node.get_and_clear_pending_msg_events();
2375 assert_eq!(events.len(), 1);
2377 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2378 assert!(update_add_htlcs.is_empty());
2379 assert!(update_fail_htlcs.is_empty());
2380 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2382 _ => panic!("Unexpected event"),
2388 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2389 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2390 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2391 check_added_monitors!(nodes[2], 1);
2392 check_closed_broadcast!(nodes[2], false);
2393 let node2_commitment_txid;
2395 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2396 node2_commitment_txid = node_txn[0].txid();
2398 // Claim the payment on nodes[3], giving it knowledge of the preimage
2399 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2400 mine_transaction(&nodes[3], &node_txn[0]);
2401 check_added_monitors!(nodes[3], 1);
2402 check_preimage_claim(&nodes[3], &node_txn);
2404 check_closed_broadcast!(nodes[3], true);
2405 assert_eq!(nodes[2].node.list_channels().len(), 0);
2406 assert_eq!(nodes[3].node.list_channels().len(), 1);
2408 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2409 // confusing us in the following tests.
2410 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2412 // One pending HTLC to time out:
2413 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2414 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2417 let (close_chan_update_1, close_chan_update_2) = {
2418 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2419 let events = nodes[3].node.get_and_clear_pending_msg_events();
2420 assert_eq!(events.len(), 2);
2421 let close_chan_update_1 = match events[0] {
2422 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2425 _ => panic!("Unexpected event"),
2428 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2429 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2431 _ => panic!("Unexpected event"),
2433 check_added_monitors!(nodes[3], 1);
2435 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2437 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2438 node_txn.retain(|tx| {
2439 if tx.input[0].previous_output.txid == node2_commitment_txid {
2445 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2447 // Claim the payment on nodes[4], giving it knowledge of the preimage
2448 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2450 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2451 let events = nodes[4].node.get_and_clear_pending_msg_events();
2452 assert_eq!(events.len(), 2);
2453 let close_chan_update_2 = match events[0] {
2454 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2457 _ => panic!("Unexpected event"),
2460 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id } => {
2461 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2463 _ => panic!("Unexpected event"),
2465 check_added_monitors!(nodes[4], 1);
2466 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2468 mine_transaction(&nodes[4], &node_txn[0]);
2469 check_preimage_claim(&nodes[4], &node_txn);
2470 (close_chan_update_1, close_chan_update_2)
2472 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2473 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2474 assert_eq!(nodes[3].node.list_channels().len(), 0);
2475 assert_eq!(nodes[4].node.list_channels().len(), 0);
2477 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2481 fn test_justice_tx() {
2482 // Test justice txn built on revoked HTLC-Success tx, against both sides
2483 let mut alice_config = UserConfig::default();
2484 alice_config.channel_options.announced_channel = true;
2485 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2486 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2487 let mut bob_config = UserConfig::default();
2488 bob_config.channel_options.announced_channel = true;
2489 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2490 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2491 let user_cfgs = [Some(alice_config), Some(bob_config)];
2492 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2493 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2494 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2495 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2496 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2497 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2498 // Create some new channels:
2499 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2501 // A pending HTLC which will be revoked:
2502 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2503 // Get the will-be-revoked local txn from nodes[0]
2504 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2505 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2506 assert_eq!(revoked_local_txn[0].input.len(), 1);
2507 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2508 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2509 assert_eq!(revoked_local_txn[1].input.len(), 1);
2510 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2511 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2512 // Revoke the old state
2513 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2516 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2518 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2519 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2520 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2522 check_spends!(node_txn[0], revoked_local_txn[0]);
2523 node_txn.swap_remove(0);
2524 node_txn.truncate(1);
2526 check_added_monitors!(nodes[1], 1);
2527 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2529 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2530 // Verify broadcast of revoked HTLC-timeout
2531 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2532 check_added_monitors!(nodes[0], 1);
2533 // Broadcast revoked HTLC-timeout on node 1
2534 mine_transaction(&nodes[1], &node_txn[1]);
2535 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2537 get_announce_close_broadcast_events(&nodes, 0, 1);
2539 assert_eq!(nodes[0].node.list_channels().len(), 0);
2540 assert_eq!(nodes[1].node.list_channels().len(), 0);
2542 // We test justice_tx build by A on B's revoked HTLC-Success tx
2543 // Create some new channels:
2544 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2546 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2550 // A pending HTLC which will be revoked:
2551 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2552 // Get the will-be-revoked local txn from B
2553 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2554 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2555 assert_eq!(revoked_local_txn[0].input.len(), 1);
2556 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2557 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2558 // Revoke the old state
2559 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2561 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2563 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2565 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2567 check_spends!(node_txn[0], revoked_local_txn[0]);
2568 node_txn.swap_remove(0);
2570 check_added_monitors!(nodes[0], 1);
2571 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2573 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2574 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2575 check_added_monitors!(nodes[1], 1);
2576 mine_transaction(&nodes[0], &node_txn[1]);
2577 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2579 get_announce_close_broadcast_events(&nodes, 0, 1);
2580 assert_eq!(nodes[0].node.list_channels().len(), 0);
2581 assert_eq!(nodes[1].node.list_channels().len(), 0);
2585 fn revoked_output_claim() {
2586 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2587 // transaction is broadcast by its counterparty
2588 let chanmon_cfgs = create_chanmon_cfgs(2);
2589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2592 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2593 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2594 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2595 assert_eq!(revoked_local_txn.len(), 1);
2596 // Only output is the full channel value back to nodes[0]:
2597 assert_eq!(revoked_local_txn[0].output.len(), 1);
2598 // Send a payment through, updating everyone's latest commitment txn
2599 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2601 // Inform nodes[1] that nodes[0] broadcast a stale tx
2602 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2603 check_added_monitors!(nodes[1], 1);
2604 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2605 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2607 check_spends!(node_txn[0], revoked_local_txn[0]);
2608 check_spends!(node_txn[1], chan_1.3);
2610 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2611 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2612 get_announce_close_broadcast_events(&nodes, 0, 1);
2613 check_added_monitors!(nodes[0], 1)
2617 fn claim_htlc_outputs_shared_tx() {
2618 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2619 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2620 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2623 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2625 // Create some new channel:
2626 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2628 // Rebalance the network to generate htlc in the two directions
2629 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2630 // 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
2631 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2632 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2634 // Get the will-be-revoked local txn from node[0]
2635 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2636 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2637 assert_eq!(revoked_local_txn[0].input.len(), 1);
2638 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2639 assert_eq!(revoked_local_txn[1].input.len(), 1);
2640 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2641 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2642 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2644 //Revoke the old state
2645 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2648 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2649 check_added_monitors!(nodes[0], 1);
2650 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2651 check_added_monitors!(nodes[1], 1);
2652 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2653 expect_payment_failed!(nodes[1], payment_hash_2, true);
2655 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2656 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2658 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2659 check_spends!(node_txn[0], revoked_local_txn[0]);
2661 let mut witness_lens = BTreeSet::new();
2662 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2663 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2664 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2665 assert_eq!(witness_lens.len(), 3);
2666 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2667 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2668 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2670 // Next nodes[1] broadcasts its current local tx state:
2671 assert_eq!(node_txn[1].input.len(), 1);
2672 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2674 assert_eq!(node_txn[2].input.len(), 1);
2675 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2676 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2677 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2678 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2679 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2681 get_announce_close_broadcast_events(&nodes, 0, 1);
2682 assert_eq!(nodes[0].node.list_channels().len(), 0);
2683 assert_eq!(nodes[1].node.list_channels().len(), 0);
2687 fn claim_htlc_outputs_single_tx() {
2688 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2689 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2690 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2693 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2695 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2697 // Rebalance the network to generate htlc in the two directions
2698 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2699 // 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
2700 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2701 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2702 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2704 // Get the will-be-revoked local txn from node[0]
2705 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2707 //Revoke the old state
2708 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2711 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2712 check_added_monitors!(nodes[0], 1);
2713 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2714 check_added_monitors!(nodes[1], 1);
2715 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2717 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2718 expect_payment_failed!(nodes[1], payment_hash_2, true);
2720 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2721 assert_eq!(node_txn.len(), 9);
2722 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2723 // ChannelManager: local commmitment + local HTLC-timeout (2)
2724 // 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)
2725 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2727 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2728 assert_eq!(node_txn[0].input.len(), 1);
2729 check_spends!(node_txn[0], chan_1.3);
2730 assert_eq!(node_txn[1].input.len(), 1);
2731 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2732 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2733 check_spends!(node_txn[1], node_txn[0]);
2735 // Justice transactions are indices 1-2-4
2736 assert_eq!(node_txn[2].input.len(), 1);
2737 assert_eq!(node_txn[3].input.len(), 1);
2738 assert_eq!(node_txn[4].input.len(), 1);
2740 check_spends!(node_txn[2], revoked_local_txn[0]);
2741 check_spends!(node_txn[3], revoked_local_txn[0]);
2742 check_spends!(node_txn[4], revoked_local_txn[0]);
2744 let mut witness_lens = BTreeSet::new();
2745 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2746 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2747 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2748 assert_eq!(witness_lens.len(), 3);
2749 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2750 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2751 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2753 get_announce_close_broadcast_events(&nodes, 0, 1);
2754 assert_eq!(nodes[0].node.list_channels().len(), 0);
2755 assert_eq!(nodes[1].node.list_channels().len(), 0);
2759 fn test_htlc_on_chain_success() {
2760 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2761 // the preimage backward accordingly. So here we test that ChannelManager is
2762 // broadcasting the right event to other nodes in payment path.
2763 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2764 // A --------------------> B ----------------------> C (preimage)
2765 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2766 // commitment transaction was broadcast.
2767 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2769 // B should be able to claim via preimage if A then broadcasts its local tx.
2770 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2771 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2772 // PaymentSent event).
2774 let chanmon_cfgs = create_chanmon_cfgs(3);
2775 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2776 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2777 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2779 // Create some initial channels
2780 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2781 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2783 // Rebalance the network a bit by relaying one payment through all the channels...
2784 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2785 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2787 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2788 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2790 // Broadcast legit commitment tx from C on B's chain
2791 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2792 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2793 assert_eq!(commitment_tx.len(), 1);
2794 check_spends!(commitment_tx[0], chan_2.3);
2795 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2796 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2797 check_added_monitors!(nodes[2], 2);
2798 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2799 assert!(updates.update_add_htlcs.is_empty());
2800 assert!(updates.update_fail_htlcs.is_empty());
2801 assert!(updates.update_fail_malformed_htlcs.is_empty());
2802 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2804 mine_transaction(&nodes[2], &commitment_tx[0]);
2805 check_closed_broadcast!(nodes[2], true);
2806 check_added_monitors!(nodes[2], 1);
2807 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)
2808 assert_eq!(node_txn.len(), 5);
2809 assert_eq!(node_txn[0], node_txn[3]);
2810 assert_eq!(node_txn[1], node_txn[4]);
2811 assert_eq!(node_txn[2], commitment_tx[0]);
2812 check_spends!(node_txn[0], commitment_tx[0]);
2813 check_spends!(node_txn[1], commitment_tx[0]);
2814 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2815 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2816 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2817 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2818 assert_eq!(node_txn[0].lock_time, 0);
2819 assert_eq!(node_txn[1].lock_time, 0);
2821 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2822 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2823 connect_block(&nodes[1], &Block { header, txdata: node_txn});
2825 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2826 assert_eq!(added_monitors.len(), 1);
2827 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2828 added_monitors.clear();
2830 let events = nodes[1].node.get_and_clear_pending_msg_events();
2832 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2833 assert_eq!(added_monitors.len(), 2);
2834 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2835 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2836 added_monitors.clear();
2838 assert_eq!(events.len(), 3);
2840 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2841 _ => panic!("Unexpected event"),
2844 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
2845 _ => panic!("Unexpected event"),
2849 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, .. } } => {
2850 assert!(update_add_htlcs.is_empty());
2851 assert!(update_fail_htlcs.is_empty());
2852 assert_eq!(update_fulfill_htlcs.len(), 1);
2853 assert!(update_fail_malformed_htlcs.is_empty());
2854 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2856 _ => panic!("Unexpected event"),
2858 macro_rules! check_tx_local_broadcast {
2859 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2860 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2861 assert_eq!(node_txn.len(), 5);
2862 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2863 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2864 check_spends!(node_txn[0], $commitment_tx);
2865 check_spends!(node_txn[1], $commitment_tx);
2866 assert_ne!(node_txn[0].lock_time, 0);
2867 assert_ne!(node_txn[1].lock_time, 0);
2869 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2870 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2871 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2872 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2874 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2875 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2876 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2877 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2879 check_spends!(node_txn[2], $chan_tx);
2880 check_spends!(node_txn[3], node_txn[2]);
2881 check_spends!(node_txn[4], node_txn[2]);
2882 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2883 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2886 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2887 assert_ne!(node_txn[3].lock_time, 0);
2888 assert_ne!(node_txn[4].lock_time, 0);
2892 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2893 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2894 // timeout-claim of the output that nodes[2] just claimed via success.
2895 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2897 // Broadcast legit commitment tx from A on B's chain
2898 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2899 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2900 check_spends!(commitment_tx[0], chan_1.3);
2901 mine_transaction(&nodes[1], &commitment_tx[0]);
2902 check_closed_broadcast!(nodes[1], true);
2903 check_added_monitors!(nodes[1], 1);
2904 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2905 assert_eq!(node_txn.len(), 4);
2906 check_spends!(node_txn[0], commitment_tx[0]);
2907 assert_eq!(node_txn[0].input.len(), 2);
2908 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2909 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2910 assert_eq!(node_txn[0].lock_time, 0);
2911 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2912 check_spends!(node_txn[1], chan_1.3);
2913 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2914 check_spends!(node_txn[2], node_txn[1]);
2915 check_spends!(node_txn[3], node_txn[1]);
2916 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2917 // we already checked the same situation with A.
2919 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2920 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2921 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] });
2922 check_closed_broadcast!(nodes[0], true);
2923 check_added_monitors!(nodes[0], 1);
2924 let events = nodes[0].node.get_and_clear_pending_events();
2925 assert_eq!(events.len(), 2);
2926 let mut first_claimed = false;
2927 for event in events {
2929 Event::PaymentSent { payment_preimage } => {
2930 if payment_preimage == our_payment_preimage {
2931 assert!(!first_claimed);
2932 first_claimed = true;
2934 assert_eq!(payment_preimage, our_payment_preimage_2);
2937 _ => panic!("Unexpected event"),
2940 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2943 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
2944 // Test that in case of a unilateral close onchain, we detect the state of output and
2945 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2946 // broadcasting the right event to other nodes in payment path.
2947 // A ------------------> B ----------------------> C (timeout)
2948 // B's commitment tx C's commitment tx
2950 // B's HTLC timeout tx B's timeout tx
2952 let chanmon_cfgs = create_chanmon_cfgs(3);
2953 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2954 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2955 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2956 *nodes[0].connect_style.borrow_mut() = connect_style;
2957 *nodes[1].connect_style.borrow_mut() = connect_style;
2958 *nodes[2].connect_style.borrow_mut() = connect_style;
2960 // Create some intial channels
2961 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2962 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2964 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2965 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2966 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2968 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2970 // Broadcast legit commitment tx from C on B's chain
2971 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2972 check_spends!(commitment_tx[0], chan_2.3);
2973 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2974 check_added_monitors!(nodes[2], 0);
2975 expect_pending_htlcs_forwardable!(nodes[2]);
2976 check_added_monitors!(nodes[2], 1);
2978 let events = nodes[2].node.get_and_clear_pending_msg_events();
2979 assert_eq!(events.len(), 1);
2981 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, .. } } => {
2982 assert!(update_add_htlcs.is_empty());
2983 assert!(!update_fail_htlcs.is_empty());
2984 assert!(update_fulfill_htlcs.is_empty());
2985 assert!(update_fail_malformed_htlcs.is_empty());
2986 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2988 _ => panic!("Unexpected event"),
2990 mine_transaction(&nodes[2], &commitment_tx[0]);
2991 check_closed_broadcast!(nodes[2], true);
2992 check_added_monitors!(nodes[2], 1);
2993 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2994 assert_eq!(node_txn.len(), 1);
2995 check_spends!(node_txn[0], chan_2.3);
2996 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2998 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2999 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3000 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3001 mine_transaction(&nodes[1], &commitment_tx[0]);
3004 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3005 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3006 assert_eq!(node_txn[0], node_txn[3]);
3007 assert_eq!(node_txn[1], node_txn[4]);
3009 check_spends!(node_txn[2], commitment_tx[0]);
3010 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3012 check_spends!(node_txn[0], chan_2.3);
3013 check_spends!(node_txn[1], node_txn[0]);
3014 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3015 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3017 timeout_tx = node_txn[2].clone();
3021 mine_transaction(&nodes[1], &timeout_tx);
3022 check_added_monitors!(nodes[1], 1);
3023 check_closed_broadcast!(nodes[1], true);
3025 // B will rebroadcast a fee-bumped timeout transaction here.
3026 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3027 assert_eq!(node_txn.len(), 1);
3028 check_spends!(node_txn[0], commitment_tx[0]);
3031 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3033 // B will rebroadcast its own holder commitment transaction here...just because
3034 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3035 assert_eq!(node_txn.len(), 1);
3036 check_spends!(node_txn[0], chan_2.3);
3039 expect_pending_htlcs_forwardable!(nodes[1]);
3040 check_added_monitors!(nodes[1], 1);
3041 let events = nodes[1].node.get_and_clear_pending_msg_events();
3042 assert_eq!(events.len(), 1);
3044 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, .. } } => {
3045 assert!(update_add_htlcs.is_empty());
3046 assert!(!update_fail_htlcs.is_empty());
3047 assert!(update_fulfill_htlcs.is_empty());
3048 assert!(update_fail_malformed_htlcs.is_empty());
3049 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3051 _ => panic!("Unexpected event"),
3054 // Broadcast legit commitment tx from B on A's chain
3055 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3056 check_spends!(commitment_tx[0], chan_1.3);
3058 mine_transaction(&nodes[0], &commitment_tx[0]);
3060 check_closed_broadcast!(nodes[0], true);
3061 check_added_monitors!(nodes[0], 1);
3062 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3063 assert_eq!(node_txn.len(), 3);
3064 check_spends!(node_txn[0], commitment_tx[0]);
3065 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3066 check_spends!(node_txn[1], chan_1.3);
3067 check_spends!(node_txn[2], node_txn[1]);
3068 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3069 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3073 fn test_htlc_on_chain_timeout() {
3074 do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3075 do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3076 do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3080 fn test_simple_commitment_revoked_fail_backward() {
3081 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3082 // and fail backward accordingly.
3084 let chanmon_cfgs = create_chanmon_cfgs(3);
3085 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3086 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3087 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3089 // Create some initial channels
3090 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3091 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3093 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3094 // Get the will-be-revoked local txn from nodes[2]
3095 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3096 // Revoke the old state
3097 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3099 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3101 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3102 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3103 check_added_monitors!(nodes[1], 1);
3104 check_closed_broadcast!(nodes[1], true);
3106 expect_pending_htlcs_forwardable!(nodes[1]);
3107 check_added_monitors!(nodes[1], 1);
3108 let events = nodes[1].node.get_and_clear_pending_msg_events();
3109 assert_eq!(events.len(), 1);
3111 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, .. } } => {
3112 assert!(update_add_htlcs.is_empty());
3113 assert_eq!(update_fail_htlcs.len(), 1);
3114 assert!(update_fulfill_htlcs.is_empty());
3115 assert!(update_fail_malformed_htlcs.is_empty());
3116 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3118 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3119 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3121 let events = nodes[0].node.get_and_clear_pending_msg_events();
3122 assert_eq!(events.len(), 1);
3124 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3125 _ => panic!("Unexpected event"),
3127 expect_payment_failed!(nodes[0], payment_hash, false);
3129 _ => panic!("Unexpected event"),
3133 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3134 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3135 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3136 // commitment transaction anymore.
3137 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3138 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3139 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3140 // technically disallowed and we should probably handle it reasonably.
3141 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3142 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3144 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3145 // commitment_signed (implying it will be in the latest remote commitment transaction).
3146 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3147 // and once they revoke the previous commitment transaction (allowing us to send a new
3148 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3149 let chanmon_cfgs = create_chanmon_cfgs(3);
3150 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3151 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3152 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3154 // Create some initial channels
3155 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3156 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3158 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3159 // Get the will-be-revoked local txn from nodes[2]
3160 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3161 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3162 // Revoke the old state
3163 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3165 let value = if use_dust {
3166 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3167 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3168 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3171 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3172 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3173 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3175 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3176 expect_pending_htlcs_forwardable!(nodes[2]);
3177 check_added_monitors!(nodes[2], 1);
3178 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3179 assert!(updates.update_add_htlcs.is_empty());
3180 assert!(updates.update_fulfill_htlcs.is_empty());
3181 assert!(updates.update_fail_malformed_htlcs.is_empty());
3182 assert_eq!(updates.update_fail_htlcs.len(), 1);
3183 assert!(updates.update_fee.is_none());
3184 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3185 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3186 // Drop the last RAA from 3 -> 2
3188 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3189 expect_pending_htlcs_forwardable!(nodes[2]);
3190 check_added_monitors!(nodes[2], 1);
3191 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3192 assert!(updates.update_add_htlcs.is_empty());
3193 assert!(updates.update_fulfill_htlcs.is_empty());
3194 assert!(updates.update_fail_malformed_htlcs.is_empty());
3195 assert_eq!(updates.update_fail_htlcs.len(), 1);
3196 assert!(updates.update_fee.is_none());
3197 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3198 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3199 check_added_monitors!(nodes[1], 1);
3200 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3201 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3202 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3203 check_added_monitors!(nodes[2], 1);
3205 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3206 expect_pending_htlcs_forwardable!(nodes[2]);
3207 check_added_monitors!(nodes[2], 1);
3208 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3209 assert!(updates.update_add_htlcs.is_empty());
3210 assert!(updates.update_fulfill_htlcs.is_empty());
3211 assert!(updates.update_fail_malformed_htlcs.is_empty());
3212 assert_eq!(updates.update_fail_htlcs.len(), 1);
3213 assert!(updates.update_fee.is_none());
3214 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3215 // At this point first_payment_hash has dropped out of the latest two commitment
3216 // transactions that nodes[1] is tracking...
3217 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3218 check_added_monitors!(nodes[1], 1);
3219 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3220 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3221 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3222 check_added_monitors!(nodes[2], 1);
3224 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3225 // on nodes[2]'s RAA.
3226 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3227 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3228 let logger = test_utils::TestLogger::new();
3229 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(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3230 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3231 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3232 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3233 check_added_monitors!(nodes[1], 0);
3236 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3237 // One monitor for the new revocation preimage, no second on as we won't generate a new
3238 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3239 check_added_monitors!(nodes[1], 1);
3240 let events = nodes[1].node.get_and_clear_pending_events();
3241 assert_eq!(events.len(), 1);
3243 Event::PendingHTLCsForwardable { .. } => { },
3244 _ => panic!("Unexpected event"),
3246 // Deliberately don't process the pending fail-back so they all fail back at once after
3247 // block connection just like the !deliver_bs_raa case
3250 let mut failed_htlcs = HashSet::new();
3251 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3253 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3254 check_added_monitors!(nodes[1], 1);
3255 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3257 let events = nodes[1].node.get_and_clear_pending_events();
3258 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3260 Event::PaymentFailed { ref payment_hash, .. } => {
3261 assert_eq!(*payment_hash, fourth_payment_hash);
3263 _ => panic!("Unexpected event"),
3265 if !deliver_bs_raa {
3267 Event::PendingHTLCsForwardable { .. } => { },
3268 _ => panic!("Unexpected event"),
3271 nodes[1].node.process_pending_htlc_forwards();
3272 check_added_monitors!(nodes[1], 1);
3274 let events = nodes[1].node.get_and_clear_pending_msg_events();
3275 assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3276 match events[if deliver_bs_raa { 1 } else { 0 }] {
3277 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3278 _ => panic!("Unexpected event"),
3280 match events[if deliver_bs_raa { 2 } else { 1 }] {
3281 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { msg: msgs::ErrorMessage { channel_id, ref data } }, node_id: _ } => {
3282 assert_eq!(channel_id, chan_2.2);
3283 assert_eq!(data.as_str(), "Commitment or closing transaction was confirmed on chain.");
3285 _ => panic!("Unexpected event"),
3289 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, .. } } => {
3290 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3291 assert_eq!(update_add_htlcs.len(), 1);
3292 assert!(update_fulfill_htlcs.is_empty());
3293 assert!(update_fail_htlcs.is_empty());
3294 assert!(update_fail_malformed_htlcs.is_empty());
3296 _ => panic!("Unexpected event"),
3299 match events[if deliver_bs_raa { 3 } else { 2 }] {
3300 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, .. } } => {
3301 assert!(update_add_htlcs.is_empty());
3302 assert_eq!(update_fail_htlcs.len(), 3);
3303 assert!(update_fulfill_htlcs.is_empty());
3304 assert!(update_fail_malformed_htlcs.is_empty());
3305 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3307 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3308 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3309 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3311 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3313 let events = nodes[0].node.get_and_clear_pending_msg_events();
3314 // If we delivered B's RAA we got an unknown preimage error, not something
3315 // that we should update our routing table for.
3316 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3317 for event in events {
3319 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3320 _ => panic!("Unexpected event"),
3323 let events = nodes[0].node.get_and_clear_pending_events();
3324 assert_eq!(events.len(), 3);
3326 Event::PaymentFailed { ref payment_hash, .. } => {
3327 assert!(failed_htlcs.insert(payment_hash.0));
3329 _ => panic!("Unexpected event"),
3332 Event::PaymentFailed { ref payment_hash, .. } => {
3333 assert!(failed_htlcs.insert(payment_hash.0));
3335 _ => panic!("Unexpected event"),
3338 Event::PaymentFailed { ref payment_hash, .. } => {
3339 assert!(failed_htlcs.insert(payment_hash.0));
3341 _ => panic!("Unexpected event"),
3344 _ => panic!("Unexpected event"),
3347 assert!(failed_htlcs.contains(&first_payment_hash.0));
3348 assert!(failed_htlcs.contains(&second_payment_hash.0));
3349 assert!(failed_htlcs.contains(&third_payment_hash.0));
3353 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3354 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3355 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3356 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3357 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3361 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3362 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3363 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3364 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3365 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3369 fn fail_backward_pending_htlc_upon_channel_failure() {
3370 let chanmon_cfgs = create_chanmon_cfgs(2);
3371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3374 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3375 let logger = test_utils::TestLogger::new();
3377 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3379 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3380 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3381 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(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3382 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3383 check_added_monitors!(nodes[0], 1);
3385 let payment_event = {
3386 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3387 assert_eq!(events.len(), 1);
3388 SendEvent::from_event(events.remove(0))
3390 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3391 assert_eq!(payment_event.msgs.len(), 1);
3394 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3395 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3397 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3398 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(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3399 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3400 check_added_monitors!(nodes[0], 0);
3402 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3405 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3407 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3409 let secp_ctx = Secp256k1::new();
3410 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3411 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3412 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3413 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(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3414 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3415 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3416 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3418 // Send a 0-msat update_add_htlc to fail the channel.
3419 let update_add_htlc = msgs::UpdateAddHTLC {
3425 onion_routing_packet,
3427 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3430 // Check that Alice fails backward the pending HTLC from the second payment.
3431 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3432 check_closed_broadcast!(nodes[0], true);
3433 check_added_monitors!(nodes[0], 1);
3437 fn test_htlc_ignore_latest_remote_commitment() {
3438 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3439 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3440 let chanmon_cfgs = create_chanmon_cfgs(2);
3441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3443 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3444 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3446 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3447 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3448 check_closed_broadcast!(nodes[0], true);
3449 check_added_monitors!(nodes[0], 1);
3451 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3452 assert_eq!(node_txn.len(), 2);
3454 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3455 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3456 check_closed_broadcast!(nodes[1], true);
3457 check_added_monitors!(nodes[1], 1);
3459 // Duplicate the connect_block call since this may happen due to other listeners
3460 // registering new transactions
3461 header.prev_blockhash = header.block_hash();
3462 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]});
3466 fn test_force_close_fail_back() {
3467 // Check which HTLCs are failed-backwards on channel force-closure
3468 let chanmon_cfgs = create_chanmon_cfgs(3);
3469 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3470 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3471 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3472 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3473 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3474 let logger = test_utils::TestLogger::new();
3476 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3478 let mut payment_event = {
3479 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3480 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(), None, None, &Vec::new(), 1000000, 42, &logger).unwrap();
3481 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3482 check_added_monitors!(nodes[0], 1);
3484 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3485 assert_eq!(events.len(), 1);
3486 SendEvent::from_event(events.remove(0))
3489 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3490 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3492 expect_pending_htlcs_forwardable!(nodes[1]);
3494 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3495 assert_eq!(events_2.len(), 1);
3496 payment_event = SendEvent::from_event(events_2.remove(0));
3497 assert_eq!(payment_event.msgs.len(), 1);
3499 check_added_monitors!(nodes[1], 1);
3500 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3501 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3502 check_added_monitors!(nodes[2], 1);
3503 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3505 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3506 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3507 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3509 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3510 check_closed_broadcast!(nodes[2], true);
3511 check_added_monitors!(nodes[2], 1);
3513 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3514 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3515 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3516 // back to nodes[1] upon timeout otherwise.
3517 assert_eq!(node_txn.len(), 1);
3521 mine_transaction(&nodes[1], &tx);
3523 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3524 check_closed_broadcast!(nodes[1], true);
3525 check_added_monitors!(nodes[1], 1);
3527 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3529 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3530 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3531 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3533 mine_transaction(&nodes[2], &tx);
3534 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3535 assert_eq!(node_txn.len(), 1);
3536 assert_eq!(node_txn[0].input.len(), 1);
3537 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3538 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3539 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3541 check_spends!(node_txn[0], tx);
3545 fn test_simple_peer_disconnect() {
3546 // Test that we can reconnect when there are no lost messages
3547 let chanmon_cfgs = create_chanmon_cfgs(3);
3548 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3549 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3550 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3551 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3552 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3554 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3555 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3556 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3558 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3559 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3560 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3561 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3563 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3564 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3565 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3567 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3568 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3569 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3570 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3572 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3573 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3575 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3576 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3578 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3580 let events = nodes[0].node.get_and_clear_pending_events();
3581 assert_eq!(events.len(), 2);
3583 Event::PaymentSent { payment_preimage } => {
3584 assert_eq!(payment_preimage, payment_preimage_3);
3586 _ => panic!("Unexpected event"),
3589 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3590 assert_eq!(payment_hash, payment_hash_5);
3591 assert!(rejected_by_dest);
3593 _ => panic!("Unexpected event"),
3597 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3598 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3601 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3602 // Test that we can reconnect when in-flight HTLC updates get dropped
3603 let chanmon_cfgs = create_chanmon_cfgs(2);
3604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3606 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3607 if messages_delivered == 0 {
3608 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3609 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3611 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3614 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3616 let logger = test_utils::TestLogger::new();
3617 let payment_event = {
3618 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3619 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3620 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3621 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3622 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3623 check_added_monitors!(nodes[0], 1);
3625 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3626 assert_eq!(events.len(), 1);
3627 SendEvent::from_event(events.remove(0))
3629 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3631 if messages_delivered < 2 {
3632 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3634 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3635 if messages_delivered >= 3 {
3636 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3637 check_added_monitors!(nodes[1], 1);
3638 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3640 if messages_delivered >= 4 {
3641 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3642 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3643 check_added_monitors!(nodes[0], 1);
3645 if messages_delivered >= 5 {
3646 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3647 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3648 // No commitment_signed so get_event_msg's assert(len == 1) passes
3649 check_added_monitors!(nodes[0], 1);
3651 if messages_delivered >= 6 {
3652 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3653 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3654 check_added_monitors!(nodes[1], 1);
3661 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3662 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3663 if messages_delivered < 3 {
3664 // Even if the funding_locked messages get exchanged, as long as nothing further was
3665 // received on either side, both sides will need to resend them.
3666 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3667 } else if messages_delivered == 3 {
3668 // nodes[0] still wants its RAA + commitment_signed
3669 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3670 } else if messages_delivered == 4 {
3671 // nodes[0] still wants its commitment_signed
3672 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3673 } else if messages_delivered == 5 {
3674 // nodes[1] still wants its final RAA
3675 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3676 } else if messages_delivered == 6 {
3677 // Everything was delivered...
3678 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3681 let events_1 = nodes[1].node.get_and_clear_pending_events();
3682 assert_eq!(events_1.len(), 1);
3684 Event::PendingHTLCsForwardable { .. } => { },
3685 _ => panic!("Unexpected event"),
3688 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3689 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3690 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3692 nodes[1].node.process_pending_htlc_forwards();
3694 let events_2 = nodes[1].node.get_and_clear_pending_events();
3695 assert_eq!(events_2.len(), 1);
3697 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3698 assert_eq!(payment_hash_1, *payment_hash);
3699 assert_eq!(*payment_secret, None);
3700 assert_eq!(amt, 1000000);
3702 _ => panic!("Unexpected event"),
3705 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3706 check_added_monitors!(nodes[1], 1);
3708 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3709 assert_eq!(events_3.len(), 1);
3710 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3711 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3712 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3713 assert!(updates.update_add_htlcs.is_empty());
3714 assert!(updates.update_fail_htlcs.is_empty());
3715 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3716 assert!(updates.update_fail_malformed_htlcs.is_empty());
3717 assert!(updates.update_fee.is_none());
3718 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3720 _ => panic!("Unexpected event"),
3723 if messages_delivered >= 1 {
3724 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3726 let events_4 = nodes[0].node.get_and_clear_pending_events();
3727 assert_eq!(events_4.len(), 1);
3729 Event::PaymentSent { ref payment_preimage } => {
3730 assert_eq!(payment_preimage_1, *payment_preimage);
3732 _ => panic!("Unexpected event"),
3735 if messages_delivered >= 2 {
3736 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3737 check_added_monitors!(nodes[0], 1);
3738 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3740 if messages_delivered >= 3 {
3741 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3742 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3743 check_added_monitors!(nodes[1], 1);
3745 if messages_delivered >= 4 {
3746 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3747 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3748 // No commitment_signed so get_event_msg's assert(len == 1) passes
3749 check_added_monitors!(nodes[1], 1);
3751 if messages_delivered >= 5 {
3752 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3753 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3754 check_added_monitors!(nodes[0], 1);
3761 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3762 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3763 if messages_delivered < 2 {
3764 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3765 //TODO: Deduplicate PaymentSent events, then enable this if:
3766 //if messages_delivered < 1 {
3767 let events_4 = nodes[0].node.get_and_clear_pending_events();
3768 assert_eq!(events_4.len(), 1);
3770 Event::PaymentSent { ref payment_preimage } => {
3771 assert_eq!(payment_preimage_1, *payment_preimage);
3773 _ => panic!("Unexpected event"),
3776 } else if messages_delivered == 2 {
3777 // nodes[0] still wants its RAA + commitment_signed
3778 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3779 } else if messages_delivered == 3 {
3780 // nodes[0] still wants its commitment_signed
3781 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3782 } else if messages_delivered == 4 {
3783 // nodes[1] still wants its final RAA
3784 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3785 } else if messages_delivered == 5 {
3786 // Everything was delivered...
3787 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3790 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3791 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3792 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3794 // Channel should still work fine...
3795 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3796 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3797 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3798 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3799 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3800 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3804 fn test_drop_messages_peer_disconnect_a() {
3805 do_test_drop_messages_peer_disconnect(0);
3806 do_test_drop_messages_peer_disconnect(1);
3807 do_test_drop_messages_peer_disconnect(2);
3808 do_test_drop_messages_peer_disconnect(3);
3812 fn test_drop_messages_peer_disconnect_b() {
3813 do_test_drop_messages_peer_disconnect(4);
3814 do_test_drop_messages_peer_disconnect(5);
3815 do_test_drop_messages_peer_disconnect(6);
3819 fn test_funding_peer_disconnect() {
3820 // Test that we can lock in our funding tx while disconnected
3821 let chanmon_cfgs = create_chanmon_cfgs(2);
3822 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3823 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3824 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3825 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3827 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3828 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3830 confirm_transaction(&nodes[0], &tx);
3831 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3832 assert_eq!(events_1.len(), 1);
3834 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3835 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3837 _ => panic!("Unexpected event"),
3840 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3842 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3843 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3845 confirm_transaction(&nodes[1], &tx);
3846 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3847 assert_eq!(events_2.len(), 2);
3848 let funding_locked = match events_2[0] {
3849 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3850 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3853 _ => panic!("Unexpected event"),
3855 let bs_announcement_sigs = match events_2[1] {
3856 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3857 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3860 _ => panic!("Unexpected event"),
3863 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3865 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3866 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3867 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3868 assert_eq!(events_3.len(), 2);
3869 let as_announcement_sigs = match events_3[0] {
3870 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3871 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3874 _ => panic!("Unexpected event"),
3876 let (as_announcement, as_update) = match events_3[1] {
3877 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3878 (msg.clone(), update_msg.clone())
3880 _ => panic!("Unexpected event"),
3883 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3884 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3885 assert_eq!(events_4.len(), 1);
3886 let (_, bs_update) = match events_4[0] {
3887 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3888 (msg.clone(), update_msg.clone())
3890 _ => panic!("Unexpected event"),
3893 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3894 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3895 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3897 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3898 let logger = test_utils::TestLogger::new();
3899 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(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3900 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3901 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3905 fn test_drop_messages_peer_disconnect_dual_htlc() {
3906 // Test that we can handle reconnecting when both sides of a channel have pending
3907 // commitment_updates when we disconnect.
3908 let chanmon_cfgs = create_chanmon_cfgs(2);
3909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3911 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3912 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3913 let logger = test_utils::TestLogger::new();
3915 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3917 // Now try to send a second payment which will fail to send
3918 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3919 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3920 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(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3921 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3922 check_added_monitors!(nodes[0], 1);
3924 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3925 assert_eq!(events_1.len(), 1);
3927 MessageSendEvent::UpdateHTLCs { .. } => {},
3928 _ => panic!("Unexpected event"),
3931 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3932 check_added_monitors!(nodes[1], 1);
3934 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3935 assert_eq!(events_2.len(), 1);
3937 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 } } => {
3938 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3939 assert!(update_add_htlcs.is_empty());
3940 assert_eq!(update_fulfill_htlcs.len(), 1);
3941 assert!(update_fail_htlcs.is_empty());
3942 assert!(update_fail_malformed_htlcs.is_empty());
3943 assert!(update_fee.is_none());
3945 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3946 let events_3 = nodes[0].node.get_and_clear_pending_events();
3947 assert_eq!(events_3.len(), 1);
3949 Event::PaymentSent { ref payment_preimage } => {
3950 assert_eq!(*payment_preimage, payment_preimage_1);
3952 _ => panic!("Unexpected event"),
3955 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3956 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3957 // No commitment_signed so get_event_msg's assert(len == 1) passes
3958 check_added_monitors!(nodes[0], 1);
3960 _ => panic!("Unexpected event"),
3963 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3964 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3966 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3967 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3968 assert_eq!(reestablish_1.len(), 1);
3969 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3970 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3971 assert_eq!(reestablish_2.len(), 1);
3973 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3974 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3975 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3976 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3978 assert!(as_resp.0.is_none());
3979 assert!(bs_resp.0.is_none());
3981 assert!(bs_resp.1.is_none());
3982 assert!(bs_resp.2.is_none());
3984 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3986 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3987 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3988 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3989 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3990 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3991 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3992 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3993 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3994 // No commitment_signed so get_event_msg's assert(len == 1) passes
3995 check_added_monitors!(nodes[1], 1);
3997 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3998 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3999 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4000 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4001 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4002 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4003 assert!(bs_second_commitment_signed.update_fee.is_none());
4004 check_added_monitors!(nodes[1], 1);
4006 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4007 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4008 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4009 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4010 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4011 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4012 assert!(as_commitment_signed.update_fee.is_none());
4013 check_added_monitors!(nodes[0], 1);
4015 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4016 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4017 // No commitment_signed so get_event_msg's assert(len == 1) passes
4018 check_added_monitors!(nodes[0], 1);
4020 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4021 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4022 // No commitment_signed so get_event_msg's assert(len == 1) passes
4023 check_added_monitors!(nodes[1], 1);
4025 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4026 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4027 check_added_monitors!(nodes[1], 1);
4029 expect_pending_htlcs_forwardable!(nodes[1]);
4031 let events_5 = nodes[1].node.get_and_clear_pending_events();
4032 assert_eq!(events_5.len(), 1);
4034 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4035 assert_eq!(payment_hash_2, *payment_hash);
4036 assert_eq!(*payment_secret, None);
4038 _ => panic!("Unexpected event"),
4041 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4042 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4043 check_added_monitors!(nodes[0], 1);
4045 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4048 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4049 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4050 // to avoid our counterparty failing the channel.
4051 let chanmon_cfgs = create_chanmon_cfgs(2);
4052 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4053 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4054 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4056 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4057 let logger = test_utils::TestLogger::new();
4059 let our_payment_hash = if send_partial_mpp {
4060 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4061 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4062 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4063 let payment_secret = PaymentSecret([0xdb; 32]);
4064 // Use the utility function send_payment_along_path to send the payment with MPP data which
4065 // indicates there are more HTLCs coming.
4066 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.
4067 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4068 check_added_monitors!(nodes[0], 1);
4069 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4070 assert_eq!(events.len(), 1);
4071 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4072 // hop should *not* yet generate any PaymentReceived event(s).
4073 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4076 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4079 let mut block = Block {
4080 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4083 connect_block(&nodes[0], &block);
4084 connect_block(&nodes[1], &block);
4085 for _ in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4086 block.header.prev_blockhash = block.block_hash();
4087 connect_block(&nodes[0], &block);
4088 connect_block(&nodes[1], &block);
4091 expect_pending_htlcs_forwardable!(nodes[1]);
4093 check_added_monitors!(nodes[1], 1);
4094 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4095 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4096 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4097 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4098 assert!(htlc_timeout_updates.update_fee.is_none());
4100 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4101 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4102 // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4103 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4104 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4105 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4109 fn test_htlc_timeout() {
4110 do_test_htlc_timeout(true);
4111 do_test_htlc_timeout(false);
4114 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4115 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4116 let chanmon_cfgs = create_chanmon_cfgs(3);
4117 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4118 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4119 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4120 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4121 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4123 // Make sure all nodes are at the same starting height
4124 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4125 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4126 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4128 let logger = test_utils::TestLogger::new();
4130 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4131 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4133 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4134 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4135 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4137 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4138 check_added_monitors!(nodes[1], 1);
4140 // Now attempt to route a second payment, which should be placed in the holding cell
4141 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4143 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4144 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4145 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4146 check_added_monitors!(nodes[0], 1);
4147 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4148 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4149 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4150 expect_pending_htlcs_forwardable!(nodes[1]);
4151 check_added_monitors!(nodes[1], 0);
4153 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4154 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4155 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4156 check_added_monitors!(nodes[1], 0);
4159 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4160 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4161 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4162 connect_blocks(&nodes[1], 1);
4165 expect_pending_htlcs_forwardable!(nodes[1]);
4166 check_added_monitors!(nodes[1], 1);
4167 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4168 assert_eq!(fail_commit.len(), 1);
4169 match fail_commit[0] {
4170 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4171 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4172 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4174 _ => unreachable!(),
4176 expect_payment_failed!(nodes[0], second_payment_hash, false);
4177 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4179 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4180 _ => panic!("Unexpected event"),
4183 panic!("Unexpected event");
4186 expect_payment_failed!(nodes[1], second_payment_hash, true);
4191 fn test_holding_cell_htlc_add_timeouts() {
4192 do_test_holding_cell_htlc_add_timeouts(false);
4193 do_test_holding_cell_htlc_add_timeouts(true);
4197 fn test_invalid_channel_announcement() {
4198 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4199 let secp_ctx = Secp256k1::new();
4200 let chanmon_cfgs = create_chanmon_cfgs(2);
4201 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4202 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4203 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4205 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4207 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4208 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4209 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4210 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4212 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 } );
4214 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4215 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4217 let as_network_key = nodes[0].node.get_our_node_id();
4218 let bs_network_key = nodes[1].node.get_our_node_id();
4220 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4222 let mut chan_announcement;
4224 macro_rules! dummy_unsigned_msg {
4226 msgs::UnsignedChannelAnnouncement {
4227 features: ChannelFeatures::known(),
4228 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4229 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4230 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4231 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4232 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4233 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4234 excess_data: Vec::new(),
4239 macro_rules! sign_msg {
4240 ($unsigned_msg: expr) => {
4241 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4242 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4243 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4244 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4245 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4246 chan_announcement = msgs::ChannelAnnouncement {
4247 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4248 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4249 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4250 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4251 contents: $unsigned_msg
4256 let unsigned_msg = dummy_unsigned_msg!();
4257 sign_msg!(unsigned_msg);
4258 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4259 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 } );
4261 // Configured with Network::Testnet
4262 let mut unsigned_msg = dummy_unsigned_msg!();
4263 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4264 sign_msg!(unsigned_msg);
4265 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4267 let mut unsigned_msg = dummy_unsigned_msg!();
4268 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4269 sign_msg!(unsigned_msg);
4270 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4274 fn test_no_txn_manager_serialize_deserialize() {
4275 let chanmon_cfgs = create_chanmon_cfgs(2);
4276 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4277 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4278 let logger: test_utils::TestLogger;
4279 let fee_estimator: test_utils::TestFeeEstimator;
4280 let persister: test_utils::TestPersister;
4281 let new_chain_monitor: test_utils::TestChainMonitor;
4282 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4283 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4285 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4287 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4289 let nodes_0_serialized = nodes[0].node.encode();
4290 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4291 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4293 logger = test_utils::TestLogger::new();
4294 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4295 persister = test_utils::TestPersister::new();
4296 let keys_manager = &chanmon_cfgs[0].keys_manager;
4297 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4298 nodes[0].chain_monitor = &new_chain_monitor;
4299 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4300 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4301 &mut chan_0_monitor_read, keys_manager).unwrap();
4302 assert!(chan_0_monitor_read.is_empty());
4304 let mut nodes_0_read = &nodes_0_serialized[..];
4305 let config = UserConfig::default();
4306 let (_, nodes_0_deserialized_tmp) = {
4307 let mut channel_monitors = HashMap::new();
4308 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4309 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4310 default_config: config,
4312 fee_estimator: &fee_estimator,
4313 chain_monitor: nodes[0].chain_monitor,
4314 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4319 nodes_0_deserialized = nodes_0_deserialized_tmp;
4320 assert!(nodes_0_read.is_empty());
4322 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4323 nodes[0].node = &nodes_0_deserialized;
4324 assert_eq!(nodes[0].node.list_channels().len(), 1);
4325 check_added_monitors!(nodes[0], 1);
4327 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4328 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4329 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4330 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4332 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4333 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4334 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4335 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4337 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4338 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4339 for node in nodes.iter() {
4340 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4341 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4342 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4345 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4349 fn test_manager_serialize_deserialize_events() {
4350 // This test makes sure the events field in ChannelManager survives de/serialization
4351 let chanmon_cfgs = create_chanmon_cfgs(2);
4352 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4353 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4354 let fee_estimator: test_utils::TestFeeEstimator;
4355 let persister: test_utils::TestPersister;
4356 let logger: test_utils::TestLogger;
4357 let new_chain_monitor: test_utils::TestChainMonitor;
4358 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4359 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4361 // Start creating a channel, but stop right before broadcasting the funding transaction
4362 let channel_value = 100000;
4363 let push_msat = 10001;
4364 let a_flags = InitFeatures::known();
4365 let b_flags = InitFeatures::known();
4366 let node_a = nodes.remove(0);
4367 let node_b = nodes.remove(0);
4368 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4369 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()));
4370 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()));
4372 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4374 node_a.node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
4375 check_added_monitors!(node_a, 0);
4377 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()));
4379 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4380 assert_eq!(added_monitors.len(), 1);
4381 assert_eq!(added_monitors[0].0, funding_output);
4382 added_monitors.clear();
4385 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()));
4387 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4388 assert_eq!(added_monitors.len(), 1);
4389 assert_eq!(added_monitors[0].0, funding_output);
4390 added_monitors.clear();
4392 // Normally, this is where node_a would broadcast the funding transaction, but the test de/serializes first instead
4397 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4398 let nodes_0_serialized = nodes[0].node.encode();
4399 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4400 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4402 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4403 logger = test_utils::TestLogger::new();
4404 persister = test_utils::TestPersister::new();
4405 let keys_manager = &chanmon_cfgs[0].keys_manager;
4406 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4407 nodes[0].chain_monitor = &new_chain_monitor;
4408 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4409 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4410 &mut chan_0_monitor_read, keys_manager).unwrap();
4411 assert!(chan_0_monitor_read.is_empty());
4413 let mut nodes_0_read = &nodes_0_serialized[..];
4414 let config = UserConfig::default();
4415 let (_, nodes_0_deserialized_tmp) = {
4416 let mut channel_monitors = HashMap::new();
4417 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4418 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4419 default_config: config,
4421 fee_estimator: &fee_estimator,
4422 chain_monitor: nodes[0].chain_monitor,
4423 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4428 nodes_0_deserialized = nodes_0_deserialized_tmp;
4429 assert!(nodes_0_read.is_empty());
4431 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4433 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4434 nodes[0].node = &nodes_0_deserialized;
4436 // After deserializing, make sure the funding_transaction is still held by the channel manager
4437 let events_4 = nodes[0].node.get_and_clear_pending_events();
4438 assert_eq!(events_4.len(), 0);
4439 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
4440 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
4442 // Make sure the channel is functioning as though the de/serialization never happened
4443 assert_eq!(nodes[0].node.list_channels().len(), 1);
4444 check_added_monitors!(nodes[0], 1);
4446 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4447 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4448 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4449 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4451 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4452 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4453 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4454 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4456 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4457 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4458 for node in nodes.iter() {
4459 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4460 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4461 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4464 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4468 fn test_simple_manager_serialize_deserialize() {
4469 let chanmon_cfgs = create_chanmon_cfgs(2);
4470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4472 let logger: test_utils::TestLogger;
4473 let fee_estimator: test_utils::TestFeeEstimator;
4474 let persister: test_utils::TestPersister;
4475 let new_chain_monitor: test_utils::TestChainMonitor;
4476 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4478 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4480 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4481 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4483 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4485 let nodes_0_serialized = nodes[0].node.encode();
4486 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4487 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4489 logger = test_utils::TestLogger::new();
4490 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4491 persister = test_utils::TestPersister::new();
4492 let keys_manager = &chanmon_cfgs[0].keys_manager;
4493 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4494 nodes[0].chain_monitor = &new_chain_monitor;
4495 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4496 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4497 &mut chan_0_monitor_read, keys_manager).unwrap();
4498 assert!(chan_0_monitor_read.is_empty());
4500 let mut nodes_0_read = &nodes_0_serialized[..];
4501 let (_, nodes_0_deserialized_tmp) = {
4502 let mut channel_monitors = HashMap::new();
4503 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4504 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4505 default_config: UserConfig::default(),
4507 fee_estimator: &fee_estimator,
4508 chain_monitor: nodes[0].chain_monitor,
4509 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4514 nodes_0_deserialized = nodes_0_deserialized_tmp;
4515 assert!(nodes_0_read.is_empty());
4517 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4518 nodes[0].node = &nodes_0_deserialized;
4519 check_added_monitors!(nodes[0], 1);
4521 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4523 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4524 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4528 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4529 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4530 let chanmon_cfgs = create_chanmon_cfgs(4);
4531 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4532 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4533 let logger: test_utils::TestLogger;
4534 let fee_estimator: test_utils::TestFeeEstimator;
4535 let persister: test_utils::TestPersister;
4536 let new_chain_monitor: test_utils::TestChainMonitor;
4537 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4538 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4539 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4540 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4541 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4543 let mut node_0_stale_monitors_serialized = Vec::new();
4544 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4545 let mut writer = test_utils::TestVecWriter(Vec::new());
4546 monitor.1.write(&mut writer).unwrap();
4547 node_0_stale_monitors_serialized.push(writer.0);
4550 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4552 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4553 let nodes_0_serialized = nodes[0].node.encode();
4555 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4556 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4557 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4558 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4560 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4562 let mut node_0_monitors_serialized = Vec::new();
4563 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4564 let mut writer = test_utils::TestVecWriter(Vec::new());
4565 monitor.1.write(&mut writer).unwrap();
4566 node_0_monitors_serialized.push(writer.0);
4569 logger = test_utils::TestLogger::new();
4570 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4571 persister = test_utils::TestPersister::new();
4572 let keys_manager = &chanmon_cfgs[0].keys_manager;
4573 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4574 nodes[0].chain_monitor = &new_chain_monitor;
4577 let mut node_0_stale_monitors = Vec::new();
4578 for serialized in node_0_stale_monitors_serialized.iter() {
4579 let mut read = &serialized[..];
4580 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4581 assert!(read.is_empty());
4582 node_0_stale_monitors.push(monitor);
4585 let mut node_0_monitors = Vec::new();
4586 for serialized in node_0_monitors_serialized.iter() {
4587 let mut read = &serialized[..];
4588 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4589 assert!(read.is_empty());
4590 node_0_monitors.push(monitor);
4593 let mut nodes_0_read = &nodes_0_serialized[..];
4594 if let Err(msgs::DecodeError::InvalidValue) =
4595 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4596 default_config: UserConfig::default(),
4598 fee_estimator: &fee_estimator,
4599 chain_monitor: nodes[0].chain_monitor,
4600 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4602 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4604 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4607 let mut nodes_0_read = &nodes_0_serialized[..];
4608 let (_, nodes_0_deserialized_tmp) =
4609 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4610 default_config: UserConfig::default(),
4612 fee_estimator: &fee_estimator,
4613 chain_monitor: nodes[0].chain_monitor,
4614 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4616 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4618 nodes_0_deserialized = nodes_0_deserialized_tmp;
4619 assert!(nodes_0_read.is_empty());
4621 { // Channel close should result in a commitment tx and an HTLC tx
4622 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4623 assert_eq!(txn.len(), 2);
4624 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4625 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4628 for monitor in node_0_monitors.drain(..) {
4629 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4630 check_added_monitors!(nodes[0], 1);
4632 nodes[0].node = &nodes_0_deserialized;
4634 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4635 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4636 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4637 //... and we can even still claim the payment!
4638 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4640 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4641 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4642 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4643 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4644 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4645 assert_eq!(msg_events.len(), 1);
4646 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4648 &ErrorAction::SendErrorMessage { ref msg } => {
4649 assert_eq!(msg.channel_id, channel_id);
4651 _ => panic!("Unexpected event!"),
4656 macro_rules! check_spendable_outputs {
4657 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4659 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4660 let mut txn = Vec::new();
4661 let mut all_outputs = Vec::new();
4662 let secp_ctx = Secp256k1::new();
4663 for event in events.drain(..) {
4665 Event::SpendableOutputs { mut outputs } => {
4666 for outp in outputs.drain(..) {
4667 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4668 all_outputs.push(outp);
4671 _ => panic!("Unexpected event"),
4674 if all_outputs.len() > 1 {
4675 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) {
4685 fn test_claim_sizeable_push_msat() {
4686 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4687 let chanmon_cfgs = create_chanmon_cfgs(2);
4688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4690 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4692 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4693 nodes[1].node.force_close_channel(&chan.2).unwrap();
4694 check_closed_broadcast!(nodes[1], true);
4695 check_added_monitors!(nodes[1], 1);
4696 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4697 assert_eq!(node_txn.len(), 1);
4698 check_spends!(node_txn[0], chan.3);
4699 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
4701 mine_transaction(&nodes[1], &node_txn[0]);
4702 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4704 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4705 assert_eq!(spend_txn.len(), 1);
4706 check_spends!(spend_txn[0], node_txn[0]);
4710 fn test_claim_on_remote_sizeable_push_msat() {
4711 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4712 // to_remote output is encumbered by a P2WPKH
4713 let chanmon_cfgs = create_chanmon_cfgs(2);
4714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4716 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4718 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4719 nodes[0].node.force_close_channel(&chan.2).unwrap();
4720 check_closed_broadcast!(nodes[0], true);
4721 check_added_monitors!(nodes[0], 1);
4723 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4724 assert_eq!(node_txn.len(), 1);
4725 check_spends!(node_txn[0], chan.3);
4726 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
4728 mine_transaction(&nodes[1], &node_txn[0]);
4729 check_closed_broadcast!(nodes[1], true);
4730 check_added_monitors!(nodes[1], 1);
4731 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4733 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4734 assert_eq!(spend_txn.len(), 1);
4735 check_spends!(spend_txn[0], node_txn[0]);
4739 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4740 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4741 // to_remote output is encumbered by a P2WPKH
4743 let chanmon_cfgs = create_chanmon_cfgs(2);
4744 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4745 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4746 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4748 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4749 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4750 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4751 assert_eq!(revoked_local_txn[0].input.len(), 1);
4752 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4754 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4755 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4756 check_closed_broadcast!(nodes[1], true);
4757 check_added_monitors!(nodes[1], 1);
4759 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4760 mine_transaction(&nodes[1], &node_txn[0]);
4761 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4763 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4764 assert_eq!(spend_txn.len(), 3);
4765 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4766 check_spends!(spend_txn[1], node_txn[0]);
4767 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4771 fn test_static_spendable_outputs_preimage_tx() {
4772 let chanmon_cfgs = create_chanmon_cfgs(2);
4773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4775 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4777 // Create some initial channels
4778 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4780 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4782 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4783 assert_eq!(commitment_tx[0].input.len(), 1);
4784 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4786 // Settle A's commitment tx on B's chain
4787 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4788 check_added_monitors!(nodes[1], 1);
4789 mine_transaction(&nodes[1], &commitment_tx[0]);
4790 check_added_monitors!(nodes[1], 1);
4791 let events = nodes[1].node.get_and_clear_pending_msg_events();
4793 MessageSendEvent::UpdateHTLCs { .. } => {},
4794 _ => panic!("Unexpected event"),
4797 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4798 _ => panic!("Unexepected event"),
4801 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4802 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4803 assert_eq!(node_txn.len(), 3);
4804 check_spends!(node_txn[0], commitment_tx[0]);
4805 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4806 check_spends!(node_txn[1], chan_1.3);
4807 check_spends!(node_txn[2], node_txn[1]);
4809 mine_transaction(&nodes[1], &node_txn[0]);
4810 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4812 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4813 assert_eq!(spend_txn.len(), 1);
4814 check_spends!(spend_txn[0], node_txn[0]);
4818 fn test_static_spendable_outputs_timeout_tx() {
4819 let chanmon_cfgs = create_chanmon_cfgs(2);
4820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824 // Create some initial channels
4825 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4827 // Rebalance the network a bit by relaying one payment through all the channels ...
4828 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4830 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4832 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4833 assert_eq!(commitment_tx[0].input.len(), 1);
4834 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4836 // Settle A's commitment tx on B' chain
4837 mine_transaction(&nodes[1], &commitment_tx[0]);
4838 check_added_monitors!(nodes[1], 1);
4839 let events = nodes[1].node.get_and_clear_pending_msg_events();
4841 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4842 _ => panic!("Unexpected event"),
4845 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4846 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4847 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4848 check_spends!(node_txn[0], commitment_tx[0].clone());
4849 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4850 check_spends!(node_txn[1], chan_1.3.clone());
4851 check_spends!(node_txn[2], node_txn[1]);
4853 mine_transaction(&nodes[1], &node_txn[0]);
4854 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4855 expect_payment_failed!(nodes[1], our_payment_hash, true);
4857 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4858 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4859 check_spends!(spend_txn[0], commitment_tx[0]);
4860 check_spends!(spend_txn[1], node_txn[0]);
4861 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4865 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4866 let chanmon_cfgs = create_chanmon_cfgs(2);
4867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4869 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4871 // Create some initial channels
4872 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4874 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4875 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4876 assert_eq!(revoked_local_txn[0].input.len(), 1);
4877 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4879 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4881 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4882 check_closed_broadcast!(nodes[1], true);
4883 check_added_monitors!(nodes[1], 1);
4885 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4886 assert_eq!(node_txn.len(), 2);
4887 assert_eq!(node_txn[0].input.len(), 2);
4888 check_spends!(node_txn[0], revoked_local_txn[0]);
4890 mine_transaction(&nodes[1], &node_txn[0]);
4891 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4893 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4894 assert_eq!(spend_txn.len(), 1);
4895 check_spends!(spend_txn[0], node_txn[0]);
4899 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4900 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4901 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4902 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4903 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4904 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906 // Create some initial channels
4907 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4909 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4910 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4911 assert_eq!(revoked_local_txn[0].input.len(), 1);
4912 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4914 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4916 // A will generate HTLC-Timeout from revoked commitment tx
4917 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4918 check_closed_broadcast!(nodes[0], true);
4919 check_added_monitors!(nodes[0], 1);
4921 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4922 assert_eq!(revoked_htlc_txn.len(), 2);
4923 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4924 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4925 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4926 check_spends!(revoked_htlc_txn[1], chan_1.3);
4928 // B will generate justice tx from A's revoked commitment/HTLC tx
4929 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4930 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
4931 check_closed_broadcast!(nodes[1], true);
4932 check_added_monitors!(nodes[1], 1);
4934 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4935 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4936 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4937 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4938 // transactions next...
4939 assert_eq!(node_txn[0].input.len(), 3);
4940 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4942 assert_eq!(node_txn[1].input.len(), 2);
4943 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4944 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4945 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4947 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4948 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4951 assert_eq!(node_txn[2].input.len(), 1);
4952 check_spends!(node_txn[2], chan_1.3);
4954 mine_transaction(&nodes[1], &node_txn[1]);
4955 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4957 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4958 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4959 assert_eq!(spend_txn.len(), 1);
4960 assert_eq!(spend_txn[0].input.len(), 1);
4961 check_spends!(spend_txn[0], node_txn[1]);
4965 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4966 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4967 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
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;
4976 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4977 assert_eq!(revoked_local_txn[0].input.len(), 1);
4978 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4980 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4981 assert_eq!(revoked_local_txn[0].output.len(), 2);
4983 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4985 // B will generate HTLC-Success from revoked commitment tx
4986 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4987 check_closed_broadcast!(nodes[1], true);
4988 check_added_monitors!(nodes[1], 1);
4989 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4991 assert_eq!(revoked_htlc_txn.len(), 2);
4992 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4993 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4994 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4996 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4997 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4998 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5000 // A will generate justice tx from B's revoked commitment/HTLC tx
5001 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5002 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] });
5003 check_closed_broadcast!(nodes[0], true);
5004 check_added_monitors!(nodes[0], 1);
5006 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5007 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5009 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5010 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5011 // transactions next...
5012 assert_eq!(node_txn[0].input.len(), 2);
5013 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5014 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5015 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5017 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5018 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5021 assert_eq!(node_txn[1].input.len(), 1);
5022 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5024 check_spends!(node_txn[2], chan_1.3);
5026 mine_transaction(&nodes[0], &node_txn[1]);
5027 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5029 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5030 // didn't try to generate any new transactions.
5032 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5033 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5034 assert_eq!(spend_txn.len(), 3);
5035 assert_eq!(spend_txn[0].input.len(), 1);
5036 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5037 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5038 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5039 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5043 fn test_onchain_to_onchain_claim() {
5044 // Test that in case of channel closure, we detect the state of output and claim HTLC
5045 // on downstream peer's remote commitment tx.
5046 // First, have C claim an HTLC against its own latest commitment transaction.
5047 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5049 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5052 let chanmon_cfgs = create_chanmon_cfgs(3);
5053 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5054 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5055 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5057 // Create some initial channels
5058 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5059 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5061 // Rebalance the network a bit by relaying one payment through all the channels ...
5062 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5063 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5065 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5066 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5067 check_spends!(commitment_tx[0], chan_2.3);
5068 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5069 check_added_monitors!(nodes[2], 1);
5070 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5071 assert!(updates.update_add_htlcs.is_empty());
5072 assert!(updates.update_fail_htlcs.is_empty());
5073 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5074 assert!(updates.update_fail_malformed_htlcs.is_empty());
5076 mine_transaction(&nodes[2], &commitment_tx[0]);
5077 check_closed_broadcast!(nodes[2], true);
5078 check_added_monitors!(nodes[2], 1);
5080 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5081 assert_eq!(c_txn.len(), 3);
5082 assert_eq!(c_txn[0], c_txn[2]);
5083 assert_eq!(commitment_tx[0], c_txn[1]);
5084 check_spends!(c_txn[1], chan_2.3);
5085 check_spends!(c_txn[2], c_txn[1]);
5086 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5087 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5088 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5089 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5091 // 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
5092 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5093 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]});
5095 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5096 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5097 assert_eq!(b_txn.len(), 3);
5098 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5099 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5100 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5101 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5102 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5103 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5104 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5105 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5106 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5109 check_added_monitors!(nodes[1], 1);
5110 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5111 assert_eq!(msg_events.len(), 3);
5112 check_added_monitors!(nodes[1], 1);
5113 match msg_events[0] {
5114 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5115 _ => panic!("Unexpected event"),
5117 match msg_events[1] {
5118 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { .. }, node_id: _ } => {},
5119 _ => panic!("Unexpected event"),
5121 match msg_events[2] {
5122 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, .. } } => {
5123 assert!(update_add_htlcs.is_empty());
5124 assert!(update_fail_htlcs.is_empty());
5125 assert_eq!(update_fulfill_htlcs.len(), 1);
5126 assert!(update_fail_malformed_htlcs.is_empty());
5127 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5129 _ => panic!("Unexpected event"),
5131 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5132 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5133 mine_transaction(&nodes[1], &commitment_tx[0]);
5134 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5135 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5136 assert_eq!(b_txn.len(), 3);
5137 check_spends!(b_txn[1], chan_1.3);
5138 check_spends!(b_txn[2], b_txn[1]);
5139 check_spends!(b_txn[0], commitment_tx[0]);
5140 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5141 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5142 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5144 check_closed_broadcast!(nodes[1], true);
5145 check_added_monitors!(nodes[1], 1);
5149 fn test_duplicate_payment_hash_one_failure_one_success() {
5150 // Topology : A --> B --> C
5151 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5152 let chanmon_cfgs = create_chanmon_cfgs(3);
5153 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5154 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5155 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5157 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5158 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5160 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5161 *nodes[0].network_payment_count.borrow_mut() -= 1;
5162 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5164 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5165 assert_eq!(commitment_txn[0].input.len(), 1);
5166 check_spends!(commitment_txn[0], chan_2.3);
5168 mine_transaction(&nodes[1], &commitment_txn[0]);
5169 check_closed_broadcast!(nodes[1], true);
5170 check_added_monitors!(nodes[1], 1);
5172 let htlc_timeout_tx;
5173 { // Extract one of the two HTLC-Timeout transaction
5174 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5175 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5176 assert_eq!(node_txn.len(), 5);
5177 check_spends!(node_txn[0], commitment_txn[0]);
5178 assert_eq!(node_txn[0].input.len(), 1);
5179 check_spends!(node_txn[1], commitment_txn[0]);
5180 assert_eq!(node_txn[1].input.len(), 1);
5181 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5182 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5183 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184 check_spends!(node_txn[2], chan_2.3);
5185 check_spends!(node_txn[3], node_txn[2]);
5186 check_spends!(node_txn[4], node_txn[2]);
5187 htlc_timeout_tx = node_txn[1].clone();
5190 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5191 mine_transaction(&nodes[2], &commitment_txn[0]);
5192 check_added_monitors!(nodes[2], 3);
5193 let events = nodes[2].node.get_and_clear_pending_msg_events();
5195 MessageSendEvent::UpdateHTLCs { .. } => {},
5196 _ => panic!("Unexpected event"),
5199 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5200 _ => panic!("Unexepected event"),
5202 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5203 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)
5204 check_spends!(htlc_success_txn[2], chan_2.3);
5205 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5206 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5207 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5208 assert_eq!(htlc_success_txn[0].input.len(), 1);
5209 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5210 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5211 assert_eq!(htlc_success_txn[1].input.len(), 1);
5212 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5213 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5214 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5215 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5217 mine_transaction(&nodes[1], &htlc_timeout_tx);
5218 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5219 expect_pending_htlcs_forwardable!(nodes[1]);
5220 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5221 assert!(htlc_updates.update_add_htlcs.is_empty());
5222 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5223 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5224 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5225 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5226 check_added_monitors!(nodes[1], 1);
5228 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5229 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5231 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5232 let events = nodes[0].node.get_and_clear_pending_msg_events();
5233 assert_eq!(events.len(), 1);
5235 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5237 _ => { panic!("Unexpected event"); }
5240 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5242 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5243 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5244 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5245 assert!(updates.update_add_htlcs.is_empty());
5246 assert!(updates.update_fail_htlcs.is_empty());
5247 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5248 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5249 assert!(updates.update_fail_malformed_htlcs.is_empty());
5250 check_added_monitors!(nodes[1], 1);
5252 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5253 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5255 let events = nodes[0].node.get_and_clear_pending_events();
5257 Event::PaymentSent { ref payment_preimage } => {
5258 assert_eq!(*payment_preimage, our_payment_preimage);
5260 _ => panic!("Unexpected event"),
5265 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5266 let chanmon_cfgs = create_chanmon_cfgs(2);
5267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5271 // Create some initial channels
5272 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5274 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5275 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5276 assert_eq!(local_txn.len(), 1);
5277 assert_eq!(local_txn[0].input.len(), 1);
5278 check_spends!(local_txn[0], chan_1.3);
5280 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5281 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5282 check_added_monitors!(nodes[1], 1);
5283 mine_transaction(&nodes[1], &local_txn[0]);
5284 check_added_monitors!(nodes[1], 1);
5285 let events = nodes[1].node.get_and_clear_pending_msg_events();
5287 MessageSendEvent::UpdateHTLCs { .. } => {},
5288 _ => panic!("Unexpected event"),
5291 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5292 _ => panic!("Unexepected event"),
5295 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5296 assert_eq!(node_txn.len(), 3);
5297 assert_eq!(node_txn[0], node_txn[2]);
5298 assert_eq!(node_txn[1], local_txn[0]);
5299 assert_eq!(node_txn[0].input.len(), 1);
5300 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5301 check_spends!(node_txn[0], local_txn[0]);
5305 mine_transaction(&nodes[1], &node_tx);
5306 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5308 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5309 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5310 assert_eq!(spend_txn.len(), 1);
5311 check_spends!(spend_txn[0], node_tx);
5314 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5315 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5316 // unrevoked commitment transaction.
5317 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5318 // a remote RAA before they could be failed backwards (and combinations thereof).
5319 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5320 // use the same payment hashes.
5321 // Thus, we use a six-node network:
5326 // And test where C fails back to A/B when D announces its latest commitment transaction
5327 let chanmon_cfgs = create_chanmon_cfgs(6);
5328 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5329 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5330 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5331 let logger = test_utils::TestLogger::new();
5333 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5334 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5335 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5336 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5337 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5339 // Rebalance and check output sanity...
5340 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5341 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5342 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5344 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5346 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
5348 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
5349 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5350 let our_node_id = &nodes[1].node.get_our_node_id();
5351 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5353 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5355 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_2); // not added < dust limit + HTLC tx fee
5357 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5359 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5360 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5362 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5364 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5367 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5369 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5370 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_5); // not added < dust limit + HTLC tx fee
5373 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
5375 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5376 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5378 // Double-check that six of the new HTLC were added
5379 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5380 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5381 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5382 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5384 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5385 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5386 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5387 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5388 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5389 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5390 check_added_monitors!(nodes[4], 0);
5391 expect_pending_htlcs_forwardable!(nodes[4]);
5392 check_added_monitors!(nodes[4], 1);
5394 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5395 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5396 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5397 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5398 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5399 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5401 // Fail 3rd below-dust and 7th above-dust HTLCs
5402 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5403 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5404 check_added_monitors!(nodes[5], 0);
5405 expect_pending_htlcs_forwardable!(nodes[5]);
5406 check_added_monitors!(nodes[5], 1);
5408 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5409 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5410 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5411 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5413 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5415 expect_pending_htlcs_forwardable!(nodes[3]);
5416 check_added_monitors!(nodes[3], 1);
5417 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5418 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5419 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5420 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5421 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5422 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5423 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5424 if deliver_last_raa {
5425 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5427 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5430 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5431 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5432 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5433 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5435 // We now broadcast the latest commitment transaction, which *should* result in failures for
5436 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5437 // the non-broadcast above-dust HTLCs.
5439 // Alternatively, we may broadcast the previous commitment transaction, which should only
5440 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5441 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5443 if announce_latest {
5444 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5446 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5448 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5449 check_closed_broadcast!(nodes[2], true);
5450 expect_pending_htlcs_forwardable!(nodes[2]);
5451 check_added_monitors!(nodes[2], 3);
5453 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5454 assert_eq!(cs_msgs.len(), 2);
5455 let mut a_done = false;
5456 for msg in cs_msgs {
5458 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5459 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5460 // should be failed-backwards here.
5461 let target = if *node_id == nodes[0].node.get_our_node_id() {
5462 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5463 for htlc in &updates.update_fail_htlcs {
5464 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 });
5466 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5471 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5472 for htlc in &updates.update_fail_htlcs {
5473 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5475 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5476 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5479 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5480 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5481 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5482 if announce_latest {
5483 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5484 if *node_id == nodes[0].node.get_our_node_id() {
5485 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5488 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5490 _ => panic!("Unexpected event"),
5494 let as_events = nodes[0].node.get_and_clear_pending_events();
5495 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5496 let mut as_failds = HashSet::new();
5497 for event in as_events.iter() {
5498 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5499 assert!(as_failds.insert(*payment_hash));
5500 if *payment_hash != payment_hash_2 {
5501 assert_eq!(*rejected_by_dest, deliver_last_raa);
5503 assert!(!rejected_by_dest);
5505 } else { panic!("Unexpected event"); }
5507 assert!(as_failds.contains(&payment_hash_1));
5508 assert!(as_failds.contains(&payment_hash_2));
5509 if announce_latest {
5510 assert!(as_failds.contains(&payment_hash_3));
5511 assert!(as_failds.contains(&payment_hash_5));
5513 assert!(as_failds.contains(&payment_hash_6));
5515 let bs_events = nodes[1].node.get_and_clear_pending_events();
5516 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5517 let mut bs_failds = HashSet::new();
5518 for event in bs_events.iter() {
5519 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5520 assert!(bs_failds.insert(*payment_hash));
5521 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5522 assert_eq!(*rejected_by_dest, deliver_last_raa);
5524 assert!(!rejected_by_dest);
5526 } else { panic!("Unexpected event"); }
5528 assert!(bs_failds.contains(&payment_hash_1));
5529 assert!(bs_failds.contains(&payment_hash_2));
5530 if announce_latest {
5531 assert!(bs_failds.contains(&payment_hash_4));
5533 assert!(bs_failds.contains(&payment_hash_5));
5535 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5536 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5537 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5538 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5539 // PaymentFailureNetworkUpdates.
5540 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5541 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5542 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5543 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5544 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5546 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5547 _ => panic!("Unexpected event"),
5553 fn test_fail_backwards_latest_remote_announce_a() {
5554 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5558 fn test_fail_backwards_latest_remote_announce_b() {
5559 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5563 fn test_fail_backwards_previous_remote_announce() {
5564 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5565 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5566 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5570 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5571 let chanmon_cfgs = create_chanmon_cfgs(2);
5572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5576 // Create some initial channels
5577 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5579 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5580 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5581 assert_eq!(local_txn[0].input.len(), 1);
5582 check_spends!(local_txn[0], chan_1.3);
5584 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5585 mine_transaction(&nodes[0], &local_txn[0]);
5586 check_closed_broadcast!(nodes[0], true);
5587 check_added_monitors!(nodes[0], 1);
5589 let htlc_timeout = {
5590 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5591 assert_eq!(node_txn[0].input.len(), 1);
5592 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5593 check_spends!(node_txn[0], local_txn[0]);
5597 mine_transaction(&nodes[0], &htlc_timeout);
5598 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5599 expect_payment_failed!(nodes[0], our_payment_hash, true);
5601 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5602 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5603 assert_eq!(spend_txn.len(), 3);
5604 check_spends!(spend_txn[0], local_txn[0]);
5605 check_spends!(spend_txn[1], htlc_timeout);
5606 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5610 fn test_key_derivation_params() {
5611 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5612 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5613 // let us re-derive the channel key set to then derive a delayed_payment_key.
5615 let chanmon_cfgs = create_chanmon_cfgs(3);
5617 // We manually create the node configuration to backup the seed.
5618 let seed = [42; 32];
5619 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5620 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);
5621 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 };
5622 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5623 node_cfgs.remove(0);
5624 node_cfgs.insert(0, node);
5626 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5627 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5629 // Create some initial channels
5630 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5632 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5633 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5634 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5636 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5637 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5638 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5639 assert_eq!(local_txn_1[0].input.len(), 1);
5640 check_spends!(local_txn_1[0], chan_1.3);
5642 // We check funding pubkey are unique
5643 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]));
5644 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]));
5645 if from_0_funding_key_0 == from_1_funding_key_0
5646 || from_0_funding_key_0 == from_1_funding_key_1
5647 || from_0_funding_key_1 == from_1_funding_key_0
5648 || from_0_funding_key_1 == from_1_funding_key_1 {
5649 panic!("Funding pubkeys aren't unique");
5652 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5653 mine_transaction(&nodes[0], &local_txn_1[0]);
5654 check_closed_broadcast!(nodes[0], true);
5655 check_added_monitors!(nodes[0], 1);
5657 let htlc_timeout = {
5658 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5659 assert_eq!(node_txn[0].input.len(), 1);
5660 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5661 check_spends!(node_txn[0], local_txn_1[0]);
5665 mine_transaction(&nodes[0], &htlc_timeout);
5666 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5667 expect_payment_failed!(nodes[0], our_payment_hash, true);
5669 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5670 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5671 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5672 assert_eq!(spend_txn.len(), 3);
5673 check_spends!(spend_txn[0], local_txn_1[0]);
5674 check_spends!(spend_txn[1], htlc_timeout);
5675 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5679 fn test_static_output_closing_tx() {
5680 let chanmon_cfgs = create_chanmon_cfgs(2);
5681 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5682 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5683 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5685 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5687 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5688 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5690 mine_transaction(&nodes[0], &closing_tx);
5691 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5693 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5694 assert_eq!(spend_txn.len(), 1);
5695 check_spends!(spend_txn[0], closing_tx);
5697 mine_transaction(&nodes[1], &closing_tx);
5698 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5700 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5701 assert_eq!(spend_txn.len(), 1);
5702 check_spends!(spend_txn[0], closing_tx);
5705 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5706 let chanmon_cfgs = create_chanmon_cfgs(2);
5707 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5708 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5709 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5710 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5712 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5714 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5715 // present in B's local commitment transaction, but none of A's commitment transactions.
5716 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5717 check_added_monitors!(nodes[1], 1);
5719 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5720 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5721 let events = nodes[0].node.get_and_clear_pending_events();
5722 assert_eq!(events.len(), 1);
5724 Event::PaymentSent { payment_preimage } => {
5725 assert_eq!(payment_preimage, our_payment_preimage);
5727 _ => panic!("Unexpected event"),
5730 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5731 check_added_monitors!(nodes[0], 1);
5732 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5733 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5734 check_added_monitors!(nodes[1], 1);
5736 let starting_block = nodes[1].best_block_info();
5737 let mut block = Block {
5738 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5741 for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5742 connect_block(&nodes[1], &block);
5743 block.header.prev_blockhash = block.block_hash();
5745 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5746 check_closed_broadcast!(nodes[1], true);
5747 check_added_monitors!(nodes[1], 1);
5750 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5751 let chanmon_cfgs = create_chanmon_cfgs(2);
5752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5755 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5756 let logger = test_utils::TestLogger::new();
5758 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5759 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5760 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(), None, None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5761 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5762 check_added_monitors!(nodes[0], 1);
5764 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5766 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5767 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5768 // to "time out" the HTLC.
5770 let starting_block = nodes[1].best_block_info();
5771 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5773 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5774 connect_block(&nodes[0], &Block { header, txdata: Vec::new()});
5775 header.prev_blockhash = header.block_hash();
5777 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5778 check_closed_broadcast!(nodes[0], true);
5779 check_added_monitors!(nodes[0], 1);
5782 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5783 let chanmon_cfgs = create_chanmon_cfgs(3);
5784 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5785 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5786 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5787 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5789 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5790 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5791 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5792 // actually revoked.
5793 let htlc_value = if use_dust { 50000 } else { 3000000 };
5794 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5795 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5796 expect_pending_htlcs_forwardable!(nodes[1]);
5797 check_added_monitors!(nodes[1], 1);
5799 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5800 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5801 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5802 check_added_monitors!(nodes[0], 1);
5803 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5804 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5805 check_added_monitors!(nodes[1], 1);
5806 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5807 check_added_monitors!(nodes[1], 1);
5808 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5810 if check_revoke_no_close {
5811 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5812 check_added_monitors!(nodes[0], 1);
5815 let starting_block = nodes[1].best_block_info();
5816 let mut block = Block {
5817 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5820 for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5821 connect_block(&nodes[0], &block);
5822 block.header.prev_blockhash = block.block_hash();
5824 if !check_revoke_no_close {
5825 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5826 check_closed_broadcast!(nodes[0], true);
5827 check_added_monitors!(nodes[0], 1);
5829 expect_payment_failed!(nodes[0], our_payment_hash, true);
5833 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5834 // There are only a few cases to test here:
5835 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5836 // broadcastable commitment transactions result in channel closure,
5837 // * its included in an unrevoked-but-previous remote commitment transaction,
5838 // * its included in the latest remote or local commitment transactions.
5839 // We test each of the three possible commitment transactions individually and use both dust and
5841 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5842 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5843 // tested for at least one of the cases in other tests.
5845 fn htlc_claim_single_commitment_only_a() {
5846 do_htlc_claim_local_commitment_only(true);
5847 do_htlc_claim_local_commitment_only(false);
5849 do_htlc_claim_current_remote_commitment_only(true);
5850 do_htlc_claim_current_remote_commitment_only(false);
5854 fn htlc_claim_single_commitment_only_b() {
5855 do_htlc_claim_previous_remote_commitment_only(true, false);
5856 do_htlc_claim_previous_remote_commitment_only(false, false);
5857 do_htlc_claim_previous_remote_commitment_only(true, true);
5858 do_htlc_claim_previous_remote_commitment_only(false, true);
5863 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5864 let chanmon_cfgs = create_chanmon_cfgs(2);
5865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5868 //Force duplicate channel ids
5869 for node in nodes.iter() {
5870 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5873 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5874 let channel_value_satoshis=10000;
5875 let push_msat=10001;
5876 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5877 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5878 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5880 //Create a second channel with a channel_id collision
5881 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5885 fn bolt2_open_channel_sending_node_checks_part2() {
5886 let chanmon_cfgs = create_chanmon_cfgs(2);
5887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5889 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5892 let channel_value_satoshis=2^24;
5893 let push_msat=10001;
5894 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5896 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5897 let channel_value_satoshis=10000;
5898 // Test when push_msat is equal to 1000 * funding_satoshis.
5899 let push_msat=1000*channel_value_satoshis+1;
5900 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5902 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5903 let channel_value_satoshis=10000;
5904 let push_msat=10001;
5905 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
5906 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5907 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5909 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5910 // 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
5911 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5913 // 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.
5914 assert!(BREAKDOWN_TIMEOUT>0);
5915 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5917 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5918 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5919 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5921 // 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.
5922 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5923 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5924 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5925 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5926 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5929 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5930 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5931 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5932 // is no longer affordable once it's freed.
5934 fn test_fail_holding_cell_htlc_upon_free() {
5935 let chanmon_cfgs = create_chanmon_cfgs(2);
5936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5938 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5939 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5940 let logger = test_utils::TestLogger::new();
5942 // First nodes[0] generates an update_fee, setting the channel's
5943 // pending_update_fee.
5944 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5945 check_added_monitors!(nodes[0], 1);
5947 let events = nodes[0].node.get_and_clear_pending_msg_events();
5948 assert_eq!(events.len(), 1);
5949 let (update_msg, commitment_signed) = match events[0] {
5950 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5951 (update_fee.as_ref(), commitment_signed)
5953 _ => panic!("Unexpected event"),
5956 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5958 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5959 let channel_reserve = chan_stat.channel_reserve_msat;
5960 let feerate = get_feerate!(nodes[0], chan.2);
5962 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5963 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5964 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5965 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5966 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(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
5968 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5969 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5970 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5971 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5973 // Flush the pending fee update.
5974 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5975 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5976 check_added_monitors!(nodes[1], 1);
5977 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5978 check_added_monitors!(nodes[0], 1);
5980 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5981 // HTLC, but now that the fee has been raised the payment will now fail, causing
5982 // us to surface its failure to the user.
5983 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5984 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5985 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5986 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 ({})", log_bytes!(our_payment_hash.0), chan_stat.channel_reserve_msat);
5987 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5989 // Check that the payment failed to be sent out.
5990 let events = nodes[0].node.get_and_clear_pending_events();
5991 assert_eq!(events.len(), 1);
5993 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5994 assert_eq!(our_payment_hash.clone(), *payment_hash);
5995 assert_eq!(*rejected_by_dest, false);
5996 assert_eq!(*error_code, None);
5997 assert_eq!(*error_data, None);
5999 _ => panic!("Unexpected event"),
6003 // Test that if multiple HTLCs are released from the holding cell and one is
6004 // valid but the other is no longer valid upon release, the valid HTLC can be
6005 // successfully completed while the other one fails as expected.
6007 fn test_free_and_fail_holding_cell_htlcs() {
6008 let chanmon_cfgs = create_chanmon_cfgs(2);
6009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6011 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6012 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6013 let logger = test_utils::TestLogger::new();
6015 // First nodes[0] generates an update_fee, setting the channel's
6016 // pending_update_fee.
6017 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6018 check_added_monitors!(nodes[0], 1);
6020 let events = nodes[0].node.get_and_clear_pending_msg_events();
6021 assert_eq!(events.len(), 1);
6022 let (update_msg, commitment_signed) = match events[0] {
6023 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6024 (update_fee.as_ref(), commitment_signed)
6026 _ => panic!("Unexpected event"),
6029 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6031 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6032 let channel_reserve = chan_stat.channel_reserve_msat;
6033 let feerate = get_feerate!(nodes[0], chan.2);
6035 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6036 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6038 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6039 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6040 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6041 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(), None, None, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6042 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(), None, None, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6044 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6045 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6046 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6047 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6048 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6049 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6050 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6052 // Flush the pending fee update.
6053 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6054 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6055 check_added_monitors!(nodes[1], 1);
6056 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6057 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6058 check_added_monitors!(nodes[0], 2);
6060 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6061 // but now that the fee has been raised the second payment will now fail, causing us
6062 // to surface its failure to the user. The first payment should succeed.
6063 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6064 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6065 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6066 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 ({})", log_bytes!(payment_hash_2.0), chan_stat.channel_reserve_msat);
6067 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6069 // Check that the second payment failed to be sent out.
6070 let events = nodes[0].node.get_and_clear_pending_events();
6071 assert_eq!(events.len(), 1);
6073 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6074 assert_eq!(payment_hash_2.clone(), *payment_hash);
6075 assert_eq!(*rejected_by_dest, false);
6076 assert_eq!(*error_code, None);
6077 assert_eq!(*error_data, None);
6079 _ => panic!("Unexpected event"),
6082 // Complete the first payment and the RAA from the fee update.
6083 let (payment_event, send_raa_event) = {
6084 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6085 assert_eq!(msgs.len(), 2);
6086 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6088 let raa = match send_raa_event {
6089 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6090 _ => panic!("Unexpected event"),
6092 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6093 check_added_monitors!(nodes[1], 1);
6094 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6095 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6096 let events = nodes[1].node.get_and_clear_pending_events();
6097 assert_eq!(events.len(), 1);
6099 Event::PendingHTLCsForwardable { .. } => {},
6100 _ => panic!("Unexpected event"),
6102 nodes[1].node.process_pending_htlc_forwards();
6103 let events = nodes[1].node.get_and_clear_pending_events();
6104 assert_eq!(events.len(), 1);
6106 Event::PaymentReceived { .. } => {},
6107 _ => panic!("Unexpected event"),
6109 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6110 check_added_monitors!(nodes[1], 1);
6111 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6112 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6113 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6114 let events = nodes[0].node.get_and_clear_pending_events();
6115 assert_eq!(events.len(), 1);
6117 Event::PaymentSent { ref payment_preimage } => {
6118 assert_eq!(*payment_preimage, payment_preimage_1);
6120 _ => panic!("Unexpected event"),
6124 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6125 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6126 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6129 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6130 let chanmon_cfgs = create_chanmon_cfgs(3);
6131 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6132 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6133 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6134 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6135 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6136 let logger = test_utils::TestLogger::new();
6138 // First nodes[1] generates an update_fee, setting the channel's
6139 // pending_update_fee.
6140 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6141 check_added_monitors!(nodes[1], 1);
6143 let events = nodes[1].node.get_and_clear_pending_msg_events();
6144 assert_eq!(events.len(), 1);
6145 let (update_msg, commitment_signed) = match events[0] {
6146 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6147 (update_fee.as_ref(), commitment_signed)
6149 _ => panic!("Unexpected event"),
6152 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6154 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6155 let channel_reserve = chan_stat.channel_reserve_msat;
6156 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6158 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6160 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6161 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6162 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6163 let payment_event = {
6164 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6165 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(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6166 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6167 check_added_monitors!(nodes[0], 1);
6169 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6170 assert_eq!(events.len(), 1);
6172 SendEvent::from_event(events.remove(0))
6174 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6175 check_added_monitors!(nodes[1], 0);
6176 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6177 expect_pending_htlcs_forwardable!(nodes[1]);
6179 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6180 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6182 // Flush the pending fee update.
6183 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6184 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6185 check_added_monitors!(nodes[2], 1);
6186 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6187 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6188 check_added_monitors!(nodes[1], 2);
6190 // A final RAA message is generated to finalize the fee update.
6191 let events = nodes[1].node.get_and_clear_pending_msg_events();
6192 assert_eq!(events.len(), 1);
6194 let raa_msg = match &events[0] {
6195 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6198 _ => panic!("Unexpected event"),
6201 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6202 check_added_monitors!(nodes[2], 1);
6203 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6205 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6206 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6207 assert_eq!(process_htlc_forwards_event.len(), 1);
6208 match &process_htlc_forwards_event[0] {
6209 &Event::PendingHTLCsForwardable { .. } => {},
6210 _ => panic!("Unexpected event"),
6213 // In response, we call ChannelManager's process_pending_htlc_forwards
6214 nodes[1].node.process_pending_htlc_forwards();
6215 check_added_monitors!(nodes[1], 1);
6217 // This causes the HTLC to be failed backwards.
6218 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6219 assert_eq!(fail_event.len(), 1);
6220 let (fail_msg, commitment_signed) = match &fail_event[0] {
6221 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6222 assert_eq!(updates.update_add_htlcs.len(), 0);
6223 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6224 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6225 assert_eq!(updates.update_fail_htlcs.len(), 1);
6226 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6228 _ => panic!("Unexpected event"),
6231 // Pass the failure messages back to nodes[0].
6232 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6233 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6235 // Complete the HTLC failure+removal process.
6236 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6237 check_added_monitors!(nodes[0], 1);
6238 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6239 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6240 check_added_monitors!(nodes[1], 2);
6241 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6242 assert_eq!(final_raa_event.len(), 1);
6243 let raa = match &final_raa_event[0] {
6244 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6245 _ => panic!("Unexpected event"),
6247 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6248 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6249 assert_eq!(fail_msg_event.len(), 1);
6250 match &fail_msg_event[0] {
6251 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6252 _ => panic!("Unexpected event"),
6254 let failure_event = nodes[0].node.get_and_clear_pending_events();
6255 assert_eq!(failure_event.len(), 1);
6256 match &failure_event[0] {
6257 &Event::PaymentFailed { rejected_by_dest, .. } => {
6258 assert!(!rejected_by_dest);
6260 _ => panic!("Unexpected event"),
6262 check_added_monitors!(nodes[0], 1);
6265 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6266 // 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.
6267 //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.
6270 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6271 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6272 let chanmon_cfgs = create_chanmon_cfgs(2);
6273 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6274 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6275 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6276 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6278 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6279 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6280 let logger = test_utils::TestLogger::new();
6281 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6282 route.paths[0][0].fee_msat = 100;
6284 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6285 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6286 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6287 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6291 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6292 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6293 let chanmon_cfgs = create_chanmon_cfgs(2);
6294 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6295 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6296 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6297 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6298 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6300 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6301 let logger = test_utils::TestLogger::new();
6302 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6303 route.paths[0][0].fee_msat = 0;
6304 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6305 assert_eq!(err, "Cannot send 0-msat HTLC"));
6307 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6308 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6312 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6313 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6314 let chanmon_cfgs = create_chanmon_cfgs(2);
6315 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6316 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6317 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6318 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6320 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6321 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6322 let logger = test_utils::TestLogger::new();
6323 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6324 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6325 check_added_monitors!(nodes[0], 1);
6326 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6327 updates.update_add_htlcs[0].amount_msat = 0;
6329 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6330 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6331 check_closed_broadcast!(nodes[1], true).unwrap();
6332 check_added_monitors!(nodes[1], 1);
6336 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6337 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6338 //It is enforced when constructing a route.
6339 let chanmon_cfgs = create_chanmon_cfgs(2);
6340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6342 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6343 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6344 let logger = test_utils::TestLogger::new();
6346 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6348 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6349 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(), None, None, &[], 100000000, 500000001, &logger).unwrap();
6350 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6351 assert_eq!(err, &"Channel CLTV overflowed?"));
6355 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6356 //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.
6357 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6358 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6359 let chanmon_cfgs = create_chanmon_cfgs(2);
6360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6363 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6364 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6366 let logger = test_utils::TestLogger::new();
6367 for i in 0..max_accepted_htlcs {
6368 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6369 let payment_event = {
6370 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6371 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6372 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6373 check_added_monitors!(nodes[0], 1);
6375 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6376 assert_eq!(events.len(), 1);
6377 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6378 assert_eq!(htlcs[0].htlc_id, i);
6382 SendEvent::from_event(events.remove(0))
6384 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6385 check_added_monitors!(nodes[1], 0);
6386 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6388 expect_pending_htlcs_forwardable!(nodes[1]);
6389 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6391 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6392 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6393 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6394 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6395 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6397 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6398 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6402 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6403 //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.
6404 let chanmon_cfgs = create_chanmon_cfgs(2);
6405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6407 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6408 let channel_value = 100000;
6409 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6410 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6412 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6414 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6415 // Manually create a route over our max in flight (which our router normally automatically
6417 let route = Route { paths: vec![vec![RouteHop {
6418 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6419 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6420 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6422 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6423 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)));
6425 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6426 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);
6428 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6431 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6433 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6434 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6435 let chanmon_cfgs = create_chanmon_cfgs(2);
6436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6438 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6439 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6440 let htlc_minimum_msat: u64;
6442 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6443 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6444 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6447 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6448 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6449 let logger = test_utils::TestLogger::new();
6450 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(), None, None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6451 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6452 check_added_monitors!(nodes[0], 1);
6453 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6454 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6455 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6456 assert!(nodes[1].node.list_channels().is_empty());
6457 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6458 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()));
6459 check_added_monitors!(nodes[1], 1);
6463 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6464 //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
6465 let chanmon_cfgs = create_chanmon_cfgs(2);
6466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6468 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6469 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6470 let logger = test_utils::TestLogger::new();
6472 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6473 let channel_reserve = chan_stat.channel_reserve_msat;
6474 let feerate = get_feerate!(nodes[0], chan.2);
6475 // The 2* and +1 are for the fee spike reserve.
6476 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6478 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6479 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6480 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6481 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(), None, None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6482 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6483 check_added_monitors!(nodes[0], 1);
6484 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6486 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6487 // at this time channel-initiatee receivers are not required to enforce that senders
6488 // respect the fee_spike_reserve.
6489 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6490 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6492 assert!(nodes[1].node.list_channels().is_empty());
6493 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6494 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6495 check_added_monitors!(nodes[1], 1);
6499 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6500 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6501 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6502 let chanmon_cfgs = create_chanmon_cfgs(2);
6503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6505 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6506 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6507 let logger = test_utils::TestLogger::new();
6509 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6510 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6512 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6513 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(), None, None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6515 let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6516 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6517 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6518 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6520 let mut msg = msgs::UpdateAddHTLC {
6524 payment_hash: our_payment_hash,
6525 cltv_expiry: htlc_cltv,
6526 onion_routing_packet: onion_packet.clone(),
6529 for i in 0..super::channel::OUR_MAX_HTLCS {
6530 msg.htlc_id = i as u64;
6531 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6533 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6534 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6536 assert!(nodes[1].node.list_channels().is_empty());
6537 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6538 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6539 check_added_monitors!(nodes[1], 1);
6543 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6544 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6545 let chanmon_cfgs = create_chanmon_cfgs(2);
6546 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6547 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6548 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6549 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6550 let logger = test_utils::TestLogger::new();
6552 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6553 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6554 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6555 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6556 check_added_monitors!(nodes[0], 1);
6557 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6558 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6559 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6561 assert!(nodes[1].node.list_channels().is_empty());
6562 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6563 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6564 check_added_monitors!(nodes[1], 1);
6568 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6569 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6570 let chanmon_cfgs = create_chanmon_cfgs(2);
6571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6573 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574 let logger = test_utils::TestLogger::new();
6576 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6577 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6578 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6579 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6580 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6581 check_added_monitors!(nodes[0], 1);
6582 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6583 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6584 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6586 assert!(nodes[1].node.list_channels().is_empty());
6587 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6588 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6589 check_added_monitors!(nodes[1], 1);
6593 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6594 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6595 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6596 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6597 let chanmon_cfgs = create_chanmon_cfgs(2);
6598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6600 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6601 let logger = test_utils::TestLogger::new();
6603 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6604 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6605 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6606 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6607 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6608 check_added_monitors!(nodes[0], 1);
6609 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6610 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6612 //Disconnect and Reconnect
6613 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6614 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6615 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6616 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6617 assert_eq!(reestablish_1.len(), 1);
6618 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6619 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6620 assert_eq!(reestablish_2.len(), 1);
6621 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6622 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6623 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6624 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6627 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6628 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6629 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6630 check_added_monitors!(nodes[1], 1);
6631 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6633 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6635 assert!(nodes[1].node.list_channels().is_empty());
6636 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6637 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6638 check_added_monitors!(nodes[1], 1);
6642 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6643 //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.
6645 let chanmon_cfgs = create_chanmon_cfgs(2);
6646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6648 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6649 let logger = test_utils::TestLogger::new();
6650 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6651 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6652 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6653 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6654 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6656 check_added_monitors!(nodes[0], 1);
6657 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6658 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6660 let update_msg = msgs::UpdateFulfillHTLC{
6663 payment_preimage: our_payment_preimage,
6666 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6668 assert!(nodes[0].node.list_channels().is_empty());
6669 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6670 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()));
6671 check_added_monitors!(nodes[0], 1);
6675 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6676 //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.
6678 let chanmon_cfgs = create_chanmon_cfgs(2);
6679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6681 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6682 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6683 let logger = test_utils::TestLogger::new();
6685 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6686 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6687 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6688 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6689 check_added_monitors!(nodes[0], 1);
6690 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6691 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6693 let update_msg = msgs::UpdateFailHTLC{
6696 reason: msgs::OnionErrorPacket { data: Vec::new()},
6699 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6701 assert!(nodes[0].node.list_channels().is_empty());
6702 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6703 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()));
6704 check_added_monitors!(nodes[0], 1);
6708 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6709 //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.
6711 let chanmon_cfgs = create_chanmon_cfgs(2);
6712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6715 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6716 let logger = test_utils::TestLogger::new();
6718 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6719 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6720 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6721 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6722 check_added_monitors!(nodes[0], 1);
6723 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6724 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6725 let update_msg = msgs::UpdateFailMalformedHTLC{
6728 sha256_of_onion: [1; 32],
6729 failure_code: 0x8000,
6732 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6734 assert!(nodes[0].node.list_channels().is_empty());
6735 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6736 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()));
6737 check_added_monitors!(nodes[0], 1);
6741 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6742 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6744 let chanmon_cfgs = create_chanmon_cfgs(2);
6745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6748 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6750 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6752 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6753 check_added_monitors!(nodes[1], 1);
6755 let events = nodes[1].node.get_and_clear_pending_msg_events();
6756 assert_eq!(events.len(), 1);
6757 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6759 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, .. } } => {
6760 assert!(update_add_htlcs.is_empty());
6761 assert_eq!(update_fulfill_htlcs.len(), 1);
6762 assert!(update_fail_htlcs.is_empty());
6763 assert!(update_fail_malformed_htlcs.is_empty());
6764 assert!(update_fee.is_none());
6765 update_fulfill_htlcs[0].clone()
6767 _ => panic!("Unexpected event"),
6771 update_fulfill_msg.htlc_id = 1;
6773 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6775 assert!(nodes[0].node.list_channels().is_empty());
6776 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6777 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6778 check_added_monitors!(nodes[0], 1);
6782 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6783 //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.
6785 let chanmon_cfgs = create_chanmon_cfgs(2);
6786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6789 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6791 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6793 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6794 check_added_monitors!(nodes[1], 1);
6796 let events = nodes[1].node.get_and_clear_pending_msg_events();
6797 assert_eq!(events.len(), 1);
6798 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6800 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, .. } } => {
6801 assert!(update_add_htlcs.is_empty());
6802 assert_eq!(update_fulfill_htlcs.len(), 1);
6803 assert!(update_fail_htlcs.is_empty());
6804 assert!(update_fail_malformed_htlcs.is_empty());
6805 assert!(update_fee.is_none());
6806 update_fulfill_htlcs[0].clone()
6808 _ => panic!("Unexpected event"),
6812 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6814 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6816 assert!(nodes[0].node.list_channels().is_empty());
6817 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6818 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6819 check_added_monitors!(nodes[0], 1);
6823 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6824 //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.
6826 let chanmon_cfgs = create_chanmon_cfgs(2);
6827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6829 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6830 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6831 let logger = test_utils::TestLogger::new();
6833 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6834 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6835 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(), None, None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6836 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6837 check_added_monitors!(nodes[0], 1);
6839 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6840 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6842 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6843 check_added_monitors!(nodes[1], 0);
6844 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6846 let events = nodes[1].node.get_and_clear_pending_msg_events();
6848 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6850 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, .. } } => {
6851 assert!(update_add_htlcs.is_empty());
6852 assert!(update_fulfill_htlcs.is_empty());
6853 assert!(update_fail_htlcs.is_empty());
6854 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6855 assert!(update_fee.is_none());
6856 update_fail_malformed_htlcs[0].clone()
6858 _ => panic!("Unexpected event"),
6861 update_msg.failure_code &= !0x8000;
6862 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6864 assert!(nodes[0].node.list_channels().is_empty());
6865 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6866 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6867 check_added_monitors!(nodes[0], 1);
6871 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6872 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6873 // * 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.
6875 let chanmon_cfgs = create_chanmon_cfgs(3);
6876 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6877 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6878 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6879 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6880 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6881 let logger = test_utils::TestLogger::new();
6883 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6886 let mut payment_event = {
6887 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6888 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(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6889 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6890 check_added_monitors!(nodes[0], 1);
6891 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6892 assert_eq!(events.len(), 1);
6893 SendEvent::from_event(events.remove(0))
6895 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6896 check_added_monitors!(nodes[1], 0);
6897 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6898 expect_pending_htlcs_forwardable!(nodes[1]);
6899 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6900 assert_eq!(events_2.len(), 1);
6901 check_added_monitors!(nodes[1], 1);
6902 payment_event = SendEvent::from_event(events_2.remove(0));
6903 assert_eq!(payment_event.msgs.len(), 1);
6906 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6907 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6908 check_added_monitors!(nodes[2], 0);
6909 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6911 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6912 assert_eq!(events_3.len(), 1);
6913 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6915 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 } } => {
6916 assert!(update_add_htlcs.is_empty());
6917 assert!(update_fulfill_htlcs.is_empty());
6918 assert!(update_fail_htlcs.is_empty());
6919 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6920 assert!(update_fee.is_none());
6921 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6923 _ => panic!("Unexpected event"),
6927 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6929 check_added_monitors!(nodes[1], 0);
6930 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6931 expect_pending_htlcs_forwardable!(nodes[1]);
6932 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6933 assert_eq!(events_4.len(), 1);
6935 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6937 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, .. } } => {
6938 assert!(update_add_htlcs.is_empty());
6939 assert!(update_fulfill_htlcs.is_empty());
6940 assert_eq!(update_fail_htlcs.len(), 1);
6941 assert!(update_fail_malformed_htlcs.is_empty());
6942 assert!(update_fee.is_none());
6944 _ => panic!("Unexpected event"),
6947 check_added_monitors!(nodes[1], 1);
6950 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6951 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6952 // 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
6953 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6955 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6956 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6957 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6958 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6959 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6960 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6962 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6964 // We route 2 dust-HTLCs between A and B
6965 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6966 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6967 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6969 // Cache one local commitment tx as previous
6970 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6972 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6973 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6974 check_added_monitors!(nodes[1], 0);
6975 expect_pending_htlcs_forwardable!(nodes[1]);
6976 check_added_monitors!(nodes[1], 1);
6978 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6979 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6980 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6981 check_added_monitors!(nodes[0], 1);
6983 // Cache one local commitment tx as lastest
6984 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6986 let events = nodes[0].node.get_and_clear_pending_msg_events();
6988 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6989 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6991 _ => panic!("Unexpected event"),
6994 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6995 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6997 _ => panic!("Unexpected event"),
7000 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7001 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7002 if announce_latest {
7003 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7005 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7008 check_closed_broadcast!(nodes[0], true);
7009 check_added_monitors!(nodes[0], 1);
7011 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7012 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7013 let events = nodes[0].node.get_and_clear_pending_events();
7014 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7015 assert_eq!(events.len(), 2);
7016 let mut first_failed = false;
7017 for event in events {
7019 Event::PaymentFailed { payment_hash, .. } => {
7020 if payment_hash == payment_hash_1 {
7021 assert!(!first_failed);
7022 first_failed = true;
7024 assert_eq!(payment_hash, payment_hash_2);
7027 _ => panic!("Unexpected event"),
7033 fn test_failure_delay_dust_htlc_local_commitment() {
7034 do_test_failure_delay_dust_htlc_local_commitment(true);
7035 do_test_failure_delay_dust_htlc_local_commitment(false);
7038 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7039 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7040 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7041 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7042 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7043 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7044 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7046 let chanmon_cfgs = create_chanmon_cfgs(3);
7047 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7048 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7049 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7050 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7052 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7054 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7055 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7057 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7058 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7060 // We revoked bs_commitment_tx
7062 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7063 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7066 let mut timeout_tx = Vec::new();
7068 // We fail dust-HTLC 1 by broadcast of local commitment tx
7069 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7070 check_closed_broadcast!(nodes[0], true);
7071 check_added_monitors!(nodes[0], 1);
7072 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7073 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7074 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7075 expect_payment_failed!(nodes[0], dust_hash, true);
7076 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7077 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7078 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7079 mine_transaction(&nodes[0], &timeout_tx[0]);
7080 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7081 expect_payment_failed!(nodes[0], non_dust_hash, true);
7083 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7084 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7085 check_closed_broadcast!(nodes[0], true);
7086 check_added_monitors!(nodes[0], 1);
7087 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7088 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7089 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7091 expect_payment_failed!(nodes[0], dust_hash, true);
7092 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7093 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7094 mine_transaction(&nodes[0], &timeout_tx[0]);
7095 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7096 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7097 expect_payment_failed!(nodes[0], non_dust_hash, true);
7099 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7101 let events = nodes[0].node.get_and_clear_pending_events();
7102 assert_eq!(events.len(), 2);
7105 Event::PaymentFailed { payment_hash, .. } => {
7106 if payment_hash == dust_hash { first = true; }
7107 else { first = false; }
7109 _ => panic!("Unexpected event"),
7112 Event::PaymentFailed { payment_hash, .. } => {
7113 if first { assert_eq!(payment_hash, non_dust_hash); }
7114 else { assert_eq!(payment_hash, dust_hash); }
7116 _ => panic!("Unexpected event"),
7123 fn test_sweep_outbound_htlc_failure_update() {
7124 do_test_sweep_outbound_htlc_failure_update(false, true);
7125 do_test_sweep_outbound_htlc_failure_update(false, false);
7126 do_test_sweep_outbound_htlc_failure_update(true, false);
7130 fn test_upfront_shutdown_script() {
7131 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7132 // enforce it at shutdown message
7134 let mut config = UserConfig::default();
7135 config.channel_options.announced_channel = true;
7136 config.peer_channel_config_limits.force_announced_channel_preference = false;
7137 config.channel_options.commit_upfront_shutdown_pubkey = false;
7138 let user_cfgs = [None, Some(config), None];
7139 let chanmon_cfgs = create_chanmon_cfgs(3);
7140 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7141 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7142 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7144 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7145 let flags = InitFeatures::known();
7146 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7147 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7148 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7149 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7150 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7151 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7152 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()));
7153 check_added_monitors!(nodes[2], 1);
7155 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7156 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7157 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7158 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7159 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7160 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7161 let events = nodes[2].node.get_and_clear_pending_msg_events();
7162 assert_eq!(events.len(), 1);
7164 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7165 _ => panic!("Unexpected event"),
7168 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7169 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7170 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7171 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7172 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7173 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7174 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7175 let events = nodes[1].node.get_and_clear_pending_msg_events();
7176 assert_eq!(events.len(), 1);
7178 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7179 _ => panic!("Unexpected event"),
7182 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7183 // channel smoothly, opt-out is from channel initiator here
7184 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7185 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7186 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7187 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7188 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7189 let events = nodes[0].node.get_and_clear_pending_msg_events();
7190 assert_eq!(events.len(), 1);
7192 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7193 _ => panic!("Unexpected event"),
7196 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7197 //// channel smoothly
7198 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7199 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7200 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7201 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7202 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7203 let events = nodes[0].node.get_and_clear_pending_msg_events();
7204 assert_eq!(events.len(), 2);
7206 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7207 _ => panic!("Unexpected event"),
7210 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7211 _ => panic!("Unexpected event"),
7216 fn test_upfront_shutdown_script_unsupport_segwit() {
7217 // We test that channel is closed early
7218 // if a segwit program is passed as upfront shutdown script,
7219 // but the peer does not support segwit.
7220 let chanmon_cfgs = create_chanmon_cfgs(2);
7221 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7222 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7223 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7225 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7227 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7228 open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7229 .push_slice(&[0, 0])
7232 let features = InitFeatures::known().clear_shutdown_anysegwit();
7233 nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7235 let events = nodes[0].node.get_and_clear_pending_msg_events();
7236 assert_eq!(events.len(), 1);
7238 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7239 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7240 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));
7242 _ => panic!("Unexpected event"),
7247 fn test_shutdown_script_any_segwit_allowed() {
7248 let mut config = UserConfig::default();
7249 config.channel_options.announced_channel = true;
7250 config.peer_channel_config_limits.force_announced_channel_preference = false;
7251 config.channel_options.commit_upfront_shutdown_pubkey = false;
7252 let user_cfgs = [None, Some(config), None];
7253 let chanmon_cfgs = create_chanmon_cfgs(3);
7254 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7255 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7256 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7258 //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7259 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7260 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7261 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7262 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7263 .push_slice(&[0, 0])
7265 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7266 let events = nodes[0].node.get_and_clear_pending_msg_events();
7267 assert_eq!(events.len(), 2);
7269 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7270 _ => panic!("Unexpected event"),
7273 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7274 _ => panic!("Unexpected event"),
7279 fn test_shutdown_script_any_segwit_not_allowed() {
7280 let mut config = UserConfig::default();
7281 config.channel_options.announced_channel = true;
7282 config.peer_channel_config_limits.force_announced_channel_preference = false;
7283 config.channel_options.commit_upfront_shutdown_pubkey = false;
7284 let user_cfgs = [None, Some(config), None];
7285 let chanmon_cfgs = create_chanmon_cfgs(3);
7286 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7287 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7288 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7290 //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7291 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7292 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7293 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7294 // Make an any segwit version script
7295 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7296 .push_slice(&[0, 0])
7298 let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7299 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7300 let events = nodes[0].node.get_and_clear_pending_msg_events();
7301 assert_eq!(events.len(), 2);
7303 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7304 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7305 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7307 _ => panic!("Unexpected event"),
7309 check_added_monitors!(nodes[0], 1);
7313 fn test_shutdown_script_segwit_but_not_anysegwit() {
7314 let mut config = UserConfig::default();
7315 config.channel_options.announced_channel = true;
7316 config.peer_channel_config_limits.force_announced_channel_preference = false;
7317 config.channel_options.commit_upfront_shutdown_pubkey = false;
7318 let user_cfgs = [None, Some(config), None];
7319 let chanmon_cfgs = create_chanmon_cfgs(3);
7320 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7321 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7322 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7324 //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7325 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7326 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7327 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7328 // Make a segwit script that is not a valid as any segwit
7329 node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7330 .push_slice(&[0, 0])
7332 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7333 let events = nodes[0].node.get_and_clear_pending_msg_events();
7334 assert_eq!(events.len(), 2);
7336 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7337 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7338 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7340 _ => panic!("Unexpected event"),
7342 check_added_monitors!(nodes[0], 1);
7346 fn test_user_configurable_csv_delay() {
7347 // We test our channel constructors yield errors when we pass them absurd csv delay
7349 let mut low_our_to_self_config = UserConfig::default();
7350 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7351 let mut high_their_to_self_config = UserConfig::default();
7352 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7353 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7354 let chanmon_cfgs = create_chanmon_cfgs(2);
7355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7357 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7359 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7360 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) {
7362 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())); },
7363 _ => panic!("Unexpected event"),
7365 } else { assert!(false) }
7367 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7368 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7369 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7370 open_channel.to_self_delay = 200;
7371 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) {
7373 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())); },
7374 _ => panic!("Unexpected event"),
7376 } else { assert!(false); }
7378 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7379 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7380 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()));
7381 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7382 accept_channel.to_self_delay = 200;
7383 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7384 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7386 &ErrorAction::SendErrorMessage { ref msg } => {
7387 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()));
7389 _ => { assert!(false); }
7391 } else { assert!(false); }
7393 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7394 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7395 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7396 open_channel.to_self_delay = 200;
7397 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) {
7399 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())); },
7400 _ => panic!("Unexpected event"),
7402 } else { assert!(false); }
7406 fn test_data_loss_protect() {
7407 // We want to be sure that :
7408 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7409 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7410 // * we close channel in case of detecting other being fallen behind
7411 // * we are able to claim our own outputs thanks to to_remote being static
7412 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7418 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7419 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7420 // during signing due to revoked tx
7421 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7422 let keys_manager = &chanmon_cfgs[0].keys_manager;
7425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7427 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7429 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7431 // Cache node A state before any channel update
7432 let previous_node_state = nodes[0].node.encode();
7433 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7434 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7436 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7437 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7439 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7440 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7442 // Restore node A from previous state
7443 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7444 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7445 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7446 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7447 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7448 persister = test_utils::TestPersister::new();
7449 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7451 let mut channel_monitors = HashMap::new();
7452 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7453 <(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 {
7454 keys_manager: keys_manager,
7455 fee_estimator: &fee_estimator,
7456 chain_monitor: &monitor,
7458 tx_broadcaster: &tx_broadcaster,
7459 default_config: UserConfig::default(),
7463 nodes[0].node = &node_state_0;
7464 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7465 nodes[0].chain_monitor = &monitor;
7466 nodes[0].chain_source = &chain_source;
7468 check_added_monitors!(nodes[0], 1);
7470 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7471 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7473 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7475 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7476 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7477 check_added_monitors!(nodes[0], 1);
7480 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7481 assert_eq!(node_txn.len(), 0);
7484 let mut reestablish_1 = Vec::with_capacity(1);
7485 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7486 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7487 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7488 reestablish_1.push(msg.clone());
7489 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7490 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7492 &ErrorAction::SendErrorMessage { ref msg } => {
7493 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");
7495 _ => panic!("Unexpected event!"),
7498 panic!("Unexpected event")
7502 // Check we close channel detecting A is fallen-behind
7503 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7504 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7505 check_added_monitors!(nodes[1], 1);
7508 // Check A is able to claim to_remote output
7509 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7510 assert_eq!(node_txn.len(), 1);
7511 check_spends!(node_txn[0], chan.3);
7512 assert_eq!(node_txn[0].output.len(), 2);
7513 mine_transaction(&nodes[0], &node_txn[0]);
7514 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7515 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7516 assert_eq!(spend_txn.len(), 1);
7517 check_spends!(spend_txn[0], node_txn[0]);
7521 fn test_check_htlc_underpaying() {
7522 // Send payment through A -> B but A is maliciously
7523 // sending a probe payment (i.e less than expected value0
7524 // to B, B should refuse payment.
7526 let chanmon_cfgs = create_chanmon_cfgs(2);
7527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7529 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7531 // Create some initial channels
7532 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7534 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7536 // Node 3 is expecting payment of 100_000 but receive 10_000,
7537 // fail htlc like we didn't know the preimage.
7538 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7539 nodes[1].node.process_pending_htlc_forwards();
7541 let events = nodes[1].node.get_and_clear_pending_msg_events();
7542 assert_eq!(events.len(), 1);
7543 let (update_fail_htlc, commitment_signed) = match events[0] {
7544 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 } } => {
7545 assert!(update_add_htlcs.is_empty());
7546 assert!(update_fulfill_htlcs.is_empty());
7547 assert_eq!(update_fail_htlcs.len(), 1);
7548 assert!(update_fail_malformed_htlcs.is_empty());
7549 assert!(update_fee.is_none());
7550 (update_fail_htlcs[0].clone(), commitment_signed)
7552 _ => panic!("Unexpected event"),
7554 check_added_monitors!(nodes[1], 1);
7556 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7557 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7559 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7560 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7561 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7562 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7563 nodes[1].node.get_and_clear_pending_events();
7567 fn test_announce_disable_channels() {
7568 // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7569 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7571 let chanmon_cfgs = create_chanmon_cfgs(2);
7572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7576 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7577 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7578 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7584 nodes[0].node.timer_tick_occurred(); // dirty -> stagged
7585 nodes[0].node.timer_tick_occurred(); // staged -> fresh
7586 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7587 assert_eq!(msg_events.len(), 3);
7588 for e in msg_events {
7590 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7591 let short_id = msg.contents.short_channel_id;
7592 // Check generated channel_update match list in PendingChannelUpdate
7593 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7594 panic!("Generated ChannelUpdate for wrong chan!");
7597 _ => panic!("Unexpected event"),
7601 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7602 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7603 assert_eq!(reestablish_1.len(), 3);
7604 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7605 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7606 assert_eq!(reestablish_2.len(), 3);
7608 // Reestablish chan_1
7609 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7610 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7611 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7612 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7613 // Reestablish chan_2
7614 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7615 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7616 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7617 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7618 // Reestablish chan_3
7619 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7620 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7621 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7622 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7624 nodes[0].node.timer_tick_occurred();
7625 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7629 fn test_bump_penalty_txn_on_revoked_commitment() {
7630 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7631 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7633 let chanmon_cfgs = create_chanmon_cfgs(2);
7634 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7635 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7636 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7638 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7639 let logger = test_utils::TestLogger::new();
7641 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7642 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7643 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(), None, None, &Vec::new(), 3000000, 30, &logger).unwrap();
7644 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7646 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7647 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7648 assert_eq!(revoked_txn[0].output.len(), 4);
7649 assert_eq!(revoked_txn[0].input.len(), 1);
7650 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7651 let revoked_txid = revoked_txn[0].txid();
7653 let mut penalty_sum = 0;
7654 for outp in revoked_txn[0].output.iter() {
7655 if outp.script_pubkey.is_v0_p2wsh() {
7656 penalty_sum += outp.value;
7660 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7661 let header_114 = connect_blocks(&nodes[1], 14);
7663 // Actually revoke tx by claiming a HTLC
7664 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7665 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7666 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] });
7667 check_added_monitors!(nodes[1], 1);
7669 // One or more justice tx should have been broadcast, check it
7673 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7674 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7675 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7676 assert_eq!(node_txn[0].output.len(), 1);
7677 check_spends!(node_txn[0], revoked_txn[0]);
7678 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7679 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7680 penalty_1 = node_txn[0].txid();
7684 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7685 connect_blocks(&nodes[1], 15);
7686 let mut penalty_2 = penalty_1;
7687 let mut feerate_2 = 0;
7689 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7690 assert_eq!(node_txn.len(), 1);
7691 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7692 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7693 assert_eq!(node_txn[0].output.len(), 1);
7694 check_spends!(node_txn[0], revoked_txn[0]);
7695 penalty_2 = node_txn[0].txid();
7696 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7697 assert_ne!(penalty_2, penalty_1);
7698 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7699 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7700 // Verify 25% bump heuristic
7701 assert!(feerate_2 * 100 >= feerate_1 * 125);
7705 assert_ne!(feerate_2, 0);
7707 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7708 connect_blocks(&nodes[1], 1);
7710 let mut feerate_3 = 0;
7712 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7713 assert_eq!(node_txn.len(), 1);
7714 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7715 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7716 assert_eq!(node_txn[0].output.len(), 1);
7717 check_spends!(node_txn[0], revoked_txn[0]);
7718 penalty_3 = node_txn[0].txid();
7719 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7720 assert_ne!(penalty_3, penalty_2);
7721 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7722 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7723 // Verify 25% bump heuristic
7724 assert!(feerate_3 * 100 >= feerate_2 * 125);
7728 assert_ne!(feerate_3, 0);
7730 nodes[1].node.get_and_clear_pending_events();
7731 nodes[1].node.get_and_clear_pending_msg_events();
7735 fn test_bump_penalty_txn_on_revoked_htlcs() {
7736 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7737 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7739 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7740 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7741 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7742 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7743 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7745 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7746 // Lock HTLC in both directions
7747 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7748 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7750 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7751 assert_eq!(revoked_local_txn[0].input.len(), 1);
7752 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7754 // Revoke local commitment tx
7755 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7757 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7758 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7759 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] });
7760 check_closed_broadcast!(nodes[1], true);
7761 check_added_monitors!(nodes[1], 1);
7763 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7764 assert_eq!(revoked_htlc_txn.len(), 4);
7765 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7766 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7767 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7768 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7769 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7770 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7771 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7772 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7773 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7774 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7775 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7776 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7777 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7778 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7781 // Broadcast set of revoked txn on A
7782 let hash_128 = connect_blocks(&nodes[0], 40);
7783 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7784 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] });
7785 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7786 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] });
7787 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7792 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7793 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7794 // Verify claim tx are spending revoked HTLC txn
7796 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7797 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7798 // which are included in the same block (they are broadcasted because we scan the
7799 // transactions linearly and generate claims as we go, they likely should be removed in the
7801 assert_eq!(node_txn[0].input.len(), 1);
7802 check_spends!(node_txn[0], revoked_local_txn[0]);
7803 assert_eq!(node_txn[1].input.len(), 1);
7804 check_spends!(node_txn[1], revoked_local_txn[0]);
7805 assert_eq!(node_txn[2].input.len(), 1);
7806 check_spends!(node_txn[2], revoked_local_txn[0]);
7808 // Each of the three justice transactions claim a separate (single) output of the three
7809 // available, which we check here:
7810 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7811 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7812 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7814 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7815 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7817 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7818 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7819 // a remote commitment tx has already been confirmed).
7820 check_spends!(node_txn[3], chan.3);
7822 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7823 // output, checked above).
7824 assert_eq!(node_txn[4].input.len(), 2);
7825 assert_eq!(node_txn[4].output.len(), 1);
7826 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7828 first = node_txn[4].txid();
7829 // Store both feerates for later comparison
7830 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7831 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7832 penalty_txn = vec![node_txn[2].clone()];
7836 // Connect one more block to see if bumped penalty are issued for HTLC txn
7837 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7838 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
7839 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7840 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() });
7842 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7843 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7845 check_spends!(node_txn[0], revoked_local_txn[0]);
7846 check_spends!(node_txn[1], revoked_local_txn[0]);
7847 // Note that these are both bogus - they spend outputs already claimed in block 129:
7848 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7849 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7851 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7852 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7858 // Few more blocks to confirm penalty txn
7859 connect_blocks(&nodes[0], 4);
7860 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7861 let header_144 = connect_blocks(&nodes[0], 9);
7863 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7864 assert_eq!(node_txn.len(), 1);
7866 assert_eq!(node_txn[0].input.len(), 2);
7867 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7868 // Verify bumped tx is different and 25% bump heuristic
7869 assert_ne!(first, node_txn[0].txid());
7870 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7871 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7872 assert!(feerate_2 * 100 > feerate_1 * 125);
7873 let txn = vec![node_txn[0].clone()];
7877 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7878 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7879 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn });
7880 connect_blocks(&nodes[0], 20);
7882 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7883 // We verify than no new transaction has been broadcast because previously
7884 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7885 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7886 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7887 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7888 // up bumped justice generation.
7889 assert_eq!(node_txn.len(), 0);
7892 check_closed_broadcast!(nodes[0], true);
7893 check_added_monitors!(nodes[0], 1);
7897 fn test_bump_penalty_txn_on_remote_commitment() {
7898 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7899 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7902 // Provide preimage for one
7903 // Check aggregation
7905 let chanmon_cfgs = create_chanmon_cfgs(2);
7906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7908 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7910 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7911 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7912 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7914 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7915 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7916 assert_eq!(remote_txn[0].output.len(), 4);
7917 assert_eq!(remote_txn[0].input.len(), 1);
7918 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7920 // Claim a HTLC without revocation (provide B monitor with preimage)
7921 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7922 mine_transaction(&nodes[1], &remote_txn[0]);
7923 check_added_monitors!(nodes[1], 2);
7925 // One or more claim tx should have been broadcast, check it
7928 let feerate_timeout;
7929 let feerate_preimage;
7931 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7932 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7933 assert_eq!(node_txn[0].input.len(), 1);
7934 assert_eq!(node_txn[1].input.len(), 1);
7935 check_spends!(node_txn[0], remote_txn[0]);
7936 check_spends!(node_txn[1], remote_txn[0]);
7937 check_spends!(node_txn[2], chan.3);
7938 check_spends!(node_txn[3], node_txn[2]);
7939 check_spends!(node_txn[4], node_txn[2]);
7940 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7941 timeout = node_txn[0].txid();
7942 let index = node_txn[0].input[0].previous_output.vout;
7943 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7944 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7946 preimage = node_txn[1].txid();
7947 let index = node_txn[1].input[0].previous_output.vout;
7948 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7949 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7951 timeout = node_txn[1].txid();
7952 let index = node_txn[1].input[0].previous_output.vout;
7953 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7954 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7956 preimage = node_txn[0].txid();
7957 let index = node_txn[0].input[0].previous_output.vout;
7958 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7959 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7963 assert_ne!(feerate_timeout, 0);
7964 assert_ne!(feerate_preimage, 0);
7966 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7967 connect_blocks(&nodes[1], 15);
7969 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7970 assert_eq!(node_txn.len(), 2);
7971 assert_eq!(node_txn[0].input.len(), 1);
7972 assert_eq!(node_txn[1].input.len(), 1);
7973 check_spends!(node_txn[0], remote_txn[0]);
7974 check_spends!(node_txn[1], remote_txn[0]);
7975 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7976 let index = node_txn[0].input[0].previous_output.vout;
7977 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7978 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7979 assert!(new_feerate * 100 > feerate_timeout * 125);
7980 assert_ne!(timeout, node_txn[0].txid());
7982 let index = node_txn[1].input[0].previous_output.vout;
7983 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7984 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7985 assert!(new_feerate * 100 > feerate_preimage * 125);
7986 assert_ne!(preimage, node_txn[1].txid());
7988 let index = node_txn[1].input[0].previous_output.vout;
7989 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7990 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7991 assert!(new_feerate * 100 > feerate_timeout * 125);
7992 assert_ne!(timeout, node_txn[1].txid());
7994 let index = node_txn[0].input[0].previous_output.vout;
7995 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7996 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7997 assert!(new_feerate * 100 > feerate_preimage * 125);
7998 assert_ne!(preimage, node_txn[0].txid());
8003 nodes[1].node.get_and_clear_pending_events();
8004 nodes[1].node.get_and_clear_pending_msg_events();
8008 fn test_counterparty_raa_skip_no_crash() {
8009 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8010 // commitment transaction, we would have happily carried on and provided them the next
8011 // commitment transaction based on one RAA forward. This would probably eventually have led to
8012 // channel closure, but it would not have resulted in funds loss. Still, our
8013 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8014 // check simply that the channel is closed in response to such an RAA, but don't check whether
8015 // we decide to punish our counterparty for revoking their funds (as we don't currently
8017 let chanmon_cfgs = create_chanmon_cfgs(2);
8018 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8019 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8020 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8021 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8023 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8024 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8025 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8026 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8027 // Must revoke without gaps
8028 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8029 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8030 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8032 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8033 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8034 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8035 check_added_monitors!(nodes[1], 1);
8039 fn test_bump_txn_sanitize_tracking_maps() {
8040 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8041 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8043 let chanmon_cfgs = create_chanmon_cfgs(2);
8044 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8045 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8046 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8048 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8049 // Lock HTLC in both directions
8050 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8051 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8053 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8054 assert_eq!(revoked_local_txn[0].input.len(), 1);
8055 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8057 // Revoke local commitment tx
8058 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8060 // Broadcast set of revoked txn on A
8061 connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8062 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8063 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8065 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8066 check_closed_broadcast!(nodes[0], true);
8067 check_added_monitors!(nodes[0], 1);
8069 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8070 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8071 check_spends!(node_txn[0], revoked_local_txn[0]);
8072 check_spends!(node_txn[1], revoked_local_txn[0]);
8073 check_spends!(node_txn[2], revoked_local_txn[0]);
8074 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8078 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8079 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn });
8080 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8082 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8083 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8084 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8085 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8091 fn test_override_channel_config() {
8092 let chanmon_cfgs = create_chanmon_cfgs(2);
8093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8097 // Node0 initiates a channel to node1 using the override config.
8098 let mut override_config = UserConfig::default();
8099 override_config.own_channel_config.our_to_self_delay = 200;
8101 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8103 // Assert the channel created by node0 is using the override config.
8104 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8105 assert_eq!(res.channel_flags, 0);
8106 assert_eq!(res.to_self_delay, 200);
8110 fn test_override_0msat_htlc_minimum() {
8111 let mut zero_config = UserConfig::default();
8112 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8113 let chanmon_cfgs = create_chanmon_cfgs(2);
8114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8116 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8118 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8119 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8120 assert_eq!(res.htlc_minimum_msat, 1);
8122 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8123 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8124 assert_eq!(res.htlc_minimum_msat, 1);
8128 fn test_simple_payment_secret() {
8129 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8130 // features, however.
8131 let chanmon_cfgs = create_chanmon_cfgs(3);
8132 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8133 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8134 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8136 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8137 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8138 let logger = test_utils::TestLogger::new();
8140 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8141 let payment_secret = PaymentSecret([0xdb; 32]);
8142 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8143 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8144 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8145 // Claiming with all the correct values but the wrong secret should result in nothing...
8146 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8147 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8148 // ...but with the right secret we should be able to claim all the way back
8149 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8153 fn test_simple_mpp() {
8154 // Simple test of sending a multi-path payment.
8155 let chanmon_cfgs = create_chanmon_cfgs(4);
8156 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8157 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8158 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8160 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8161 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8162 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8163 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8164 let logger = test_utils::TestLogger::new();
8166 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8167 let payment_secret = PaymentSecret([0xdb; 32]);
8168 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8169 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(), None, None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8170 let path = route.paths[0].clone();
8171 route.paths.push(path);
8172 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8173 route.paths[0][0].short_channel_id = chan_1_id;
8174 route.paths[0][1].short_channel_id = chan_3_id;
8175 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8176 route.paths[1][0].short_channel_id = chan_2_id;
8177 route.paths[1][1].short_channel_id = chan_4_id;
8178 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8179 // Claiming with all the correct values but the wrong secret should result in nothing...
8180 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8181 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8182 // ...but with the right secret we should be able to claim all the way back
8183 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8187 fn test_update_err_monitor_lockdown() {
8188 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8189 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8190 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8192 // This scenario may happen in a watchtower setup, where watchtower process a block height
8193 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8194 // commitment at same time.
8196 let chanmon_cfgs = create_chanmon_cfgs(2);
8197 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8198 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8199 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8201 // Create some initial channel
8202 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8203 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8205 // Rebalance the network to generate htlc in the two directions
8206 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8208 // Route a HTLC from node 0 to node 1 (but don't settle)
8209 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8211 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8212 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8213 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8214 let persister = test_utils::TestPersister::new();
8216 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8217 let monitor = monitors.get(&outpoint).unwrap();
8218 let mut w = test_utils::TestVecWriter(Vec::new());
8219 monitor.write(&mut w).unwrap();
8220 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8221 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8222 assert!(new_monitor == *monitor);
8223 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);
8224 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8227 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8228 watchtower.chain_monitor.block_connected(&header, &[], 200);
8230 // Try to update ChannelMonitor
8231 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8232 check_added_monitors!(nodes[1], 1);
8233 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8234 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8235 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8236 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8237 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8238 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8239 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8240 } else { assert!(false); }
8241 } else { assert!(false); };
8242 // Our local monitor is in-sync and hasn't processed yet timeout
8243 check_added_monitors!(nodes[0], 1);
8244 let events = nodes[0].node.get_and_clear_pending_events();
8245 assert_eq!(events.len(), 1);
8249 fn test_concurrent_monitor_claim() {
8250 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8251 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8252 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8253 // state N+1 confirms. Alice claims output from state N+1.
8255 let chanmon_cfgs = create_chanmon_cfgs(2);
8256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8258 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8260 // Create some initial channel
8261 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8262 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8264 // Rebalance the network to generate htlc in the two directions
8265 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8267 // Route a HTLC from node 0 to node 1 (but don't settle)
8268 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8270 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8271 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8272 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8273 let persister = test_utils::TestPersister::new();
8274 let watchtower_alice = {
8275 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8276 let monitor = monitors.get(&outpoint).unwrap();
8277 let mut w = test_utils::TestVecWriter(Vec::new());
8278 monitor.write(&mut w).unwrap();
8279 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8280 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8281 assert!(new_monitor == *monitor);
8282 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);
8283 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8286 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8287 watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8289 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8291 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8292 assert_eq!(txn.len(), 2);
8296 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8297 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8298 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8299 let persister = test_utils::TestPersister::new();
8300 let watchtower_bob = {
8301 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8302 let monitor = monitors.get(&outpoint).unwrap();
8303 let mut w = test_utils::TestVecWriter(Vec::new());
8304 monitor.write(&mut w).unwrap();
8305 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8306 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8307 assert!(new_monitor == *monitor);
8308 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);
8309 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8312 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8313 watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8315 // Route another payment to generate another update with still previous HTLC pending
8316 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8318 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8319 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(), None, None, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8320 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8322 check_added_monitors!(nodes[1], 1);
8324 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8325 assert_eq!(updates.update_add_htlcs.len(), 1);
8326 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8327 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8328 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8329 // Watchtower Alice should already have seen the block and reject the update
8330 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8331 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8332 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8333 } else { assert!(false); }
8334 } else { assert!(false); };
8335 // Our local monitor is in-sync and hasn't processed yet timeout
8336 check_added_monitors!(nodes[0], 1);
8338 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8339 watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8341 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8344 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8345 assert_eq!(txn.len(), 2);
8346 bob_state_y = txn[0].clone();
8350 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8351 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8353 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8354 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8355 // the onchain detection of the HTLC output
8356 assert_eq!(htlc_txn.len(), 2);
8357 check_spends!(htlc_txn[0], bob_state_y);
8358 check_spends!(htlc_txn[1], bob_state_y);
8363 fn test_pre_lockin_no_chan_closed_update() {
8364 // Test that if a peer closes a channel in response to a funding_created message we don't
8365 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8368 // Doing so would imply a channel monitor update before the initial channel monitor
8369 // registration, violating our API guarantees.
8371 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8372 // then opening a second channel with the same funding output as the first (which is not
8373 // rejected because the first channel does not exist in the ChannelManager) and closing it
8374 // before receiving funding_signed.
8375 let chanmon_cfgs = create_chanmon_cfgs(2);
8376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8378 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8380 // Create an initial channel
8381 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8382 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8383 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8384 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8385 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8387 // Move the first channel through the funding flow...
8388 let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], 100000, 42);
8390 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8391 check_added_monitors!(nodes[0], 0);
8393 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8394 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8395 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8396 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8400 fn test_htlc_no_detection() {
8401 // This test is a mutation to underscore the detection logic bug we had
8402 // before #653. HTLC value routed is above the remaining balance, thus
8403 // inverting HTLC and `to_remote` output. HTLC will come second and
8404 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8405 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8406 // outputs order detection for correct spending children filtring.
8408 let chanmon_cfgs = create_chanmon_cfgs(2);
8409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8411 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8413 // Create some initial channels
8414 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8416 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8417 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8418 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8419 assert_eq!(local_txn[0].input.len(), 1);
8420 assert_eq!(local_txn[0].output.len(), 3);
8421 check_spends!(local_txn[0], chan_1.3);
8423 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8424 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8425 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] });
8426 // We deliberately connect the local tx twice as this should provoke a failure calling
8427 // this test before #653 fix.
8428 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);
8429 check_closed_broadcast!(nodes[0], true);
8430 check_added_monitors!(nodes[0], 1);
8432 let htlc_timeout = {
8433 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8434 assert_eq!(node_txn[0].input.len(), 1);
8435 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8436 check_spends!(node_txn[0], local_txn[0]);
8440 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8441 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] });
8442 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8443 expect_payment_failed!(nodes[0], our_payment_hash, true);
8446 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8447 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8448 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8449 // Carol, Alice would be the upstream node, and Carol the downstream.)
8451 // Steps of the test:
8452 // 1) Alice sends a HTLC to Carol through Bob.
8453 // 2) Carol doesn't settle the HTLC.
8454 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8455 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8456 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8457 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8458 // 5) Carol release the preimage to Bob off-chain.
8459 // 6) Bob claims the offered output on the broadcasted commitment.
8460 let chanmon_cfgs = create_chanmon_cfgs(3);
8461 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8462 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8463 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8465 // Create some initial channels
8466 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8467 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8469 // Steps (1) and (2):
8470 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8471 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8473 // Check that Alice's commitment transaction now contains an output for this HTLC.
8474 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8475 check_spends!(alice_txn[0], chan_ab.3);
8476 assert_eq!(alice_txn[0].output.len(), 2);
8477 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8478 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8479 assert_eq!(alice_txn.len(), 2);
8481 // Steps (3) and (4):
8482 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8483 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8484 let mut force_closing_node = 0; // Alice force-closes
8485 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8486 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8487 check_closed_broadcast!(nodes[force_closing_node], true);
8488 check_added_monitors!(nodes[force_closing_node], 1);
8489 if go_onchain_before_fulfill {
8490 let txn_to_broadcast = match broadcast_alice {
8491 true => alice_txn.clone(),
8492 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8494 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8495 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8496 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8497 if broadcast_alice {
8498 check_closed_broadcast!(nodes[1], true);
8499 check_added_monitors!(nodes[1], 1);
8501 assert_eq!(bob_txn.len(), 1);
8502 check_spends!(bob_txn[0], chan_ab.3);
8506 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8507 // process of removing the HTLC from their commitment transactions.
8508 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8509 check_added_monitors!(nodes[2], 1);
8510 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8511 assert!(carol_updates.update_add_htlcs.is_empty());
8512 assert!(carol_updates.update_fail_htlcs.is_empty());
8513 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8514 assert!(carol_updates.update_fee.is_none());
8515 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8517 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8518 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8519 if !go_onchain_before_fulfill && broadcast_alice {
8520 let events = nodes[1].node.get_and_clear_pending_msg_events();
8521 assert_eq!(events.len(), 1);
8523 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8524 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8526 _ => panic!("Unexpected event"),
8529 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8530 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8531 // Carol<->Bob's updated commitment transaction info.
8532 check_added_monitors!(nodes[1], 2);
8534 let events = nodes[1].node.get_and_clear_pending_msg_events();
8535 assert_eq!(events.len(), 2);
8536 let bob_revocation = match events[0] {
8537 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8538 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8541 _ => panic!("Unexpected event"),
8543 let bob_updates = match events[1] {
8544 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8545 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8548 _ => panic!("Unexpected event"),
8551 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8552 check_added_monitors!(nodes[2], 1);
8553 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8554 check_added_monitors!(nodes[2], 1);
8556 let events = nodes[2].node.get_and_clear_pending_msg_events();
8557 assert_eq!(events.len(), 1);
8558 let carol_revocation = match events[0] {
8559 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8560 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8563 _ => panic!("Unexpected event"),
8565 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8566 check_added_monitors!(nodes[1], 1);
8568 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8569 // here's where we put said channel's commitment tx on-chain.
8570 let mut txn_to_broadcast = alice_txn.clone();
8571 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8572 if !go_onchain_before_fulfill {
8573 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8574 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]});
8575 // If Bob was the one to force-close, he will have already passed these checks earlier.
8576 if broadcast_alice {
8577 check_closed_broadcast!(nodes[1], true);
8578 check_added_monitors!(nodes[1], 1);
8580 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8581 if broadcast_alice {
8582 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8583 // new block being connected. The ChannelManager being notified triggers a monitor update,
8584 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8585 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8587 assert_eq!(bob_txn.len(), 3);
8588 check_spends!(bob_txn[1], chan_ab.3);
8590 assert_eq!(bob_txn.len(), 2);
8591 check_spends!(bob_txn[0], chan_ab.3);
8596 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8597 // broadcasted commitment transaction.
8599 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8600 if go_onchain_before_fulfill {
8601 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8602 assert_eq!(bob_txn.len(), 2);
8604 let script_weight = match broadcast_alice {
8605 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8606 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8608 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8609 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8610 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8611 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8612 if broadcast_alice && !go_onchain_before_fulfill {
8613 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8614 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8616 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8617 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8623 fn test_onchain_htlc_settlement_after_close() {
8624 do_test_onchain_htlc_settlement_after_close(true, true);
8625 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8626 do_test_onchain_htlc_settlement_after_close(true, false);
8627 do_test_onchain_htlc_settlement_after_close(false, false);
8631 fn test_duplicate_chan_id() {
8632 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8633 // already open we reject it and keep the old channel.
8635 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8636 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8637 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8638 // updating logic for the existing channel.
8639 let chanmon_cfgs = create_chanmon_cfgs(2);
8640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8644 // Create an initial channel
8645 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8646 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8647 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8648 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()));
8650 // Try to create a second channel with the same temporary_channel_id as the first and check
8651 // that it is rejected.
8652 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8654 let events = nodes[1].node.get_and_clear_pending_msg_events();
8655 assert_eq!(events.len(), 1);
8657 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8658 // Technically, at this point, nodes[1] would be justified in thinking both the
8659 // first (valid) and second (invalid) channels are closed, given they both have
8660 // the same non-temporary channel_id. However, currently we do not, so we just
8661 // move forward with it.
8662 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8663 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8665 _ => panic!("Unexpected event"),
8669 // Move the first channel through the funding flow...
8670 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8672 nodes[0].node.funding_transaction_generated(&temporary_channel_id, tx.clone()).unwrap();
8673 check_added_monitors!(nodes[0], 0);
8675 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8676 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8678 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8679 assert_eq!(added_monitors.len(), 1);
8680 assert_eq!(added_monitors[0].0, funding_output);
8681 added_monitors.clear();
8683 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8685 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8686 let channel_id = funding_outpoint.to_channel_id();
8688 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8691 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8692 // Technically this is allowed by the spec, but we don't support it and there's little reason
8693 // to. Still, it shouldn't cause any other issues.
8694 open_chan_msg.temporary_channel_id = channel_id;
8695 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8697 let events = nodes[1].node.get_and_clear_pending_msg_events();
8698 assert_eq!(events.len(), 1);
8700 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8701 // Technically, at this point, nodes[1] would be justified in thinking both
8702 // channels are closed, but currently we do not, so we just move forward with it.
8703 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8704 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8706 _ => panic!("Unexpected event"),
8710 // Now try to create a second channel which has a duplicate funding output.
8711 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8712 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8713 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8714 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()));
8715 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8717 let funding_created = {
8718 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8719 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8720 let logger = test_utils::TestLogger::new();
8721 as_chan.get_outbound_funding_created(tx.clone(), funding_outpoint, &&logger).unwrap()
8723 check_added_monitors!(nodes[0], 0);
8724 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8725 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8726 // still needs to be cleared here.
8727 check_added_monitors!(nodes[1], 1);
8729 // ...still, nodes[1] will reject the duplicate channel.
8731 let events = nodes[1].node.get_and_clear_pending_msg_events();
8732 assert_eq!(events.len(), 1);
8734 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8735 // Technically, at this point, nodes[1] would be justified in thinking both
8736 // channels are closed, but currently we do not, so we just move forward with it.
8737 assert_eq!(msg.channel_id, channel_id);
8738 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8740 _ => panic!("Unexpected event"),
8744 // finally, finish creating the original channel and send a payment over it to make sure
8745 // everything is functional.
8746 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8748 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8749 assert_eq!(added_monitors.len(), 1);
8750 assert_eq!(added_monitors[0].0, funding_output);
8751 added_monitors.clear();
8754 let events_4 = nodes[0].node.get_and_clear_pending_events();
8755 assert_eq!(events_4.len(), 0);
8756 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
8757 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].txid(), funding_output.txid);
8759 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8760 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8761 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8762 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8766 fn test_error_chans_closed() {
8767 // Test that we properly handle error messages, closing appropriate channels.
8769 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8770 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8771 // we can test various edge cases around it to ensure we don't regress.
8772 let chanmon_cfgs = create_chanmon_cfgs(3);
8773 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8774 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8775 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8777 // Create some initial channels
8778 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8779 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8780 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8782 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8783 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8784 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8786 // Closing a channel from a different peer has no effect
8787 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8788 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8790 // Closing one channel doesn't impact others
8791 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8792 check_added_monitors!(nodes[0], 1);
8793 check_closed_broadcast!(nodes[0], false);
8794 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
8795 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8796 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);
8797 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);
8799 // A null channel ID should close all channels
8800 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8801 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8802 check_added_monitors!(nodes[0], 2);
8803 let events = nodes[0].node.get_and_clear_pending_msg_events();
8804 assert_eq!(events.len(), 2);
8806 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8807 assert_eq!(msg.contents.flags & 2, 2);
8809 _ => panic!("Unexpected event"),
8812 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8813 assert_eq!(msg.contents.flags & 2, 2);
8815 _ => panic!("Unexpected event"),
8817 // Note that at this point users of a standard PeerHandler will end up calling
8818 // peer_disconnected with no_connection_possible set to false, duplicating the
8819 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8820 // users with their own peer handling logic. We duplicate the call here, however.
8821 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8822 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8824 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8825 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8826 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);