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::{Sign, KeysInterface};
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;
54 use std::sync::atomic::Ordering;
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
61 fn test_insane_channel_opens() {
62 // Stand up a network of 2 nodes
63 let chanmon_cfgs = create_chanmon_cfgs(2);
64 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
68 // Instantiate channel parameters where we push the maximum msats given our
70 let channel_value_sat = 31337; // same as funding satoshis
71 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
74 // Have node0 initiate a channel to node1 with aforementioned parameters
75 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
77 // Extract the channel open message from node0 to node1
78 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
80 // Test helper that asserts we get the correct error string given a mutator
81 // that supposedly makes the channel open message insane
82 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85 assert_eq!(msg_events.len(), 1);
86 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
89 &ErrorAction::SendErrorMessage { .. } => {
90 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
92 _ => panic!("unexpected event!"),
94 } else { assert!(false); }
97 use ln::channel::MAX_FUNDING_SATOSHIS;
98 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
100 // Test all mutations that would make the channel open message insane
101 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 });
103 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
105 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 });
107 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
109 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 });
111 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 });
113 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 });
115 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
117 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 fn test_async_inbound_update_fee() {
122 let chanmon_cfgs = create_chanmon_cfgs(2);
123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127 let logger = test_utils::TestLogger::new();
128 let channel_id = chan.2;
131 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
135 // send (1) commitment_signed -.
136 // <- update_add_htlc/commitment_signed
137 // send (2) RAA (awaiting remote revoke) -.
138 // (1) commitment_signed is delivered ->
139 // .- send (3) RAA (awaiting remote revoke)
140 // (2) RAA is delivered ->
141 // .- send (4) commitment_signed
142 // <- (3) RAA is delivered
143 // send (5) commitment_signed -.
144 // <- (4) commitment_signed is delivered
146 // (5) commitment_signed is delivered ->
148 // (6) RAA is delivered ->
150 // First nodes[0] generates an update_fee
151 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152 check_added_monitors!(nodes[0], 1);
154 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155 assert_eq!(events_0.len(), 1);
156 let (update_msg, commitment_signed) = match events_0[0] { // (1)
157 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158 (update_fee.as_ref(), commitment_signed)
160 _ => panic!("Unexpected event"),
163 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
165 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168 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();
169 check_added_monitors!(nodes[1], 1);
171 let payment_event = {
172 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173 assert_eq!(events_1.len(), 1);
174 SendEvent::from_event(events_1.remove(0))
176 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177 assert_eq!(payment_event.msgs.len(), 1);
179 // ...now when the messages get delivered everyone should be happy
180 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184 check_added_monitors!(nodes[0], 1);
186 // deliver(1), generate (3):
187 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190 check_added_monitors!(nodes[1], 1);
192 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198 assert!(bs_update.update_fee.is_none()); // (4)
199 check_added_monitors!(nodes[1], 1);
201 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203 assert!(as_update.update_add_htlcs.is_empty()); // (5)
204 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207 assert!(as_update.update_fee.is_none()); // (5)
208 check_added_monitors!(nodes[0], 1);
210 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212 // only (6) so get_event_msg's assert(len == 1) passes
213 check_added_monitors!(nodes[0], 1);
215 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217 check_added_monitors!(nodes[1], 1);
219 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220 check_added_monitors!(nodes[0], 1);
222 let events_2 = nodes[0].node.get_and_clear_pending_events();
223 assert_eq!(events_2.len(), 1);
225 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226 _ => panic!("Unexpected event"),
229 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230 check_added_monitors!(nodes[1], 1);
234 fn test_update_fee_unordered_raa() {
235 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236 // crash in an earlier version of the update_fee patch)
237 let chanmon_cfgs = create_chanmon_cfgs(2);
238 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242 let channel_id = chan.2;
243 let logger = test_utils::TestLogger::new();
246 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
248 // First nodes[0] generates an update_fee
249 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250 check_added_monitors!(nodes[0], 1);
252 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253 assert_eq!(events_0.len(), 1);
254 let update_msg = match events_0[0] { // (1)
255 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
258 _ => panic!("Unexpected event"),
261 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
263 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266 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();
267 check_added_monitors!(nodes[1], 1);
269 let payment_event = {
270 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271 assert_eq!(events_1.len(), 1);
272 SendEvent::from_event(events_1.remove(0))
274 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275 assert_eq!(payment_event.msgs.len(), 1);
277 // ...now when the messages get delivered everyone should be happy
278 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[0], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285 check_added_monitors!(nodes[1], 1);
287 // We can't continue, sadly, because our (1) now has a bogus signature
291 fn test_multi_flight_update_fee() {
292 let chanmon_cfgs = create_chanmon_cfgs(2);
293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297 let channel_id = chan.2;
300 // update_fee/commitment_signed ->
301 // .- send (1) RAA and (2) commitment_signed
302 // update_fee (never committed) ->
304 // We have to manually generate the above update_fee, it is allowed by the protocol but we
305 // don't track which updates correspond to which revoke_and_ack responses so we're in
306 // AwaitingRAA mode and will not generate the update_fee yet.
307 // <- (1) RAA delivered
308 // (3) is generated and send (4) CS -.
309 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310 // know the per_commitment_point to use for it.
311 // <- (2) commitment_signed delivered
313 // B should send no response here
314 // (4) commitment_signed delivered ->
315 // <- RAA/commitment_signed delivered
318 // First nodes[0] generates an update_fee
319 let initial_feerate = get_feerate!(nodes[0], channel_id);
320 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321 check_added_monitors!(nodes[0], 1);
323 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324 assert_eq!(events_0.len(), 1);
325 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327 (update_fee.as_ref().unwrap(), commitment_signed)
329 _ => panic!("Unexpected event"),
332 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336 check_added_monitors!(nodes[1], 1);
338 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
340 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
344 // Create the (3) update_fee message that nodes[0] will generate before it does...
345 let mut update_msg_2 = msgs::UpdateFee {
346 channel_id: update_msg_1.channel_id.clone(),
347 feerate_per_kw: (initial_feerate + 30) as u32,
350 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
352 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
354 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
356 // Deliver (1), generating (3) and (4)
357 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359 check_added_monitors!(nodes[0], 1);
360 assert!(as_second_update.update_add_htlcs.is_empty());
361 assert!(as_second_update.update_fulfill_htlcs.is_empty());
362 assert!(as_second_update.update_fail_htlcs.is_empty());
363 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364 // Check that the update_fee newly generated matches what we delivered:
365 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
368 // Deliver (2) commitment_signed
369 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371 check_added_monitors!(nodes[0], 1);
372 // No commitment_signed so get_event_msg's assert(len == 1) passes
374 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376 check_added_monitors!(nodes[1], 1);
379 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381 check_added_monitors!(nodes[1], 1);
383 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385 check_added_monitors!(nodes[0], 1);
387 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389 // No commitment_signed so get_event_msg's assert(len == 1) passes
390 check_added_monitors!(nodes[0], 1);
392 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394 check_added_monitors!(nodes[1], 1);
398 fn test_1_conf_open() {
399 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
400 // tests that we properly send one in that case.
401 let mut alice_config = UserConfig::default();
402 alice_config.own_channel_config.minimum_depth = 1;
403 alice_config.channel_options.announced_channel = true;
404 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
405 let mut bob_config = UserConfig::default();
406 bob_config.own_channel_config.minimum_depth = 1;
407 bob_config.channel_options.announced_channel = true;
408 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
409 let chanmon_cfgs = create_chanmon_cfgs(2);
410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
414 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415 mine_transaction(&nodes[1], &tx);
416 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()));
418 mine_transaction(&nodes[0], &tx);
419 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
420 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
423 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
424 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
425 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
429 fn do_test_sanity_on_in_flight_opens(steps: u8) {
430 // Previously, we had issues deserializing channels when we hadn't connected the first block
431 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
432 // serialization round-trips and simply do steps towards opening a channel and then drop the
435 let chanmon_cfgs = create_chanmon_cfgs(2);
436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
440 if steps & 0b1000_0000 != 0{
442 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
445 connect_block(&nodes[0], &block, 1);
446 connect_block(&nodes[1], &block, 1);
449 if steps & 0x0f == 0 { return; }
450 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
451 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
453 if steps & 0x0f == 1 { return; }
454 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
455 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
457 if steps & 0x0f == 2 { return; }
458 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
460 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
462 if steps & 0x0f == 3 { return; }
463 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
464 check_added_monitors!(nodes[0], 0);
465 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
467 if steps & 0x0f == 4 { return; }
468 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
470 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
471 assert_eq!(added_monitors.len(), 1);
472 assert_eq!(added_monitors[0].0, funding_output);
473 added_monitors.clear();
475 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
477 if steps & 0x0f == 5 { return; }
478 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
480 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
481 assert_eq!(added_monitors.len(), 1);
482 assert_eq!(added_monitors[0].0, funding_output);
483 added_monitors.clear();
486 let events_4 = nodes[0].node.get_and_clear_pending_events();
487 assert_eq!(events_4.len(), 1);
489 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
490 assert_eq!(user_channel_id, 42);
491 assert_eq!(*funding_txo, funding_output);
493 _ => panic!("Unexpected event"),
496 if steps & 0x0f == 6 { return; }
497 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
499 if steps & 0x0f == 7 { return; }
500 confirm_transaction_at(&nodes[0], &tx, 2);
501 connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
502 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
506 fn test_sanity_on_in_flight_opens() {
507 do_test_sanity_on_in_flight_opens(0);
508 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
509 do_test_sanity_on_in_flight_opens(1);
510 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
511 do_test_sanity_on_in_flight_opens(2);
512 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
513 do_test_sanity_on_in_flight_opens(3);
514 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
515 do_test_sanity_on_in_flight_opens(4);
516 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
517 do_test_sanity_on_in_flight_opens(5);
518 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
519 do_test_sanity_on_in_flight_opens(6);
520 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
521 do_test_sanity_on_in_flight_opens(7);
522 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
523 do_test_sanity_on_in_flight_opens(8);
524 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
528 fn test_update_fee_vanilla() {
529 let chanmon_cfgs = create_chanmon_cfgs(2);
530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
532 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
533 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
534 let channel_id = chan.2;
536 let feerate = get_feerate!(nodes[0], channel_id);
537 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
538 check_added_monitors!(nodes[0], 1);
540 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
541 assert_eq!(events_0.len(), 1);
542 let (update_msg, commitment_signed) = match events_0[0] {
543 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 } } => {
544 (update_fee.as_ref(), commitment_signed)
546 _ => panic!("Unexpected event"),
548 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
550 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
551 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
552 check_added_monitors!(nodes[1], 1);
554 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
555 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
556 check_added_monitors!(nodes[0], 1);
558 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
559 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
560 // No commitment_signed so get_event_msg's assert(len == 1) passes
561 check_added_monitors!(nodes[0], 1);
563 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
564 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
565 check_added_monitors!(nodes[1], 1);
569 fn test_update_fee_that_funder_cannot_afford() {
570 let chanmon_cfgs = create_chanmon_cfgs(2);
571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
574 let channel_value = 1888;
575 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
576 let channel_id = chan.2;
579 nodes[0].node.update_fee(channel_id, feerate).unwrap();
580 check_added_monitors!(nodes[0], 1);
581 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
583 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
585 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
587 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
588 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
590 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
592 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
593 let num_htlcs = commitment_tx.output.len() - 2;
594 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
595 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
596 actual_fee = channel_value - actual_fee;
597 assert_eq!(total_fee, actual_fee);
600 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
601 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
602 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
603 check_added_monitors!(nodes[0], 1);
605 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
607 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
609 //While producing the commitment_signed response after handling a received update_fee request the
610 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
611 //Should produce and error.
612 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
613 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
614 check_added_monitors!(nodes[1], 1);
615 check_closed_broadcast!(nodes[1], true);
619 fn test_update_fee_with_fundee_update_add_htlc() {
620 let chanmon_cfgs = create_chanmon_cfgs(2);
621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
623 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
624 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
625 let channel_id = chan.2;
626 let logger = test_utils::TestLogger::new();
629 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
631 let feerate = get_feerate!(nodes[0], channel_id);
632 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
633 check_added_monitors!(nodes[0], 1);
635 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
636 assert_eq!(events_0.len(), 1);
637 let (update_msg, commitment_signed) = match events_0[0] {
638 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 } } => {
639 (update_fee.as_ref(), commitment_signed)
641 _ => panic!("Unexpected event"),
643 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
644 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
645 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
646 check_added_monitors!(nodes[1], 1);
648 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
649 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
650 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();
652 // nothing happens since node[1] is in AwaitingRemoteRevoke
653 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
655 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
656 assert_eq!(added_monitors.len(), 0);
657 added_monitors.clear();
659 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
660 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
661 // node[1] has nothing to do
663 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
665 check_added_monitors!(nodes[0], 1);
667 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
668 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
669 // No commitment_signed so get_event_msg's assert(len == 1) passes
670 check_added_monitors!(nodes[0], 1);
671 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
672 check_added_monitors!(nodes[1], 1);
673 // AwaitingRemoteRevoke ends here
675 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
676 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
677 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
678 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
679 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
680 assert_eq!(commitment_update.update_fee.is_none(), true);
682 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
683 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
684 check_added_monitors!(nodes[0], 1);
685 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
687 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
688 check_added_monitors!(nodes[1], 1);
689 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
691 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
692 check_added_monitors!(nodes[1], 1);
693 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
694 // No commitment_signed so get_event_msg's assert(len == 1) passes
696 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
697 check_added_monitors!(nodes[0], 1);
698 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
700 expect_pending_htlcs_forwardable!(nodes[0]);
702 let events = nodes[0].node.get_and_clear_pending_events();
703 assert_eq!(events.len(), 1);
705 Event::PaymentReceived { .. } => { },
706 _ => panic!("Unexpected event"),
709 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
711 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
712 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
713 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
717 fn test_update_fee() {
718 let chanmon_cfgs = create_chanmon_cfgs(2);
719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
721 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
722 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
723 let channel_id = chan.2;
726 // (1) update_fee/commitment_signed ->
727 // <- (2) revoke_and_ack
728 // .- send (3) commitment_signed
729 // (4) update_fee/commitment_signed ->
730 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
731 // <- (3) commitment_signed delivered
732 // send (6) revoke_and_ack -.
733 // <- (5) deliver revoke_and_ack
734 // (6) deliver revoke_and_ack ->
735 // .- send (7) commitment_signed in response to (4)
736 // <- (7) deliver commitment_signed
739 // Create and deliver (1)...
740 let feerate = get_feerate!(nodes[0], channel_id);
741 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
742 check_added_monitors!(nodes[0], 1);
744 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
745 assert_eq!(events_0.len(), 1);
746 let (update_msg, commitment_signed) = match events_0[0] {
747 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 } } => {
748 (update_fee.as_ref(), commitment_signed)
750 _ => panic!("Unexpected event"),
752 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
754 // Generate (2) and (3):
755 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
756 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
757 check_added_monitors!(nodes[1], 1);
760 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
761 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
762 check_added_monitors!(nodes[0], 1);
764 // Create and deliver (4)...
765 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
766 check_added_monitors!(nodes[0], 1);
767 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
768 assert_eq!(events_0.len(), 1);
769 let (update_msg, commitment_signed) = match events_0[0] {
770 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 } } => {
771 (update_fee.as_ref(), commitment_signed)
773 _ => panic!("Unexpected event"),
776 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
777 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
778 check_added_monitors!(nodes[1], 1);
780 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
781 // No commitment_signed so get_event_msg's assert(len == 1) passes
783 // Handle (3), creating (6):
784 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
785 check_added_monitors!(nodes[0], 1);
786 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
787 // No commitment_signed so get_event_msg's assert(len == 1) passes
790 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
791 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
792 check_added_monitors!(nodes[0], 1);
794 // Deliver (6), creating (7):
795 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
796 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
797 assert!(commitment_update.update_add_htlcs.is_empty());
798 assert!(commitment_update.update_fulfill_htlcs.is_empty());
799 assert!(commitment_update.update_fail_htlcs.is_empty());
800 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
801 assert!(commitment_update.update_fee.is_none());
802 check_added_monitors!(nodes[1], 1);
805 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
806 check_added_monitors!(nodes[0], 1);
807 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
808 // No commitment_signed so get_event_msg's assert(len == 1) passes
810 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
811 check_added_monitors!(nodes[1], 1);
812 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
814 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
815 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
816 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
820 fn pre_funding_lock_shutdown_test() {
821 // Test sending a shutdown prior to funding_locked after funding generation
822 let chanmon_cfgs = create_chanmon_cfgs(2);
823 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
824 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
825 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
826 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
827 mine_transaction(&nodes[0], &tx);
828 mine_transaction(&nodes[1], &tx);
830 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
831 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
832 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
833 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
834 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
836 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
837 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
838 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
839 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
840 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
841 assert!(node_0_none.is_none());
843 assert!(nodes[0].node.list_channels().is_empty());
844 assert!(nodes[1].node.list_channels().is_empty());
848 fn updates_shutdown_wait() {
849 // Test sending a shutdown with outstanding updates pending
850 let chanmon_cfgs = create_chanmon_cfgs(3);
851 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
852 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
853 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
854 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
855 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
856 let logger = test_utils::TestLogger::new();
858 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
860 nodes[0].node.close_channel(&chan_1.2).unwrap();
861 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
862 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
863 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
864 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
866 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
867 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
869 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
871 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
872 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
873 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();
874 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();
875 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
876 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
878 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
879 check_added_monitors!(nodes[2], 1);
880 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
881 assert!(updates.update_add_htlcs.is_empty());
882 assert!(updates.update_fail_htlcs.is_empty());
883 assert!(updates.update_fail_malformed_htlcs.is_empty());
884 assert!(updates.update_fee.is_none());
885 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
886 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
887 check_added_monitors!(nodes[1], 1);
888 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
891 assert!(updates_2.update_add_htlcs.is_empty());
892 assert!(updates_2.update_fail_htlcs.is_empty());
893 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
894 assert!(updates_2.update_fee.is_none());
895 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
896 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
897 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
899 let events = nodes[0].node.get_and_clear_pending_events();
900 assert_eq!(events.len(), 1);
902 Event::PaymentSent { ref payment_preimage } => {
903 assert_eq!(our_payment_preimage, *payment_preimage);
905 _ => panic!("Unexpected event"),
908 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
909 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
910 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
911 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
912 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
913 assert!(node_0_none.is_none());
915 assert!(nodes[0].node.list_channels().is_empty());
917 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
918 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
919 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
920 assert!(nodes[1].node.list_channels().is_empty());
921 assert!(nodes[2].node.list_channels().is_empty());
925 fn htlc_fail_async_shutdown() {
926 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
927 let chanmon_cfgs = create_chanmon_cfgs(3);
928 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
929 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
930 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
931 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
932 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
933 let logger = test_utils::TestLogger::new();
935 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
936 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
937 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();
938 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
939 check_added_monitors!(nodes[0], 1);
940 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
941 assert_eq!(updates.update_add_htlcs.len(), 1);
942 assert!(updates.update_fulfill_htlcs.is_empty());
943 assert!(updates.update_fail_htlcs.is_empty());
944 assert!(updates.update_fail_malformed_htlcs.is_empty());
945 assert!(updates.update_fee.is_none());
947 nodes[1].node.close_channel(&chan_1.2).unwrap();
948 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
949 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
950 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
952 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
953 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
954 check_added_monitors!(nodes[1], 1);
955 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
956 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
958 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
959 assert!(updates_2.update_add_htlcs.is_empty());
960 assert!(updates_2.update_fulfill_htlcs.is_empty());
961 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
962 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
963 assert!(updates_2.update_fee.is_none());
965 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
966 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
968 expect_payment_failed!(nodes[0], our_payment_hash, false);
970 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
971 assert_eq!(msg_events.len(), 2);
972 let node_0_closing_signed = match msg_events[0] {
973 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
974 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
977 _ => panic!("Unexpected event"),
979 match msg_events[1] {
980 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
981 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
983 _ => panic!("Unexpected event"),
986 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
987 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
988 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
989 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
990 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
991 assert!(node_0_none.is_none());
993 assert!(nodes[0].node.list_channels().is_empty());
995 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
996 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
997 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
998 assert!(nodes[1].node.list_channels().is_empty());
999 assert!(nodes[2].node.list_channels().is_empty());
1002 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1003 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1004 // messages delivered prior to disconnect
1005 let chanmon_cfgs = create_chanmon_cfgs(3);
1006 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1007 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1008 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1009 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1010 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1012 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1014 nodes[1].node.close_channel(&chan_1.2).unwrap();
1015 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1017 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1018 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1020 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1024 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1025 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1027 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1029 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1030 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1032 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1033 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1034 assert!(node_1_shutdown == node_1_2nd_shutdown);
1036 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1037 let node_0_2nd_shutdown = if recv_count > 0 {
1038 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1039 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1042 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1043 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1044 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1046 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1048 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1051 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1052 check_added_monitors!(nodes[2], 1);
1053 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1054 assert!(updates.update_add_htlcs.is_empty());
1055 assert!(updates.update_fail_htlcs.is_empty());
1056 assert!(updates.update_fail_malformed_htlcs.is_empty());
1057 assert!(updates.update_fee.is_none());
1058 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1059 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1060 check_added_monitors!(nodes[1], 1);
1061 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1062 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1064 assert!(updates_2.update_add_htlcs.is_empty());
1065 assert!(updates_2.update_fail_htlcs.is_empty());
1066 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1067 assert!(updates_2.update_fee.is_none());
1068 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1069 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1070 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1072 let events = nodes[0].node.get_and_clear_pending_events();
1073 assert_eq!(events.len(), 1);
1075 Event::PaymentSent { ref payment_preimage } => {
1076 assert_eq!(our_payment_preimage, *payment_preimage);
1078 _ => panic!("Unexpected event"),
1081 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1083 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1084 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1085 assert!(node_1_closing_signed.is_some());
1088 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1089 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1091 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1093 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1094 if recv_count == 0 {
1095 // If all closing_signeds weren't delivered we can just resume where we left off...
1096 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1098 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1099 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1100 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1102 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1103 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1104 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1106 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1107 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1109 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1110 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1111 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1113 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1114 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1115 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1116 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1117 assert!(node_0_none.is_none());
1119 // If one node, however, received + responded with an identical closing_signed we end
1120 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1121 // There isn't really anything better we can do simply, but in the future we might
1122 // explore storing a set of recently-closed channels that got disconnected during
1123 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1124 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1126 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1128 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1129 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1130 assert_eq!(msg_events.len(), 1);
1131 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1133 &ErrorAction::SendErrorMessage { ref msg } => {
1134 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1135 assert_eq!(msg.channel_id, chan_1.2);
1137 _ => panic!("Unexpected event!"),
1139 } else { panic!("Needed SendErrorMessage close"); }
1141 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1142 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1143 // closing_signed so we do it ourselves
1144 check_closed_broadcast!(nodes[0], false);
1145 check_added_monitors!(nodes[0], 1);
1148 assert!(nodes[0].node.list_channels().is_empty());
1150 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1151 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1152 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1153 assert!(nodes[1].node.list_channels().is_empty());
1154 assert!(nodes[2].node.list_channels().is_empty());
1158 fn test_shutdown_rebroadcast() {
1159 do_test_shutdown_rebroadcast(0);
1160 do_test_shutdown_rebroadcast(1);
1161 do_test_shutdown_rebroadcast(2);
1165 fn fake_network_test() {
1166 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1167 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1168 let chanmon_cfgs = create_chanmon_cfgs(4);
1169 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1170 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1171 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1173 // Create some initial channels
1174 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1175 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1176 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1178 // Rebalance the network a bit by relaying one payment through all the channels...
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);
1181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1184 // Send some more payments
1185 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1186 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1187 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1189 // Test failure packets
1190 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1191 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1193 // Add a new channel that skips 3
1194 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1196 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1197 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_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);
1201 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1204 // Do some rebalance loop payments, simultaneously
1205 let mut hops = Vec::with_capacity(3);
1206 hops.push(RouteHop {
1207 pubkey: nodes[2].node.get_our_node_id(),
1208 node_features: NodeFeatures::empty(),
1209 short_channel_id: chan_2.0.contents.short_channel_id,
1210 channel_features: ChannelFeatures::empty(),
1212 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1214 hops.push(RouteHop {
1215 pubkey: nodes[3].node.get_our_node_id(),
1216 node_features: NodeFeatures::empty(),
1217 short_channel_id: chan_3.0.contents.short_channel_id,
1218 channel_features: ChannelFeatures::empty(),
1220 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1222 hops.push(RouteHop {
1223 pubkey: nodes[1].node.get_our_node_id(),
1224 node_features: NodeFeatures::empty(),
1225 short_channel_id: chan_4.0.contents.short_channel_id,
1226 channel_features: ChannelFeatures::empty(),
1228 cltv_expiry_delta: TEST_FINAL_CLTV,
1230 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;
1231 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;
1232 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1234 let mut hops = Vec::with_capacity(3);
1235 hops.push(RouteHop {
1236 pubkey: nodes[3].node.get_our_node_id(),
1237 node_features: NodeFeatures::empty(),
1238 short_channel_id: chan_4.0.contents.short_channel_id,
1239 channel_features: ChannelFeatures::empty(),
1241 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1243 hops.push(RouteHop {
1244 pubkey: nodes[2].node.get_our_node_id(),
1245 node_features: NodeFeatures::empty(),
1246 short_channel_id: chan_3.0.contents.short_channel_id,
1247 channel_features: ChannelFeatures::empty(),
1249 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1251 hops.push(RouteHop {
1252 pubkey: nodes[1].node.get_our_node_id(),
1253 node_features: NodeFeatures::empty(),
1254 short_channel_id: chan_2.0.contents.short_channel_id,
1255 channel_features: ChannelFeatures::empty(),
1257 cltv_expiry_delta: TEST_FINAL_CLTV,
1259 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;
1260 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;
1261 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1263 // Claim the rebalances...
1264 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1265 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1267 // Add a duplicate new channel from 2 to 4
1268 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1270 // Send some payments across both channels
1271 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1276 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1277 let events = nodes[0].node.get_and_clear_pending_msg_events();
1278 assert_eq!(events.len(), 0);
1279 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);
1281 //TODO: Test that routes work again here as we've been notified that the channel is full
1283 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1284 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1285 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1287 // Close down the channels...
1288 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1289 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1290 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1291 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1292 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1296 fn holding_cell_htlc_counting() {
1297 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1298 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1299 // commitment dance rounds.
1300 let chanmon_cfgs = create_chanmon_cfgs(3);
1301 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1302 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1303 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1304 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1305 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1306 let logger = test_utils::TestLogger::new();
1308 let mut payments = Vec::new();
1309 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1310 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1311 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1312 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();
1313 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1314 payments.push((payment_preimage, payment_hash));
1316 check_added_monitors!(nodes[1], 1);
1318 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1319 assert_eq!(events.len(), 1);
1320 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1321 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1323 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1324 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1326 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1328 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1329 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();
1330 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1331 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1332 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1333 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1336 // This should also be true if we try to forward a payment.
1337 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1339 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1340 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();
1341 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1342 check_added_monitors!(nodes[0], 1);
1345 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1346 assert_eq!(events.len(), 1);
1347 let payment_event = SendEvent::from_event(events.pop().unwrap());
1348 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1350 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1351 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1352 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1353 // fails), the second will process the resulting failure and fail the HTLC backward.
1354 expect_pending_htlcs_forwardable!(nodes[1]);
1355 expect_pending_htlcs_forwardable!(nodes[1]);
1356 check_added_monitors!(nodes[1], 1);
1358 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1359 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1360 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1362 let events = nodes[0].node.get_and_clear_pending_msg_events();
1363 assert_eq!(events.len(), 1);
1365 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1366 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1368 _ => panic!("Unexpected event"),
1371 expect_payment_failed!(nodes[0], payment_hash_2, false);
1373 // Now forward all the pending HTLCs and claim them back
1374 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1375 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1376 check_added_monitors!(nodes[2], 1);
1378 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1379 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1380 check_added_monitors!(nodes[1], 1);
1381 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1383 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1384 check_added_monitors!(nodes[1], 1);
1385 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1387 for ref update in as_updates.update_add_htlcs.iter() {
1388 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1390 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1391 check_added_monitors!(nodes[2], 1);
1392 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1393 check_added_monitors!(nodes[2], 1);
1394 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1396 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1397 check_added_monitors!(nodes[1], 1);
1398 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1399 check_added_monitors!(nodes[1], 1);
1400 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1402 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1403 check_added_monitors!(nodes[2], 1);
1405 expect_pending_htlcs_forwardable!(nodes[2]);
1407 let events = nodes[2].node.get_and_clear_pending_events();
1408 assert_eq!(events.len(), payments.len());
1409 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1411 &Event::PaymentReceived { ref payment_hash, .. } => {
1412 assert_eq!(*payment_hash, *hash);
1414 _ => panic!("Unexpected event"),
1418 for (preimage, _) in payments.drain(..) {
1419 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1422 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1426 fn duplicate_htlc_test() {
1427 // Test that we accept duplicate payment_hash HTLCs across the network and that
1428 // claiming/failing them are all separate and don't affect each other
1429 let chanmon_cfgs = create_chanmon_cfgs(6);
1430 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1431 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1432 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1434 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1435 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1436 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1437 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1438 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1439 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1441 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1443 *nodes[0].network_payment_count.borrow_mut() -= 1;
1444 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1446 *nodes[0].network_payment_count.borrow_mut() -= 1;
1447 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1449 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1450 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1451 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1455 fn test_duplicate_htlc_different_direction_onchain() {
1456 // Test that ChannelMonitor doesn't generate 2 preimage txn
1457 // when we have 2 HTLCs with same preimage that go across a node
1458 // in opposite directions.
1459 let chanmon_cfgs = create_chanmon_cfgs(2);
1460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1462 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1464 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1465 let logger = test_utils::TestLogger::new();
1468 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1470 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1472 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1473 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();
1474 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1476 // Provide preimage to node 0 by claiming payment
1477 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1478 check_added_monitors!(nodes[0], 1);
1480 // Broadcast node 1 commitment txn
1481 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1483 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1484 let mut has_both_htlcs = 0; // check htlcs match ones committed
1485 for outp in remote_txn[0].output.iter() {
1486 if outp.value == 800_000 / 1000 {
1487 has_both_htlcs += 1;
1488 } else if outp.value == 900_000 / 1000 {
1489 has_both_htlcs += 1;
1492 assert_eq!(has_both_htlcs, 2);
1494 mine_transaction(&nodes[0], &remote_txn[0]);
1495 check_added_monitors!(nodes[0], 1);
1497 // Check we only broadcast 1 timeout tx
1498 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1499 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()) };
1500 assert_eq!(claim_txn.len(), 5);
1501 check_spends!(claim_txn[2], chan_1.3);
1502 check_spends!(claim_txn[3], claim_txn[2]);
1503 assert_eq!(htlc_pair.0.input.len(), 1);
1504 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1505 check_spends!(htlc_pair.0, remote_txn[0]);
1506 assert_eq!(htlc_pair.1.input.len(), 1);
1507 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1508 check_spends!(htlc_pair.1, remote_txn[0]);
1510 let events = nodes[0].node.get_and_clear_pending_msg_events();
1511 assert_eq!(events.len(), 2);
1514 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1515 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, .. } } => {
1516 assert!(update_add_htlcs.is_empty());
1517 assert!(update_fail_htlcs.is_empty());
1518 assert_eq!(update_fulfill_htlcs.len(), 1);
1519 assert!(update_fail_malformed_htlcs.is_empty());
1520 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1522 _ => panic!("Unexpected event"),
1528 fn test_basic_channel_reserve() {
1529 let chanmon_cfgs = create_chanmon_cfgs(2);
1530 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1531 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1532 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1533 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1534 let logger = test_utils::TestLogger::new();
1536 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1537 let channel_reserve = chan_stat.channel_reserve_msat;
1539 // The 2* and +1 are for the fee spike reserve.
1540 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1541 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1542 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1543 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1544 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();
1545 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1547 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1549 &APIError::ChannelUnavailable{ref err} =>
1550 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1551 _ => panic!("Unexpected error variant"),
1554 _ => panic!("Unexpected error variant"),
1556 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1557 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);
1559 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1563 fn test_fee_spike_violation_fails_htlc() {
1564 let chanmon_cfgs = create_chanmon_cfgs(2);
1565 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1566 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1567 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1568 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1569 let logger = test_utils::TestLogger::new();
1571 macro_rules! get_route_and_payment_hash {
1572 ($recv_value: expr) => {{
1573 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1574 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1575 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();
1576 (route, payment_hash, payment_preimage)
1580 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1581 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1582 let secp_ctx = Secp256k1::new();
1583 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1585 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1587 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1588 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1589 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1590 let msg = msgs::UpdateAddHTLC {
1593 amount_msat: htlc_msat,
1594 payment_hash: payment_hash,
1595 cltv_expiry: htlc_cltv,
1596 onion_routing_packet: onion_packet,
1599 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1601 // Now manually create the commitment_signed message corresponding to the update_add
1602 // nodes[0] just sent. In the code for construction of this message, "local" refers
1603 // to the sender of the message, and "remote" refers to the receiver.
1605 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1607 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1609 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1610 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1611 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1612 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1613 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1614 let chan_signer = local_chan.get_signer();
1615 let pubkeys = chan_signer.pubkeys();
1616 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1617 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1618 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1620 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1621 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1622 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1623 let chan_signer = remote_chan.get_signer();
1624 let pubkeys = chan_signer.pubkeys();
1625 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1626 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1629 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1630 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1631 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1633 // Build the remote commitment transaction so we can sign it, and then later use the
1634 // signature for the commitment_signed message.
1635 let local_chan_balance = 1313;
1637 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1639 amount_msat: 3460001,
1640 cltv_expiry: htlc_cltv,
1642 transaction_output_index: Some(1),
1645 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1648 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1649 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1650 let local_chan_signer = local_chan.get_signer();
1651 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1655 commit_tx_keys.clone(),
1657 &mut vec![(accepted_htlc_info, ())],
1658 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1660 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1663 let commit_signed_msg = msgs::CommitmentSigned {
1666 htlc_signatures: res.1
1669 // Send the commitment_signed message to the nodes[1].
1670 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1671 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1673 // Send the RAA to nodes[1].
1674 let raa_msg = msgs::RevokeAndACK {
1676 per_commitment_secret: local_secret,
1677 next_per_commitment_point: next_local_point
1679 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1681 let events = nodes[1].node.get_and_clear_pending_msg_events();
1682 assert_eq!(events.len(), 1);
1683 // Make sure the HTLC failed in the way we expect.
1685 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1686 assert_eq!(update_fail_htlcs.len(), 1);
1687 update_fail_htlcs[0].clone()
1689 _ => panic!("Unexpected event"),
1691 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1693 check_added_monitors!(nodes[1], 2);
1697 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1698 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1699 // Set the fee rate for the channel very high, to the point where the fundee
1700 // sending any above-dust amount would result in a channel reserve violation.
1701 // In this test we check that we would be prevented from sending an HTLC in
1703 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1704 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1705 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1706 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1707 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1708 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1709 let logger = test_utils::TestLogger::new();
1711 macro_rules! get_route_and_payment_hash {
1712 ($recv_value: expr) => {{
1713 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1714 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1715 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();
1716 (route, payment_hash, payment_preimage)
1720 let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1721 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1722 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1723 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1724 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);
1728 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1729 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1730 // Set the fee rate for the channel very high, to the point where the funder
1731 // receiving 1 update_add_htlc would result in them closing the channel due
1732 // to channel reserve violation. This close could also happen if the fee went
1733 // up a more realistic amount, but many HTLCs were outstanding at the time of
1734 // the update_add_htlc.
1735 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1736 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1737 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1738 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1739 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1740 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1741 let logger = test_utils::TestLogger::new();
1743 macro_rules! get_route_and_payment_hash {
1744 ($recv_value: expr) => {{
1745 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1746 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1747 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();
1748 (route, payment_hash, payment_preimage)
1752 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1753 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1754 let secp_ctx = Secp256k1::new();
1755 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1756 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1757 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1758 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1759 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1760 let msg = msgs::UpdateAddHTLC {
1763 amount_msat: htlc_msat + 1,
1764 payment_hash: payment_hash,
1765 cltv_expiry: htlc_cltv,
1766 onion_routing_packet: onion_packet,
1769 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1770 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1771 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);
1772 assert_eq!(nodes[0].node.list_channels().len(), 0);
1773 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1774 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1775 check_added_monitors!(nodes[0], 1);
1779 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1780 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1781 // calculating our commitment transaction fee (this was previously broken).
1782 let chanmon_cfgs = create_chanmon_cfgs(2);
1783 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1784 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1785 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1787 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1788 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1789 // transaction fee with 0 HTLCs (183 sats)).
1790 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1792 let dust_amt = 546000; // Dust amount
1793 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1794 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1795 // commitment transaction fee.
1796 let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1800 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1801 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1802 // calculating our counterparty's commitment transaction fee (this was previously broken).
1803 let chanmon_cfgs = create_chanmon_cfgs(2);
1804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1806 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1807 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1809 let payment_amt = 46000; // Dust amount
1810 // In the previous code, these first four payments would succeed.
1811 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1812 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1813 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1814 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1817 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
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);
1823 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1824 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1825 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1826 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1830 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1831 let chanmon_cfgs = create_chanmon_cfgs(3);
1832 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1833 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1834 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1835 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1836 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1837 let logger = test_utils::TestLogger::new();
1839 macro_rules! get_route_and_payment_hash {
1840 ($recv_value: expr) => {{
1841 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1842 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1843 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();
1844 (route, payment_hash, payment_preimage)
1849 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1850 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1851 let feerate = get_feerate!(nodes[0], chan.2);
1853 // Add a 2* and +1 for the fee spike reserve.
1854 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1855 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;
1856 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1858 // Add a pending HTLC.
1859 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1860 let payment_event_1 = {
1861 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1862 check_added_monitors!(nodes[0], 1);
1864 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1865 assert_eq!(events.len(), 1);
1866 SendEvent::from_event(events.remove(0))
1868 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1870 // Attempt to trigger a channel reserve violation --> payment failure.
1871 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1872 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;
1873 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1874 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1876 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1877 let secp_ctx = Secp256k1::new();
1878 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1879 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1880 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1881 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1882 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1883 let msg = msgs::UpdateAddHTLC {
1886 amount_msat: htlc_msat + 1,
1887 payment_hash: our_payment_hash_1,
1888 cltv_expiry: htlc_cltv,
1889 onion_routing_packet: onion_packet,
1892 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1893 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1894 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1895 assert_eq!(nodes[1].node.list_channels().len(), 1);
1896 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1897 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1898 check_added_monitors!(nodes[1], 1);
1902 fn test_inbound_outbound_capacity_is_not_zero() {
1903 let chanmon_cfgs = create_chanmon_cfgs(2);
1904 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1905 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1906 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1907 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1908 let channels0 = node_chanmgrs[0].list_channels();
1909 let channels1 = node_chanmgrs[1].list_channels();
1910 assert_eq!(channels0.len(), 1);
1911 assert_eq!(channels1.len(), 1);
1913 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1914 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1916 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1917 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1920 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1921 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1925 fn test_channel_reserve_holding_cell_htlcs() {
1926 let chanmon_cfgs = create_chanmon_cfgs(3);
1927 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1928 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1929 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1930 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1931 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1932 let logger = test_utils::TestLogger::new();
1934 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1935 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1937 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1938 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1940 macro_rules! get_route_and_payment_hash {
1941 ($recv_value: expr) => {{
1942 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1943 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1944 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();
1945 (route, payment_hash, payment_preimage)
1949 macro_rules! expect_forward {
1951 let mut events = $node.node.get_and_clear_pending_msg_events();
1952 assert_eq!(events.len(), 1);
1953 check_added_monitors!($node, 1);
1954 let payment_event = SendEvent::from_event(events.remove(0));
1959 let feemsat = 239; // somehow we know?
1960 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1961 let feerate = get_feerate!(nodes[0], chan_1.2);
1963 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1965 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1967 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1968 route.paths[0].last_mut().unwrap().fee_msat += 1;
1969 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1970 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1971 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)));
1972 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1973 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);
1976 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1977 // nodes[0]'s wealth
1979 let amt_msat = recv_value_0 + total_fee_msat;
1980 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1981 // Also, ensure that each payment has enough to be over the dust limit to
1982 // ensure it'll be included in each commit tx fee calculation.
1983 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1984 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1985 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1988 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1990 let (stat01_, stat11_, stat12_, stat22_) = (
1991 get_channel_value_stat!(nodes[0], chan_1.2),
1992 get_channel_value_stat!(nodes[1], chan_1.2),
1993 get_channel_value_stat!(nodes[1], chan_2.2),
1994 get_channel_value_stat!(nodes[2], chan_2.2),
1997 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1998 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1999 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2000 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2001 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2004 // adding pending output.
2005 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2006 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2007 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2008 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2009 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2010 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2011 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2012 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2013 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2015 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2016 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2017 let amt_msat_1 = recv_value_1 + total_fee_msat;
2019 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2020 let payment_event_1 = {
2021 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2022 check_added_monitors!(nodes[0], 1);
2024 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2025 assert_eq!(events.len(), 1);
2026 SendEvent::from_event(events.remove(0))
2028 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2030 // channel reserve test with htlc pending output > 0
2031 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2033 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2034 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2035 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2036 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2039 // split the rest to test holding cell
2040 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2041 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2042 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2043 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2045 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2046 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);
2049 // now see if they go through on both sides
2050 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2051 // but this will stuck in the holding cell
2052 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2053 check_added_monitors!(nodes[0], 0);
2054 let events = nodes[0].node.get_and_clear_pending_events();
2055 assert_eq!(events.len(), 0);
2057 // test with outbound holding cell amount > 0
2059 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2060 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2061 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2062 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2063 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);
2066 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2067 // this will also stuck in the holding cell
2068 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2069 check_added_monitors!(nodes[0], 0);
2070 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2071 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2073 // flush the pending htlc
2074 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2075 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2076 check_added_monitors!(nodes[1], 1);
2078 // the pending htlc should be promoted to committed
2079 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2080 check_added_monitors!(nodes[0], 1);
2081 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2083 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2084 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2085 // No commitment_signed so get_event_msg's assert(len == 1) passes
2086 check_added_monitors!(nodes[0], 1);
2088 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2089 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2090 check_added_monitors!(nodes[1], 1);
2092 expect_pending_htlcs_forwardable!(nodes[1]);
2094 let ref payment_event_11 = expect_forward!(nodes[1]);
2095 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2096 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2098 expect_pending_htlcs_forwardable!(nodes[2]);
2099 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2101 // flush the htlcs in the holding cell
2102 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2103 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2104 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2105 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2106 expect_pending_htlcs_forwardable!(nodes[1]);
2108 let ref payment_event_3 = expect_forward!(nodes[1]);
2109 assert_eq!(payment_event_3.msgs.len(), 2);
2110 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2111 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2113 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2114 expect_pending_htlcs_forwardable!(nodes[2]);
2116 let events = nodes[2].node.get_and_clear_pending_events();
2117 assert_eq!(events.len(), 2);
2119 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2120 assert_eq!(our_payment_hash_21, *payment_hash);
2121 assert_eq!(*payment_secret, None);
2122 assert_eq!(recv_value_21, amt);
2124 _ => panic!("Unexpected event"),
2127 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2128 assert_eq!(our_payment_hash_22, *payment_hash);
2129 assert_eq!(None, *payment_secret);
2130 assert_eq!(recv_value_22, amt);
2132 _ => panic!("Unexpected event"),
2135 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2136 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2137 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2139 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2140 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2141 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2143 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2144 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);
2145 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2146 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2147 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2149 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2150 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2154 fn channel_reserve_in_flight_removes() {
2155 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2156 // can send to its counterparty, but due to update ordering, the other side may not yet have
2157 // considered those HTLCs fully removed.
2158 // This tests that we don't count HTLCs which will not be included in the next remote
2159 // commitment transaction towards the reserve value (as it implies no commitment transaction
2160 // will be generated which violates the remote reserve value).
2161 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2163 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2164 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2165 // you only consider the value of the first HTLC, it may not),
2166 // * start routing a third HTLC from A to B,
2167 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2168 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2169 // * deliver the first fulfill from B
2170 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2172 // * deliver A's response CS and RAA.
2173 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2174 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2175 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2176 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2177 let chanmon_cfgs = create_chanmon_cfgs(2);
2178 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2179 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2180 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2181 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2182 let logger = test_utils::TestLogger::new();
2184 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2185 // Route the first two HTLCs.
2186 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2187 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2189 // Start routing the third HTLC (this is just used to get everyone in the right state).
2190 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2192 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2193 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();
2194 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2195 check_added_monitors!(nodes[0], 1);
2196 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2197 assert_eq!(events.len(), 1);
2198 SendEvent::from_event(events.remove(0))
2201 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2202 // initial fulfill/CS.
2203 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2204 check_added_monitors!(nodes[1], 1);
2205 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2207 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2208 // remove the second HTLC when we send the HTLC back from B to A.
2209 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2210 check_added_monitors!(nodes[1], 1);
2211 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2213 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2214 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2215 check_added_monitors!(nodes[0], 1);
2216 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2217 expect_payment_sent!(nodes[0], payment_preimage_1);
2219 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2220 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2221 check_added_monitors!(nodes[1], 1);
2222 // B is already AwaitingRAA, so cant generate a CS here
2223 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2225 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2226 check_added_monitors!(nodes[1], 1);
2227 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2229 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2230 check_added_monitors!(nodes[0], 1);
2231 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2233 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2234 check_added_monitors!(nodes[1], 1);
2235 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2237 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2238 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2239 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2240 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2241 // on-chain as necessary).
2242 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2243 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2244 check_added_monitors!(nodes[0], 1);
2245 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2246 expect_payment_sent!(nodes[0], payment_preimage_2);
2248 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2249 check_added_monitors!(nodes[1], 1);
2250 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2252 expect_pending_htlcs_forwardable!(nodes[1]);
2253 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2255 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2256 // resolve the second HTLC from A's point of view.
2257 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2258 check_added_monitors!(nodes[0], 1);
2259 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2261 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2262 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2263 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2265 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2266 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();
2267 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2268 check_added_monitors!(nodes[1], 1);
2269 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2270 assert_eq!(events.len(), 1);
2271 SendEvent::from_event(events.remove(0))
2274 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2275 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2276 check_added_monitors!(nodes[0], 1);
2277 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2279 // Now just resolve all the outstanding messages/HTLCs for completeness...
2281 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2282 check_added_monitors!(nodes[1], 1);
2283 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2285 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2286 check_added_monitors!(nodes[1], 1);
2288 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2289 check_added_monitors!(nodes[0], 1);
2290 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2292 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2293 check_added_monitors!(nodes[1], 1);
2294 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2296 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2297 check_added_monitors!(nodes[0], 1);
2299 expect_pending_htlcs_forwardable!(nodes[0]);
2300 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2302 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2303 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2307 fn channel_monitor_network_test() {
2308 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2309 // tests that ChannelMonitor is able to recover from various states.
2310 let chanmon_cfgs = create_chanmon_cfgs(5);
2311 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2312 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2313 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2315 // Create some initial channels
2316 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2317 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2318 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2319 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2321 // Make sure all nodes are at the same starting height
2322 connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2323 connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2324 connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2325 connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2326 connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2328 // Rebalance the network a bit by relaying one payment through all the channels...
2329 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2330 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
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);
2334 // Simple case with no pending HTLCs:
2335 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2336 check_added_monitors!(nodes[1], 1);
2338 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2339 assert_eq!(node_txn.len(), 1);
2340 mine_transaction(&nodes[0], &node_txn[0]);
2341 check_added_monitors!(nodes[0], 1);
2342 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2344 get_announce_close_broadcast_events(&nodes, 0, 1);
2345 assert_eq!(nodes[0].node.list_channels().len(), 0);
2346 assert_eq!(nodes[1].node.list_channels().len(), 1);
2348 // One pending HTLC is discarded by the force-close:
2349 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2351 // Simple case of one pending HTLC to HTLC-Timeout
2352 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2353 check_added_monitors!(nodes[1], 1);
2355 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2356 mine_transaction(&nodes[2], &node_txn[0]);
2357 check_added_monitors!(nodes[2], 1);
2358 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2360 get_announce_close_broadcast_events(&nodes, 1, 2);
2361 assert_eq!(nodes[1].node.list_channels().len(), 0);
2362 assert_eq!(nodes[2].node.list_channels().len(), 1);
2364 macro_rules! claim_funds {
2365 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2367 assert!($node.node.claim_funds($preimage, &None, $amount));
2368 check_added_monitors!($node, 1);
2370 let events = $node.node.get_and_clear_pending_msg_events();
2371 assert_eq!(events.len(), 1);
2373 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2374 assert!(update_add_htlcs.is_empty());
2375 assert!(update_fail_htlcs.is_empty());
2376 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2378 _ => panic!("Unexpected event"),
2384 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2385 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2386 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2387 check_added_monitors!(nodes[2], 1);
2388 let node2_commitment_txid;
2390 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2391 node2_commitment_txid = node_txn[0].txid();
2393 // Claim the payment on nodes[3], giving it knowledge of the preimage
2394 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2395 mine_transaction(&nodes[3], &node_txn[0]);
2396 check_added_monitors!(nodes[3], 1);
2397 check_preimage_claim(&nodes[3], &node_txn);
2399 get_announce_close_broadcast_events(&nodes, 2, 3);
2400 assert_eq!(nodes[2].node.list_channels().len(), 0);
2401 assert_eq!(nodes[3].node.list_channels().len(), 1);
2403 // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2404 // confusing us in the following tests.
2405 let chan_3_mon = nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().remove(&OutPoint { txid: chan_3.3.txid(), index: 0 }).unwrap();
2407 // One pending HTLC to time out:
2408 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2409 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2412 let (close_chan_update_1, close_chan_update_2) = {
2413 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2414 let events = nodes[3].node.get_and_clear_pending_msg_events();
2415 assert_eq!(events.len(), 1);
2416 let close_chan_update_1 = match events[0] {
2417 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2420 _ => panic!("Unexpected event"),
2422 check_added_monitors!(nodes[3], 1);
2424 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2426 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2427 node_txn.retain(|tx| {
2428 if tx.input[0].previous_output.txid == node2_commitment_txid {
2434 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2436 // Claim the payment on nodes[4], giving it knowledge of the preimage
2437 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2439 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2440 let events = nodes[4].node.get_and_clear_pending_msg_events();
2441 assert_eq!(events.len(), 1);
2442 let close_chan_update_2 = match events[0] {
2443 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2446 _ => panic!("Unexpected event"),
2448 check_added_monitors!(nodes[4], 1);
2449 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2451 mine_transaction(&nodes[4], &node_txn[0]);
2452 check_preimage_claim(&nodes[4], &node_txn);
2453 (close_chan_update_1, close_chan_update_2)
2455 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2456 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2457 assert_eq!(nodes[3].node.list_channels().len(), 0);
2458 assert_eq!(nodes[4].node.list_channels().len(), 0);
2460 nodes[3].chain_monitor.chain_monitor.monitors.write().unwrap().insert(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon);
2464 fn test_justice_tx() {
2465 // Test justice txn built on revoked HTLC-Success tx, against both sides
2466 let mut alice_config = UserConfig::default();
2467 alice_config.channel_options.announced_channel = true;
2468 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2469 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2470 let mut bob_config = UserConfig::default();
2471 bob_config.channel_options.announced_channel = true;
2472 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2473 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2474 let user_cfgs = [Some(alice_config), Some(bob_config)];
2475 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2476 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2477 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2480 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2481 // Create some new channels:
2482 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2484 // A pending HTLC which will be revoked:
2485 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2486 // Get the will-be-revoked local txn from nodes[0]
2487 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2488 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2489 assert_eq!(revoked_local_txn[0].input.len(), 1);
2490 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2491 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2492 assert_eq!(revoked_local_txn[1].input.len(), 1);
2493 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2494 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2495 // Revoke the old state
2496 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2499 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2501 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2502 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2503 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2505 check_spends!(node_txn[0], revoked_local_txn[0]);
2506 node_txn.swap_remove(0);
2507 node_txn.truncate(1);
2509 check_added_monitors!(nodes[1], 1);
2510 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2512 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2513 // Verify broadcast of revoked HTLC-timeout
2514 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2515 check_added_monitors!(nodes[0], 1);
2516 // Broadcast revoked HTLC-timeout on node 1
2517 mine_transaction(&nodes[1], &node_txn[1]);
2518 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2520 get_announce_close_broadcast_events(&nodes, 0, 1);
2522 assert_eq!(nodes[0].node.list_channels().len(), 0);
2523 assert_eq!(nodes[1].node.list_channels().len(), 0);
2525 // We test justice_tx build by A on B's revoked HTLC-Success tx
2526 // Create some new channels:
2527 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2529 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2533 // A pending HTLC which will be revoked:
2534 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2535 // Get the will-be-revoked local txn from B
2536 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2537 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2538 assert_eq!(revoked_local_txn[0].input.len(), 1);
2539 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2540 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2541 // Revoke the old state
2542 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2544 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2546 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2547 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2548 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2550 check_spends!(node_txn[0], revoked_local_txn[0]);
2551 node_txn.swap_remove(0);
2553 check_added_monitors!(nodes[0], 1);
2554 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2556 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2557 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2558 check_added_monitors!(nodes[1], 1);
2559 mine_transaction(&nodes[0], &node_txn[1]);
2560 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2562 get_announce_close_broadcast_events(&nodes, 0, 1);
2563 assert_eq!(nodes[0].node.list_channels().len(), 0);
2564 assert_eq!(nodes[1].node.list_channels().len(), 0);
2568 fn revoked_output_claim() {
2569 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2570 // transaction is broadcast by its counterparty
2571 let chanmon_cfgs = create_chanmon_cfgs(2);
2572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2575 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2576 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2577 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2578 assert_eq!(revoked_local_txn.len(), 1);
2579 // Only output is the full channel value back to nodes[0]:
2580 assert_eq!(revoked_local_txn[0].output.len(), 1);
2581 // Send a payment through, updating everyone's latest commitment txn
2582 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2584 // Inform nodes[1] that nodes[0] broadcast a stale tx
2585 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2586 check_added_monitors!(nodes[1], 1);
2587 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2588 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2590 check_spends!(node_txn[0], revoked_local_txn[0]);
2591 check_spends!(node_txn[1], chan_1.3);
2593 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2594 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2595 get_announce_close_broadcast_events(&nodes, 0, 1);
2596 check_added_monitors!(nodes[0], 1)
2600 fn claim_htlc_outputs_shared_tx() {
2601 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2602 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2603 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2606 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608 // Create some new channel:
2609 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2611 // Rebalance the network to generate htlc in the two directions
2612 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2613 // 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
2614 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2615 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2617 // Get the will-be-revoked local txn from node[0]
2618 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2619 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2620 assert_eq!(revoked_local_txn[0].input.len(), 1);
2621 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2622 assert_eq!(revoked_local_txn[1].input.len(), 1);
2623 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2624 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2625 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2627 //Revoke the old state
2628 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2631 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2632 check_added_monitors!(nodes[0], 1);
2633 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2634 check_added_monitors!(nodes[1], 1);
2635 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2636 expect_payment_failed!(nodes[1], payment_hash_2, true);
2638 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2639 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2641 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2642 check_spends!(node_txn[0], revoked_local_txn[0]);
2644 let mut witness_lens = BTreeSet::new();
2645 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2646 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2647 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2648 assert_eq!(witness_lens.len(), 3);
2649 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2650 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2651 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2653 // Next nodes[1] broadcasts its current local tx state:
2654 assert_eq!(node_txn[1].input.len(), 1);
2655 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2657 assert_eq!(node_txn[2].input.len(), 1);
2658 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2659 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2660 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2661 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2662 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2664 get_announce_close_broadcast_events(&nodes, 0, 1);
2665 assert_eq!(nodes[0].node.list_channels().len(), 0);
2666 assert_eq!(nodes[1].node.list_channels().len(), 0);
2670 fn claim_htlc_outputs_single_tx() {
2671 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2672 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2673 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2676 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2678 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2680 // Rebalance the network to generate htlc in the two directions
2681 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2682 // 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
2683 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2684 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2685 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2687 // Get the will-be-revoked local txn from node[0]
2688 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2690 //Revoke the old state
2691 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2694 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2695 check_added_monitors!(nodes[0], 1);
2696 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2697 check_added_monitors!(nodes[1], 1);
2698 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2700 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2701 expect_payment_failed!(nodes[1], payment_hash_2, true);
2703 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2704 assert_eq!(node_txn.len(), 9);
2705 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2706 // ChannelManager: local commmitment + local HTLC-timeout (2)
2707 // 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)
2708 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2710 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2711 assert_eq!(node_txn[0].input.len(), 1);
2712 check_spends!(node_txn[0], chan_1.3);
2713 assert_eq!(node_txn[1].input.len(), 1);
2714 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2715 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2716 check_spends!(node_txn[1], node_txn[0]);
2718 // Justice transactions are indices 1-2-4
2719 assert_eq!(node_txn[2].input.len(), 1);
2720 assert_eq!(node_txn[3].input.len(), 1);
2721 assert_eq!(node_txn[4].input.len(), 1);
2723 check_spends!(node_txn[2], revoked_local_txn[0]);
2724 check_spends!(node_txn[3], revoked_local_txn[0]);
2725 check_spends!(node_txn[4], revoked_local_txn[0]);
2727 let mut witness_lens = BTreeSet::new();
2728 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2729 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2730 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2731 assert_eq!(witness_lens.len(), 3);
2732 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2733 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2734 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2736 get_announce_close_broadcast_events(&nodes, 0, 1);
2737 assert_eq!(nodes[0].node.list_channels().len(), 0);
2738 assert_eq!(nodes[1].node.list_channels().len(), 0);
2742 fn test_htlc_on_chain_success() {
2743 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2744 // the preimage backward accordingly. So here we test that ChannelManager is
2745 // broadcasting the right event to other nodes in payment path.
2746 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2747 // A --------------------> B ----------------------> C (preimage)
2748 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2749 // commitment transaction was broadcast.
2750 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2752 // B should be able to claim via preimage if A then broadcasts its local tx.
2753 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2754 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2755 // PaymentSent event).
2757 let chanmon_cfgs = create_chanmon_cfgs(3);
2758 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2759 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2760 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2762 // Create some initial channels
2763 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2764 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2766 // Rebalance the network a bit by relaying one payment through all the channels...
2767 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2768 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2770 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2771 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2773 // Broadcast legit commitment tx from C on B's chain
2774 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2775 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2776 assert_eq!(commitment_tx.len(), 1);
2777 check_spends!(commitment_tx[0], chan_2.3);
2778 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2779 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2780 check_added_monitors!(nodes[2], 2);
2781 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2782 assert!(updates.update_add_htlcs.is_empty());
2783 assert!(updates.update_fail_htlcs.is_empty());
2784 assert!(updates.update_fail_malformed_htlcs.is_empty());
2785 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2787 mine_transaction(&nodes[2], &commitment_tx[0]);
2788 check_closed_broadcast!(nodes[2], false);
2789 check_added_monitors!(nodes[2], 1);
2790 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)
2791 assert_eq!(node_txn.len(), 5);
2792 assert_eq!(node_txn[0], node_txn[3]);
2793 assert_eq!(node_txn[1], node_txn[4]);
2794 assert_eq!(node_txn[2], commitment_tx[0]);
2795 check_spends!(node_txn[0], commitment_tx[0]);
2796 check_spends!(node_txn[1], commitment_tx[0]);
2797 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2798 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2799 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2800 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2801 assert_eq!(node_txn[0].lock_time, 0);
2802 assert_eq!(node_txn[1].lock_time, 0);
2804 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2805 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2806 connect_block(&nodes[1], &Block { header, txdata: node_txn}, nodes[1].best_block_info().1 + 1);
2808 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2809 assert_eq!(added_monitors.len(), 1);
2810 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2811 added_monitors.clear();
2813 let events = nodes[1].node.get_and_clear_pending_msg_events();
2815 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2816 assert_eq!(added_monitors.len(), 2);
2817 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2818 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2819 added_monitors.clear();
2821 assert_eq!(events.len(), 2);
2823 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2824 _ => panic!("Unexpected event"),
2827 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, .. } } => {
2828 assert!(update_add_htlcs.is_empty());
2829 assert!(update_fail_htlcs.is_empty());
2830 assert_eq!(update_fulfill_htlcs.len(), 1);
2831 assert!(update_fail_malformed_htlcs.is_empty());
2832 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2834 _ => panic!("Unexpected event"),
2836 macro_rules! check_tx_local_broadcast {
2837 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2838 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2839 assert_eq!(node_txn.len(), 5);
2840 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2841 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2842 check_spends!(node_txn[0], $commitment_tx);
2843 check_spends!(node_txn[1], $commitment_tx);
2844 assert_ne!(node_txn[0].lock_time, 0);
2845 assert_ne!(node_txn[1].lock_time, 0);
2847 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2848 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2849 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2850 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2852 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2853 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2855 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2857 check_spends!(node_txn[2], $chan_tx);
2858 check_spends!(node_txn[3], node_txn[2]);
2859 check_spends!(node_txn[4], node_txn[2]);
2860 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2861 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2862 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2863 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2864 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2865 assert_ne!(node_txn[3].lock_time, 0);
2866 assert_ne!(node_txn[4].lock_time, 0);
2870 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2871 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2872 // timeout-claim of the output that nodes[2] just claimed via success.
2873 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2875 // Broadcast legit commitment tx from A on B's chain
2876 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2877 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2878 check_spends!(commitment_tx[0], chan_1.3);
2879 mine_transaction(&nodes[1], &commitment_tx[0]);
2880 check_closed_broadcast!(nodes[1], false);
2881 check_added_monitors!(nodes[1], 1);
2882 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2883 assert_eq!(node_txn.len(), 4);
2884 check_spends!(node_txn[0], commitment_tx[0]);
2885 assert_eq!(node_txn[0].input.len(), 2);
2886 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2888 assert_eq!(node_txn[0].lock_time, 0);
2889 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2890 check_spends!(node_txn[1], chan_1.3);
2891 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2892 check_spends!(node_txn[2], node_txn[1]);
2893 check_spends!(node_txn[3], node_txn[1]);
2894 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2895 // we already checked the same situation with A.
2897 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2898 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2899 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
2900 check_closed_broadcast!(nodes[0], false);
2901 check_added_monitors!(nodes[0], 1);
2902 let events = nodes[0].node.get_and_clear_pending_events();
2903 assert_eq!(events.len(), 2);
2904 let mut first_claimed = false;
2905 for event in events {
2907 Event::PaymentSent { payment_preimage } => {
2908 if payment_preimage == our_payment_preimage {
2909 assert!(!first_claimed);
2910 first_claimed = true;
2912 assert_eq!(payment_preimage, our_payment_preimage_2);
2915 _ => panic!("Unexpected event"),
2918 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2922 fn test_htlc_on_chain_timeout() {
2923 // Test that in case of a unilateral close onchain, we detect the state of output and
2924 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2925 // broadcasting the right event to other nodes in payment path.
2926 // A ------------------> B ----------------------> C (timeout)
2927 // B's commitment tx C's commitment tx
2929 // B's HTLC timeout tx B's timeout tx
2931 let chanmon_cfgs = create_chanmon_cfgs(3);
2932 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2933 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2934 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2936 // Create some intial channels
2937 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2938 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2940 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2941 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2942 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2944 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2946 // Broadcast legit commitment tx from C on B's chain
2947 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2948 check_spends!(commitment_tx[0], chan_2.3);
2949 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2950 check_added_monitors!(nodes[2], 0);
2951 expect_pending_htlcs_forwardable!(nodes[2]);
2952 check_added_monitors!(nodes[2], 1);
2954 let events = nodes[2].node.get_and_clear_pending_msg_events();
2955 assert_eq!(events.len(), 1);
2957 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, .. } } => {
2958 assert!(update_add_htlcs.is_empty());
2959 assert!(!update_fail_htlcs.is_empty());
2960 assert!(update_fulfill_htlcs.is_empty());
2961 assert!(update_fail_malformed_htlcs.is_empty());
2962 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2964 _ => panic!("Unexpected event"),
2966 mine_transaction(&nodes[2], &commitment_tx[0]);
2967 check_closed_broadcast!(nodes[2], false);
2968 check_added_monitors!(nodes[2], 1);
2969 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2970 assert_eq!(node_txn.len(), 1);
2971 check_spends!(node_txn[0], chan_2.3);
2972 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2974 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2975 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2976 connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
2977 mine_transaction(&nodes[1], &commitment_tx[0]);
2980 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2981 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2982 assert_eq!(node_txn[0], node_txn[3]);
2983 assert_eq!(node_txn[1], node_txn[4]);
2985 check_spends!(node_txn[2], commitment_tx[0]);
2986 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2988 check_spends!(node_txn[0], chan_2.3);
2989 check_spends!(node_txn[1], node_txn[0]);
2990 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2991 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2993 timeout_tx = node_txn[2].clone();
2997 mine_transaction(&nodes[1], &timeout_tx);
2998 check_added_monitors!(nodes[1], 1);
2999 check_closed_broadcast!(nodes[1], false);
3001 // B will rebroadcast a fee-bumped timeout transaction here.
3002 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3003 assert_eq!(node_txn.len(), 1);
3004 check_spends!(node_txn[0], commitment_tx[0]);
3007 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3009 // B will rebroadcast its own holder commitment transaction here...just because
3010 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3011 assert_eq!(node_txn.len(), 1);
3012 check_spends!(node_txn[0], chan_2.3);
3015 expect_pending_htlcs_forwardable!(nodes[1]);
3016 check_added_monitors!(nodes[1], 1);
3017 let events = nodes[1].node.get_and_clear_pending_msg_events();
3018 assert_eq!(events.len(), 1);
3020 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, .. } } => {
3021 assert!(update_add_htlcs.is_empty());
3022 assert!(!update_fail_htlcs.is_empty());
3023 assert!(update_fulfill_htlcs.is_empty());
3024 assert!(update_fail_malformed_htlcs.is_empty());
3025 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3027 _ => panic!("Unexpected event"),
3030 // Broadcast legit commitment tx from B on A's chain
3031 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3032 check_spends!(commitment_tx[0], chan_1.3);
3034 mine_transaction(&nodes[0], &commitment_tx[0]);
3036 check_closed_broadcast!(nodes[0], false);
3037 check_added_monitors!(nodes[0], 1);
3038 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3039 assert_eq!(node_txn.len(), 3);
3040 check_spends!(node_txn[0], commitment_tx[0]);
3041 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3042 check_spends!(node_txn[1], chan_1.3);
3043 check_spends!(node_txn[2], node_txn[1]);
3044 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3045 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3049 fn test_simple_commitment_revoked_fail_backward() {
3050 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3051 // and fail backward accordingly.
3053 let chanmon_cfgs = create_chanmon_cfgs(3);
3054 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3055 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3056 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3058 // Create some initial channels
3059 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3060 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3062 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3063 // Get the will-be-revoked local txn from nodes[2]
3064 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3065 // Revoke the old state
3066 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3068 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3070 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3071 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3072 check_added_monitors!(nodes[1], 1);
3073 check_closed_broadcast!(nodes[1], false);
3075 expect_pending_htlcs_forwardable!(nodes[1]);
3076 check_added_monitors!(nodes[1], 1);
3077 let events = nodes[1].node.get_and_clear_pending_msg_events();
3078 assert_eq!(events.len(), 1);
3080 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, .. } } => {
3081 assert!(update_add_htlcs.is_empty());
3082 assert_eq!(update_fail_htlcs.len(), 1);
3083 assert!(update_fulfill_htlcs.is_empty());
3084 assert!(update_fail_malformed_htlcs.is_empty());
3085 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3087 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3088 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3090 let events = nodes[0].node.get_and_clear_pending_msg_events();
3091 assert_eq!(events.len(), 1);
3093 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3094 _ => panic!("Unexpected event"),
3096 expect_payment_failed!(nodes[0], payment_hash, false);
3098 _ => panic!("Unexpected event"),
3102 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3103 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3104 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3105 // commitment transaction anymore.
3106 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3107 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3108 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3109 // technically disallowed and we should probably handle it reasonably.
3110 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3111 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3113 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3114 // commitment_signed (implying it will be in the latest remote commitment transaction).
3115 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3116 // and once they revoke the previous commitment transaction (allowing us to send a new
3117 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3118 let chanmon_cfgs = create_chanmon_cfgs(3);
3119 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3120 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3121 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3123 // Create some initial channels
3124 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3125 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3127 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3128 // Get the will-be-revoked local txn from nodes[2]
3129 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3130 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3131 // Revoke the old state
3132 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3134 let value = if use_dust {
3135 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3136 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3137 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3140 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3141 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3142 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3144 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3145 expect_pending_htlcs_forwardable!(nodes[2]);
3146 check_added_monitors!(nodes[2], 1);
3147 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3148 assert!(updates.update_add_htlcs.is_empty());
3149 assert!(updates.update_fulfill_htlcs.is_empty());
3150 assert!(updates.update_fail_malformed_htlcs.is_empty());
3151 assert_eq!(updates.update_fail_htlcs.len(), 1);
3152 assert!(updates.update_fee.is_none());
3153 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3154 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3155 // Drop the last RAA from 3 -> 2
3157 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3158 expect_pending_htlcs_forwardable!(nodes[2]);
3159 check_added_monitors!(nodes[2], 1);
3160 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3161 assert!(updates.update_add_htlcs.is_empty());
3162 assert!(updates.update_fulfill_htlcs.is_empty());
3163 assert!(updates.update_fail_malformed_htlcs.is_empty());
3164 assert_eq!(updates.update_fail_htlcs.len(), 1);
3165 assert!(updates.update_fee.is_none());
3166 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3167 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3168 check_added_monitors!(nodes[1], 1);
3169 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3170 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3171 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3172 check_added_monitors!(nodes[2], 1);
3174 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3175 expect_pending_htlcs_forwardable!(nodes[2]);
3176 check_added_monitors!(nodes[2], 1);
3177 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3178 assert!(updates.update_add_htlcs.is_empty());
3179 assert!(updates.update_fulfill_htlcs.is_empty());
3180 assert!(updates.update_fail_malformed_htlcs.is_empty());
3181 assert_eq!(updates.update_fail_htlcs.len(), 1);
3182 assert!(updates.update_fee.is_none());
3183 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3184 // At this point first_payment_hash has dropped out of the latest two commitment
3185 // transactions that nodes[1] is tracking...
3186 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3187 check_added_monitors!(nodes[1], 1);
3188 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3189 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3190 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3191 check_added_monitors!(nodes[2], 1);
3193 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3194 // on nodes[2]'s RAA.
3195 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3196 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3197 let logger = test_utils::TestLogger::new();
3198 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();
3199 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3200 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3201 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3202 check_added_monitors!(nodes[1], 0);
3205 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3206 // One monitor for the new revocation preimage, no second on as we won't generate a new
3207 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3208 check_added_monitors!(nodes[1], 1);
3209 let events = nodes[1].node.get_and_clear_pending_events();
3210 assert_eq!(events.len(), 1);
3212 Event::PendingHTLCsForwardable { .. } => { },
3213 _ => panic!("Unexpected event"),
3215 // Deliberately don't process the pending fail-back so they all fail back at once after
3216 // block connection just like the !deliver_bs_raa case
3219 let mut failed_htlcs = HashSet::new();
3220 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3222 mine_transaction(&nodes[1], &revoked_local_txn[0]);
3223 check_added_monitors!(nodes[1], 1);
3224 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3226 let events = nodes[1].node.get_and_clear_pending_events();
3227 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3229 Event::PaymentFailed { ref payment_hash, .. } => {
3230 assert_eq!(*payment_hash, fourth_payment_hash);
3232 _ => panic!("Unexpected event"),
3234 if !deliver_bs_raa {
3236 Event::PendingHTLCsForwardable { .. } => { },
3237 _ => panic!("Unexpected event"),
3240 nodes[1].node.process_pending_htlc_forwards();
3241 check_added_monitors!(nodes[1], 1);
3243 let events = nodes[1].node.get_and_clear_pending_msg_events();
3244 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3245 match events[if deliver_bs_raa { 1 } else { 0 }] {
3246 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3247 _ => panic!("Unexpected event"),
3251 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, .. } } => {
3252 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3253 assert_eq!(update_add_htlcs.len(), 1);
3254 assert!(update_fulfill_htlcs.is_empty());
3255 assert!(update_fail_htlcs.is_empty());
3256 assert!(update_fail_malformed_htlcs.is_empty());
3258 _ => panic!("Unexpected event"),
3261 match events[if deliver_bs_raa { 2 } else { 1 }] {
3262 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, .. } } => {
3263 assert!(update_add_htlcs.is_empty());
3264 assert_eq!(update_fail_htlcs.len(), 3);
3265 assert!(update_fulfill_htlcs.is_empty());
3266 assert!(update_fail_malformed_htlcs.is_empty());
3267 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3269 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3270 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3271 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3273 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3275 let events = nodes[0].node.get_and_clear_pending_msg_events();
3276 // If we delivered B's RAA we got an unknown preimage error, not something
3277 // that we should update our routing table for.
3278 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3279 for event in events {
3281 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3282 _ => panic!("Unexpected event"),
3285 let events = nodes[0].node.get_and_clear_pending_events();
3286 assert_eq!(events.len(), 3);
3288 Event::PaymentFailed { ref payment_hash, .. } => {
3289 assert!(failed_htlcs.insert(payment_hash.0));
3291 _ => panic!("Unexpected event"),
3294 Event::PaymentFailed { ref payment_hash, .. } => {
3295 assert!(failed_htlcs.insert(payment_hash.0));
3297 _ => panic!("Unexpected event"),
3300 Event::PaymentFailed { ref payment_hash, .. } => {
3301 assert!(failed_htlcs.insert(payment_hash.0));
3303 _ => panic!("Unexpected event"),
3306 _ => panic!("Unexpected event"),
3309 assert!(failed_htlcs.contains(&first_payment_hash.0));
3310 assert!(failed_htlcs.contains(&second_payment_hash.0));
3311 assert!(failed_htlcs.contains(&third_payment_hash.0));
3315 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3316 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3317 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3318 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3319 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3323 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3324 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3325 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3326 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3327 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3331 fn fail_backward_pending_htlc_upon_channel_failure() {
3332 let chanmon_cfgs = create_chanmon_cfgs(2);
3333 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3334 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3335 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3336 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3337 let logger = test_utils::TestLogger::new();
3339 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3341 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3342 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3343 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();
3344 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3345 check_added_monitors!(nodes[0], 1);
3347 let payment_event = {
3348 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3349 assert_eq!(events.len(), 1);
3350 SendEvent::from_event(events.remove(0))
3352 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3353 assert_eq!(payment_event.msgs.len(), 1);
3356 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3357 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3359 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3360 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();
3361 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3362 check_added_monitors!(nodes[0], 0);
3364 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3367 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3369 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3371 let secp_ctx = Secp256k1::new();
3372 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3373 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3374 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3375 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();
3376 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3377 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3378 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3380 // Send a 0-msat update_add_htlc to fail the channel.
3381 let update_add_htlc = msgs::UpdateAddHTLC {
3387 onion_routing_packet,
3389 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3392 // Check that Alice fails backward the pending HTLC from the second payment.
3393 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3394 check_closed_broadcast!(nodes[0], true);
3395 check_added_monitors!(nodes[0], 1);
3399 fn test_htlc_ignore_latest_remote_commitment() {
3400 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3401 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3402 let chanmon_cfgs = create_chanmon_cfgs(2);
3403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3405 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3406 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3408 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3409 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3410 check_closed_broadcast!(nodes[0], false);
3411 check_added_monitors!(nodes[0], 1);
3413 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3414 assert_eq!(node_txn.len(), 2);
3416 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3417 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, nodes[1].best_block_info().1 + 1);
3418 check_closed_broadcast!(nodes[1], false);
3419 check_added_monitors!(nodes[1], 1);
3421 // Duplicate the connect_block call since this may happen due to other listeners
3422 // registering new transactions
3423 header.prev_blockhash = header.block_hash();
3424 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, nodes[1].best_block_info().1 + 1);
3428 fn test_force_close_fail_back() {
3429 // Check which HTLCs are failed-backwards on channel force-closure
3430 let chanmon_cfgs = create_chanmon_cfgs(3);
3431 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3432 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3433 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3434 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3435 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3436 let logger = test_utils::TestLogger::new();
3438 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3440 let mut payment_event = {
3441 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3442 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();
3443 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3444 check_added_monitors!(nodes[0], 1);
3446 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3447 assert_eq!(events.len(), 1);
3448 SendEvent::from_event(events.remove(0))
3451 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3452 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3454 expect_pending_htlcs_forwardable!(nodes[1]);
3456 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3457 assert_eq!(events_2.len(), 1);
3458 payment_event = SendEvent::from_event(events_2.remove(0));
3459 assert_eq!(payment_event.msgs.len(), 1);
3461 check_added_monitors!(nodes[1], 1);
3462 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3463 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3464 check_added_monitors!(nodes[2], 1);
3465 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3467 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3468 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3469 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3471 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3472 check_closed_broadcast!(nodes[2], false);
3473 check_added_monitors!(nodes[2], 1);
3475 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3476 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3477 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3478 // back to nodes[1] upon timeout otherwise.
3479 assert_eq!(node_txn.len(), 1);
3483 mine_transaction(&nodes[1], &tx);
3485 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3486 check_closed_broadcast!(nodes[1], false);
3487 check_added_monitors!(nodes[1], 1);
3489 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3491 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3492 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3493 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3495 mine_transaction(&nodes[2], &tx);
3496 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3497 assert_eq!(node_txn.len(), 1);
3498 assert_eq!(node_txn[0].input.len(), 1);
3499 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3500 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3501 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3503 check_spends!(node_txn[0], tx);
3507 fn test_simple_peer_disconnect() {
3508 // Test that we can reconnect when there are no lost messages
3509 let chanmon_cfgs = create_chanmon_cfgs(3);
3510 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3511 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3512 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3513 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3514 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3516 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3517 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3518 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3520 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3521 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3522 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3523 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3525 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3526 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3527 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3529 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3530 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3531 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3532 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3534 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3535 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3537 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3538 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3540 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3542 let events = nodes[0].node.get_and_clear_pending_events();
3543 assert_eq!(events.len(), 2);
3545 Event::PaymentSent { payment_preimage } => {
3546 assert_eq!(payment_preimage, payment_preimage_3);
3548 _ => panic!("Unexpected event"),
3551 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3552 assert_eq!(payment_hash, payment_hash_5);
3553 assert!(rejected_by_dest);
3555 _ => panic!("Unexpected event"),
3559 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3560 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3563 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3564 // Test that we can reconnect when in-flight HTLC updates get dropped
3565 let chanmon_cfgs = create_chanmon_cfgs(2);
3566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3568 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3569 if messages_delivered == 0 {
3570 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3571 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3573 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3576 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3578 let logger = test_utils::TestLogger::new();
3579 let payment_event = {
3580 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3581 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3582 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3583 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3584 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3585 check_added_monitors!(nodes[0], 1);
3587 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3588 assert_eq!(events.len(), 1);
3589 SendEvent::from_event(events.remove(0))
3591 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3593 if messages_delivered < 2 {
3594 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3596 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3597 if messages_delivered >= 3 {
3598 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3599 check_added_monitors!(nodes[1], 1);
3600 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3602 if messages_delivered >= 4 {
3603 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3604 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3605 check_added_monitors!(nodes[0], 1);
3607 if messages_delivered >= 5 {
3608 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3609 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3610 // No commitment_signed so get_event_msg's assert(len == 1) passes
3611 check_added_monitors!(nodes[0], 1);
3613 if messages_delivered >= 6 {
3614 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3615 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3616 check_added_monitors!(nodes[1], 1);
3623 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3624 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3625 if messages_delivered < 3 {
3626 // Even if the funding_locked messages get exchanged, as long as nothing further was
3627 // received on either side, both sides will need to resend them.
3628 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3629 } else if messages_delivered == 3 {
3630 // nodes[0] still wants its RAA + commitment_signed
3631 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3632 } else if messages_delivered == 4 {
3633 // nodes[0] still wants its commitment_signed
3634 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3635 } else if messages_delivered == 5 {
3636 // nodes[1] still wants its final RAA
3637 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3638 } else if messages_delivered == 6 {
3639 // Everything was delivered...
3640 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3643 let events_1 = nodes[1].node.get_and_clear_pending_events();
3644 assert_eq!(events_1.len(), 1);
3646 Event::PendingHTLCsForwardable { .. } => { },
3647 _ => panic!("Unexpected event"),
3650 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3651 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3652 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3654 nodes[1].node.process_pending_htlc_forwards();
3656 let events_2 = nodes[1].node.get_and_clear_pending_events();
3657 assert_eq!(events_2.len(), 1);
3659 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3660 assert_eq!(payment_hash_1, *payment_hash);
3661 assert_eq!(*payment_secret, None);
3662 assert_eq!(amt, 1000000);
3664 _ => panic!("Unexpected event"),
3667 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3668 check_added_monitors!(nodes[1], 1);
3670 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3671 assert_eq!(events_3.len(), 1);
3672 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3673 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3674 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3675 assert!(updates.update_add_htlcs.is_empty());
3676 assert!(updates.update_fail_htlcs.is_empty());
3677 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3678 assert!(updates.update_fail_malformed_htlcs.is_empty());
3679 assert!(updates.update_fee.is_none());
3680 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3682 _ => panic!("Unexpected event"),
3685 if messages_delivered >= 1 {
3686 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3688 let events_4 = nodes[0].node.get_and_clear_pending_events();
3689 assert_eq!(events_4.len(), 1);
3691 Event::PaymentSent { ref payment_preimage } => {
3692 assert_eq!(payment_preimage_1, *payment_preimage);
3694 _ => panic!("Unexpected event"),
3697 if messages_delivered >= 2 {
3698 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3699 check_added_monitors!(nodes[0], 1);
3700 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3702 if messages_delivered >= 3 {
3703 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3704 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3705 check_added_monitors!(nodes[1], 1);
3707 if messages_delivered >= 4 {
3708 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3709 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3710 // No commitment_signed so get_event_msg's assert(len == 1) passes
3711 check_added_monitors!(nodes[1], 1);
3713 if messages_delivered >= 5 {
3714 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3715 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3716 check_added_monitors!(nodes[0], 1);
3723 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3724 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3725 if messages_delivered < 2 {
3726 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3727 //TODO: Deduplicate PaymentSent events, then enable this if:
3728 //if messages_delivered < 1 {
3729 let events_4 = nodes[0].node.get_and_clear_pending_events();
3730 assert_eq!(events_4.len(), 1);
3732 Event::PaymentSent { ref payment_preimage } => {
3733 assert_eq!(payment_preimage_1, *payment_preimage);
3735 _ => panic!("Unexpected event"),
3738 } else if messages_delivered == 2 {
3739 // nodes[0] still wants its RAA + commitment_signed
3740 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3741 } else if messages_delivered == 3 {
3742 // nodes[0] still wants its commitment_signed
3743 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3744 } else if messages_delivered == 4 {
3745 // nodes[1] still wants its final RAA
3746 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3747 } else if messages_delivered == 5 {
3748 // Everything was delivered...
3749 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3752 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3753 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3754 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3756 // Channel should still work fine...
3757 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3758 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3759 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3760 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3761 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3762 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3766 fn test_drop_messages_peer_disconnect_a() {
3767 do_test_drop_messages_peer_disconnect(0);
3768 do_test_drop_messages_peer_disconnect(1);
3769 do_test_drop_messages_peer_disconnect(2);
3770 do_test_drop_messages_peer_disconnect(3);
3774 fn test_drop_messages_peer_disconnect_b() {
3775 do_test_drop_messages_peer_disconnect(4);
3776 do_test_drop_messages_peer_disconnect(5);
3777 do_test_drop_messages_peer_disconnect(6);
3781 fn test_funding_peer_disconnect() {
3782 // Test that we can lock in our funding tx while disconnected
3783 let chanmon_cfgs = create_chanmon_cfgs(2);
3784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3787 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3789 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3790 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3792 confirm_transaction(&nodes[0], &tx);
3793 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3794 assert_eq!(events_1.len(), 1);
3796 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3797 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3799 _ => panic!("Unexpected event"),
3802 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3804 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3805 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3807 confirm_transaction(&nodes[1], &tx);
3808 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3809 assert_eq!(events_2.len(), 2);
3810 let funding_locked = match events_2[0] {
3811 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3812 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3815 _ => panic!("Unexpected event"),
3817 let bs_announcement_sigs = match events_2[1] {
3818 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3819 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3822 _ => panic!("Unexpected event"),
3825 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3827 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3828 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3829 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3830 assert_eq!(events_3.len(), 2);
3831 let as_announcement_sigs = match events_3[0] {
3832 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3833 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3836 _ => panic!("Unexpected event"),
3838 let (as_announcement, as_update) = match events_3[1] {
3839 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3840 (msg.clone(), update_msg.clone())
3842 _ => panic!("Unexpected event"),
3845 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3846 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3847 assert_eq!(events_4.len(), 1);
3848 let (_, bs_update) = match events_4[0] {
3849 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3850 (msg.clone(), update_msg.clone())
3852 _ => panic!("Unexpected event"),
3855 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3856 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3857 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3859 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3860 let logger = test_utils::TestLogger::new();
3861 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();
3862 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3863 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3867 fn test_drop_messages_peer_disconnect_dual_htlc() {
3868 // Test that we can handle reconnecting when both sides of a channel have pending
3869 // commitment_updates when we disconnect.
3870 let chanmon_cfgs = create_chanmon_cfgs(2);
3871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3873 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3874 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3875 let logger = test_utils::TestLogger::new();
3877 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3879 // Now try to send a second payment which will fail to send
3880 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3881 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3882 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();
3883 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3884 check_added_monitors!(nodes[0], 1);
3886 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3887 assert_eq!(events_1.len(), 1);
3889 MessageSendEvent::UpdateHTLCs { .. } => {},
3890 _ => panic!("Unexpected event"),
3893 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3894 check_added_monitors!(nodes[1], 1);
3896 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3897 assert_eq!(events_2.len(), 1);
3899 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 } } => {
3900 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3901 assert!(update_add_htlcs.is_empty());
3902 assert_eq!(update_fulfill_htlcs.len(), 1);
3903 assert!(update_fail_htlcs.is_empty());
3904 assert!(update_fail_malformed_htlcs.is_empty());
3905 assert!(update_fee.is_none());
3907 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3908 let events_3 = nodes[0].node.get_and_clear_pending_events();
3909 assert_eq!(events_3.len(), 1);
3911 Event::PaymentSent { ref payment_preimage } => {
3912 assert_eq!(*payment_preimage, payment_preimage_1);
3914 _ => panic!("Unexpected event"),
3917 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3918 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3919 // No commitment_signed so get_event_msg's assert(len == 1) passes
3920 check_added_monitors!(nodes[0], 1);
3922 _ => panic!("Unexpected event"),
3925 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3926 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3928 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3929 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3930 assert_eq!(reestablish_1.len(), 1);
3931 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3932 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3933 assert_eq!(reestablish_2.len(), 1);
3935 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3936 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3937 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3938 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3940 assert!(as_resp.0.is_none());
3941 assert!(bs_resp.0.is_none());
3943 assert!(bs_resp.1.is_none());
3944 assert!(bs_resp.2.is_none());
3946 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3948 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3949 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3950 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3951 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3952 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3954 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3955 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3956 // No commitment_signed so get_event_msg's assert(len == 1) passes
3957 check_added_monitors!(nodes[1], 1);
3959 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3960 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3961 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3962 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3963 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3964 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3965 assert!(bs_second_commitment_signed.update_fee.is_none());
3966 check_added_monitors!(nodes[1], 1);
3968 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3969 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3970 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3971 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3972 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3973 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3974 assert!(as_commitment_signed.update_fee.is_none());
3975 check_added_monitors!(nodes[0], 1);
3977 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3978 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3979 // No commitment_signed so get_event_msg's assert(len == 1) passes
3980 check_added_monitors!(nodes[0], 1);
3982 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3983 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3984 // No commitment_signed so get_event_msg's assert(len == 1) passes
3985 check_added_monitors!(nodes[1], 1);
3987 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3988 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3989 check_added_monitors!(nodes[1], 1);
3991 expect_pending_htlcs_forwardable!(nodes[1]);
3993 let events_5 = nodes[1].node.get_and_clear_pending_events();
3994 assert_eq!(events_5.len(), 1);
3996 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3997 assert_eq!(payment_hash_2, *payment_hash);
3998 assert_eq!(*payment_secret, None);
4000 _ => panic!("Unexpected event"),
4003 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4004 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4005 check_added_monitors!(nodes[0], 1);
4007 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4010 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4011 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4012 // to avoid our counterparty failing the channel.
4013 let chanmon_cfgs = create_chanmon_cfgs(2);
4014 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4015 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4016 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4018 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4019 let logger = test_utils::TestLogger::new();
4021 let our_payment_hash = if send_partial_mpp {
4022 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4023 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();
4024 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4025 let payment_secret = PaymentSecret([0xdb; 32]);
4026 // Use the utility function send_payment_along_path to send the payment with MPP data which
4027 // indicates there are more HTLCs coming.
4028 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.
4029 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4030 check_added_monitors!(nodes[0], 1);
4031 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4032 assert_eq!(events.len(), 1);
4033 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4034 // hop should *not* yet generate any PaymentReceived event(s).
4035 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4038 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4041 let mut block = Block {
4042 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4045 connect_block(&nodes[0], &block, CHAN_CONFIRM_DEPTH + 1);
4046 connect_block(&nodes[1], &block, CHAN_CONFIRM_DEPTH + 1);
4047 for i in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4048 block.header.prev_blockhash = block.block_hash();
4049 connect_block(&nodes[0], &block, i);
4050 connect_block(&nodes[1], &block, i);
4053 expect_pending_htlcs_forwardable!(nodes[1]);
4055 check_added_monitors!(nodes[1], 1);
4056 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4057 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4058 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4059 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4060 assert!(htlc_timeout_updates.update_fee.is_none());
4062 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4063 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4064 // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4065 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4066 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4067 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4071 fn test_htlc_timeout() {
4072 do_test_htlc_timeout(true);
4073 do_test_htlc_timeout(false);
4076 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4077 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4078 let chanmon_cfgs = create_chanmon_cfgs(3);
4079 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4080 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4081 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4082 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4083 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4085 // Make sure all nodes are at the same starting height
4086 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4087 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4088 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4090 let logger = test_utils::TestLogger::new();
4092 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4093 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4095 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4096 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();
4097 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4099 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4100 check_added_monitors!(nodes[1], 1);
4102 // Now attempt to route a second payment, which should be placed in the holding cell
4103 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4105 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4106 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();
4107 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4108 check_added_monitors!(nodes[0], 1);
4109 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4110 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4111 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4112 expect_pending_htlcs_forwardable!(nodes[1]);
4113 check_added_monitors!(nodes[1], 0);
4115 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4116 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();
4117 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4118 check_added_monitors!(nodes[1], 0);
4121 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4122 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4123 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4124 connect_blocks(&nodes[1], 1);
4127 expect_pending_htlcs_forwardable!(nodes[1]);
4128 check_added_monitors!(nodes[1], 1);
4129 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4130 assert_eq!(fail_commit.len(), 1);
4131 match fail_commit[0] {
4132 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4133 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4134 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4136 _ => unreachable!(),
4138 expect_payment_failed!(nodes[0], second_payment_hash, false);
4139 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4141 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4142 _ => panic!("Unexpected event"),
4145 panic!("Unexpected event");
4148 expect_payment_failed!(nodes[1], second_payment_hash, true);
4153 fn test_holding_cell_htlc_add_timeouts() {
4154 do_test_holding_cell_htlc_add_timeouts(false);
4155 do_test_holding_cell_htlc_add_timeouts(true);
4159 fn test_invalid_channel_announcement() {
4160 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4161 let secp_ctx = Secp256k1::new();
4162 let chanmon_cfgs = create_chanmon_cfgs(2);
4163 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4164 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4165 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4167 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4169 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4170 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4171 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4172 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4174 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 } );
4176 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4177 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4179 let as_network_key = nodes[0].node.get_our_node_id();
4180 let bs_network_key = nodes[1].node.get_our_node_id();
4182 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4184 let mut chan_announcement;
4186 macro_rules! dummy_unsigned_msg {
4188 msgs::UnsignedChannelAnnouncement {
4189 features: ChannelFeatures::known(),
4190 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4191 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4192 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4193 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4194 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4195 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4196 excess_data: Vec::new(),
4201 macro_rules! sign_msg {
4202 ($unsigned_msg: expr) => {
4203 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4204 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4205 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4206 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4207 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4208 chan_announcement = msgs::ChannelAnnouncement {
4209 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4210 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4211 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4212 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4213 contents: $unsigned_msg
4218 let unsigned_msg = dummy_unsigned_msg!();
4219 sign_msg!(unsigned_msg);
4220 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4221 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 } );
4223 // Configured with Network::Testnet
4224 let mut unsigned_msg = dummy_unsigned_msg!();
4225 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4226 sign_msg!(unsigned_msg);
4227 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4229 let mut unsigned_msg = dummy_unsigned_msg!();
4230 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4231 sign_msg!(unsigned_msg);
4232 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4236 fn test_no_txn_manager_serialize_deserialize() {
4237 let chanmon_cfgs = create_chanmon_cfgs(2);
4238 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4239 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4240 let logger: test_utils::TestLogger;
4241 let fee_estimator: test_utils::TestFeeEstimator;
4242 let persister: test_utils::TestPersister;
4243 let new_chain_monitor: test_utils::TestChainMonitor;
4244 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4245 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4247 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4249 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4251 let nodes_0_serialized = nodes[0].node.encode();
4252 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4253 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4255 logger = test_utils::TestLogger::new();
4256 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4257 persister = test_utils::TestPersister::new();
4258 let keys_manager = &chanmon_cfgs[0].keys_manager;
4259 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4260 nodes[0].chain_monitor = &new_chain_monitor;
4261 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4262 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4263 &mut chan_0_monitor_read, keys_manager).unwrap();
4264 assert!(chan_0_monitor_read.is_empty());
4266 let mut nodes_0_read = &nodes_0_serialized[..];
4267 let config = UserConfig::default();
4268 let (_, nodes_0_deserialized_tmp) = {
4269 let mut channel_monitors = HashMap::new();
4270 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4271 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4272 default_config: config,
4274 fee_estimator: &fee_estimator,
4275 chain_monitor: nodes[0].chain_monitor,
4276 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4281 nodes_0_deserialized = nodes_0_deserialized_tmp;
4282 assert!(nodes_0_read.is_empty());
4284 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4285 nodes[0].node = &nodes_0_deserialized;
4286 assert_eq!(nodes[0].node.list_channels().len(), 1);
4287 check_added_monitors!(nodes[0], 1);
4289 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4290 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4291 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4292 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4294 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4295 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4296 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4297 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4299 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4300 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4301 for node in nodes.iter() {
4302 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4303 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4304 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4307 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4311 fn test_manager_serialize_deserialize_events() {
4312 // This test makes sure the events field in ChannelManager survives de/serialization
4313 let chanmon_cfgs = create_chanmon_cfgs(2);
4314 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4315 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4316 let fee_estimator: test_utils::TestFeeEstimator;
4317 let persister: test_utils::TestPersister;
4318 let logger: test_utils::TestLogger;
4319 let new_chain_monitor: test_utils::TestChainMonitor;
4320 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4321 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4323 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4324 let channel_value = 100000;
4325 let push_msat = 10001;
4326 let a_flags = InitFeatures::known();
4327 let b_flags = InitFeatures::known();
4328 let node_a = nodes.remove(0);
4329 let node_b = nodes.remove(0);
4330 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4331 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()));
4332 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()));
4334 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4336 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4337 check_added_monitors!(node_a, 0);
4339 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()));
4341 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4342 assert_eq!(added_monitors.len(), 1);
4343 assert_eq!(added_monitors[0].0, funding_output);
4344 added_monitors.clear();
4347 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()));
4349 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4350 assert_eq!(added_monitors.len(), 1);
4351 assert_eq!(added_monitors[0].0, funding_output);
4352 added_monitors.clear();
4354 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4359 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4360 let nodes_0_serialized = nodes[0].node.encode();
4361 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4362 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4364 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4365 logger = test_utils::TestLogger::new();
4366 persister = test_utils::TestPersister::new();
4367 let keys_manager = &chanmon_cfgs[0].keys_manager;
4368 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4369 nodes[0].chain_monitor = &new_chain_monitor;
4370 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4371 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4372 &mut chan_0_monitor_read, keys_manager).unwrap();
4373 assert!(chan_0_monitor_read.is_empty());
4375 let mut nodes_0_read = &nodes_0_serialized[..];
4376 let config = UserConfig::default();
4377 let (_, nodes_0_deserialized_tmp) = {
4378 let mut channel_monitors = HashMap::new();
4379 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4380 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4381 default_config: config,
4383 fee_estimator: &fee_estimator,
4384 chain_monitor: nodes[0].chain_monitor,
4385 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4390 nodes_0_deserialized = nodes_0_deserialized_tmp;
4391 assert!(nodes_0_read.is_empty());
4393 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4395 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4396 nodes[0].node = &nodes_0_deserialized;
4398 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4399 let events_4 = nodes[0].node.get_and_clear_pending_events();
4400 assert_eq!(events_4.len(), 1);
4402 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4403 assert_eq!(user_channel_id, 42);
4404 assert_eq!(*funding_txo, funding_output);
4406 _ => panic!("Unexpected event"),
4409 // Make sure the channel is functioning as though the de/serialization never happened
4410 assert_eq!(nodes[0].node.list_channels().len(), 1);
4411 check_added_monitors!(nodes[0], 1);
4413 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4414 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4415 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4416 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4418 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4419 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4420 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4421 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4423 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4424 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4425 for node in nodes.iter() {
4426 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4427 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4428 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4431 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4435 fn test_simple_manager_serialize_deserialize() {
4436 let chanmon_cfgs = create_chanmon_cfgs(2);
4437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4439 let logger: test_utils::TestLogger;
4440 let fee_estimator: test_utils::TestFeeEstimator;
4441 let persister: test_utils::TestPersister;
4442 let new_chain_monitor: test_utils::TestChainMonitor;
4443 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4444 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4445 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4447 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4448 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4450 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4452 let nodes_0_serialized = nodes[0].node.encode();
4453 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4454 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4456 logger = test_utils::TestLogger::new();
4457 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4458 persister = test_utils::TestPersister::new();
4459 let keys_manager = &chanmon_cfgs[0].keys_manager;
4460 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4461 nodes[0].chain_monitor = &new_chain_monitor;
4462 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4463 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4464 &mut chan_0_monitor_read, keys_manager).unwrap();
4465 assert!(chan_0_monitor_read.is_empty());
4467 let mut nodes_0_read = &nodes_0_serialized[..];
4468 let (_, nodes_0_deserialized_tmp) = {
4469 let mut channel_monitors = HashMap::new();
4470 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4471 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4472 default_config: UserConfig::default(),
4474 fee_estimator: &fee_estimator,
4475 chain_monitor: nodes[0].chain_monitor,
4476 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4481 nodes_0_deserialized = nodes_0_deserialized_tmp;
4482 assert!(nodes_0_read.is_empty());
4484 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4485 nodes[0].node = &nodes_0_deserialized;
4486 check_added_monitors!(nodes[0], 1);
4488 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4490 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4491 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4495 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4496 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4497 let chanmon_cfgs = create_chanmon_cfgs(4);
4498 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4499 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4500 let logger: test_utils::TestLogger;
4501 let fee_estimator: test_utils::TestFeeEstimator;
4502 let persister: test_utils::TestPersister;
4503 let new_chain_monitor: test_utils::TestChainMonitor;
4504 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4505 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4506 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4507 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4508 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4510 let mut node_0_stale_monitors_serialized = Vec::new();
4511 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4512 let mut writer = test_utils::TestVecWriter(Vec::new());
4513 monitor.1.write(&mut writer).unwrap();
4514 node_0_stale_monitors_serialized.push(writer.0);
4517 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4519 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4520 let nodes_0_serialized = nodes[0].node.encode();
4522 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4523 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4524 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4525 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4527 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4529 let mut node_0_monitors_serialized = Vec::new();
4530 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4531 let mut writer = test_utils::TestVecWriter(Vec::new());
4532 monitor.1.write(&mut writer).unwrap();
4533 node_0_monitors_serialized.push(writer.0);
4536 logger = test_utils::TestLogger::new();
4537 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4538 persister = test_utils::TestPersister::new();
4539 let keys_manager = &chanmon_cfgs[0].keys_manager;
4540 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4541 nodes[0].chain_monitor = &new_chain_monitor;
4544 let mut node_0_stale_monitors = Vec::new();
4545 for serialized in node_0_stale_monitors_serialized.iter() {
4546 let mut read = &serialized[..];
4547 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4548 assert!(read.is_empty());
4549 node_0_stale_monitors.push(monitor);
4552 let mut node_0_monitors = Vec::new();
4553 for serialized in node_0_monitors_serialized.iter() {
4554 let mut read = &serialized[..];
4555 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4556 assert!(read.is_empty());
4557 node_0_monitors.push(monitor);
4560 let mut nodes_0_read = &nodes_0_serialized[..];
4561 if let Err(msgs::DecodeError::InvalidValue) =
4562 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4563 default_config: UserConfig::default(),
4565 fee_estimator: &fee_estimator,
4566 chain_monitor: nodes[0].chain_monitor,
4567 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4569 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4571 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4574 let mut nodes_0_read = &nodes_0_serialized[..];
4575 let (_, nodes_0_deserialized_tmp) =
4576 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4577 default_config: UserConfig::default(),
4579 fee_estimator: &fee_estimator,
4580 chain_monitor: nodes[0].chain_monitor,
4581 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4583 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4585 nodes_0_deserialized = nodes_0_deserialized_tmp;
4586 assert!(nodes_0_read.is_empty());
4588 { // Channel close should result in a commitment tx and an HTLC tx
4589 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4590 assert_eq!(txn.len(), 2);
4591 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4592 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4595 for monitor in node_0_monitors.drain(..) {
4596 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4597 check_added_monitors!(nodes[0], 1);
4599 nodes[0].node = &nodes_0_deserialized;
4601 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4602 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4603 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4604 //... and we can even still claim the payment!
4605 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4607 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4608 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4609 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4610 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4611 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4612 assert_eq!(msg_events.len(), 1);
4613 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4615 &ErrorAction::SendErrorMessage { ref msg } => {
4616 assert_eq!(msg.channel_id, channel_id);
4618 _ => panic!("Unexpected event!"),
4623 macro_rules! check_spendable_outputs {
4624 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4626 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4627 let mut txn = Vec::new();
4628 let mut all_outputs = Vec::new();
4629 let secp_ctx = Secp256k1::new();
4630 for event in events.drain(..) {
4632 Event::SpendableOutputs { mut outputs } => {
4633 for outp in outputs.drain(..) {
4634 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4635 all_outputs.push(outp);
4638 _ => panic!("Unexpected event"),
4641 if all_outputs.len() > 1 {
4642 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) {
4652 fn test_claim_sizeable_push_msat() {
4653 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4654 let chanmon_cfgs = create_chanmon_cfgs(2);
4655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4657 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4659 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4660 nodes[1].node.force_close_channel(&chan.2).unwrap();
4661 check_closed_broadcast!(nodes[1], false);
4662 check_added_monitors!(nodes[1], 1);
4663 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4664 assert_eq!(node_txn.len(), 1);
4665 check_spends!(node_txn[0], chan.3);
4666 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
4668 mine_transaction(&nodes[1], &node_txn[0]);
4669 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4671 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4672 assert_eq!(spend_txn.len(), 1);
4673 check_spends!(spend_txn[0], node_txn[0]);
4677 fn test_claim_on_remote_sizeable_push_msat() {
4678 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4679 // to_remote output is encumbered by a P2WPKH
4680 let chanmon_cfgs = create_chanmon_cfgs(2);
4681 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4682 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4683 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4685 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4686 nodes[0].node.force_close_channel(&chan.2).unwrap();
4687 check_closed_broadcast!(nodes[0], false);
4688 check_added_monitors!(nodes[0], 1);
4690 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4691 assert_eq!(node_txn.len(), 1);
4692 check_spends!(node_txn[0], chan.3);
4693 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
4695 mine_transaction(&nodes[1], &node_txn[0]);
4696 check_closed_broadcast!(nodes[1], false);
4697 check_added_monitors!(nodes[1], 1);
4698 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4700 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4701 assert_eq!(spend_txn.len(), 1);
4702 check_spends!(spend_txn[0], node_txn[0]);
4706 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4707 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4708 // to_remote output is encumbered by a P2WPKH
4710 let chanmon_cfgs = create_chanmon_cfgs(2);
4711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4715 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4716 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4717 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4718 assert_eq!(revoked_local_txn[0].input.len(), 1);
4719 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4721 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4722 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4723 check_closed_broadcast!(nodes[1], false);
4724 check_added_monitors!(nodes[1], 1);
4726 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4727 mine_transaction(&nodes[1], &node_txn[0]);
4728 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4730 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4731 assert_eq!(spend_txn.len(), 3);
4732 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4733 check_spends!(spend_txn[1], node_txn[0]);
4734 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4738 fn test_static_spendable_outputs_preimage_tx() {
4739 let chanmon_cfgs = create_chanmon_cfgs(2);
4740 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4741 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4742 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4744 // Create some initial channels
4745 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4747 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4749 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4750 assert_eq!(commitment_tx[0].input.len(), 1);
4751 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4753 // Settle A's commitment tx on B's chain
4754 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4755 check_added_monitors!(nodes[1], 1);
4756 mine_transaction(&nodes[1], &commitment_tx[0]);
4757 check_added_monitors!(nodes[1], 1);
4758 let events = nodes[1].node.get_and_clear_pending_msg_events();
4760 MessageSendEvent::UpdateHTLCs { .. } => {},
4761 _ => panic!("Unexpected event"),
4764 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4765 _ => panic!("Unexepected event"),
4768 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4769 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4770 assert_eq!(node_txn.len(), 3);
4771 check_spends!(node_txn[0], commitment_tx[0]);
4772 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4773 check_spends!(node_txn[1], chan_1.3);
4774 check_spends!(node_txn[2], node_txn[1]);
4776 mine_transaction(&nodes[1], &node_txn[0]);
4777 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4779 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4780 assert_eq!(spend_txn.len(), 1);
4781 check_spends!(spend_txn[0], node_txn[0]);
4785 fn test_static_spendable_outputs_timeout_tx() {
4786 let chanmon_cfgs = create_chanmon_cfgs(2);
4787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4789 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4791 // Create some initial channels
4792 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4794 // Rebalance the network a bit by relaying one payment through all the channels ...
4795 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4797 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4799 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4800 assert_eq!(commitment_tx[0].input.len(), 1);
4801 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4803 // Settle A's commitment tx on B' chain
4804 mine_transaction(&nodes[1], &commitment_tx[0]);
4805 check_added_monitors!(nodes[1], 1);
4806 let events = nodes[1].node.get_and_clear_pending_msg_events();
4808 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4809 _ => panic!("Unexpected event"),
4812 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4813 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4814 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4815 check_spends!(node_txn[0], commitment_tx[0].clone());
4816 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4817 check_spends!(node_txn[1], chan_1.3.clone());
4818 check_spends!(node_txn[2], node_txn[1]);
4820 mine_transaction(&nodes[1], &node_txn[0]);
4821 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4822 expect_payment_failed!(nodes[1], our_payment_hash, true);
4824 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4825 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4826 check_spends!(spend_txn[0], commitment_tx[0]);
4827 check_spends!(spend_txn[1], node_txn[0]);
4828 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4832 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4833 let chanmon_cfgs = create_chanmon_cfgs(2);
4834 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4835 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4836 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4838 // Create some initial channels
4839 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4841 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4842 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4843 assert_eq!(revoked_local_txn[0].input.len(), 1);
4844 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4846 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4848 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4849 check_closed_broadcast!(nodes[1], false);
4850 check_added_monitors!(nodes[1], 1);
4852 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4853 assert_eq!(node_txn.len(), 2);
4854 assert_eq!(node_txn[0].input.len(), 2);
4855 check_spends!(node_txn[0], revoked_local_txn[0]);
4857 mine_transaction(&nodes[1], &node_txn[0]);
4858 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4860 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4861 assert_eq!(spend_txn.len(), 1);
4862 check_spends!(spend_txn[0], node_txn[0]);
4866 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4867 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4868 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4869 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4870 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4871 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4873 // Create some initial channels
4874 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4876 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4877 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4878 assert_eq!(revoked_local_txn[0].input.len(), 1);
4879 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4881 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4883 // A will generate HTLC-Timeout from revoked commitment tx
4884 mine_transaction(&nodes[0], &revoked_local_txn[0]);
4885 check_closed_broadcast!(nodes[0], false);
4886 check_added_monitors!(nodes[0], 1);
4888 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4889 assert_eq!(revoked_htlc_txn.len(), 2);
4890 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4891 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4892 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4893 check_spends!(revoked_htlc_txn[1], chan_1.3);
4895 // B will generate justice tx from A's revoked commitment/HTLC tx
4896 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4897 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, nodes[1].best_block_info().1 + 1);
4898 check_closed_broadcast!(nodes[1], false);
4899 check_added_monitors!(nodes[1], 1);
4901 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4902 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4903 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4904 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4905 // transactions next...
4906 assert_eq!(node_txn[0].input.len(), 3);
4907 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4909 assert_eq!(node_txn[1].input.len(), 2);
4910 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4911 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4912 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4914 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4915 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4918 assert_eq!(node_txn[2].input.len(), 1);
4919 check_spends!(node_txn[2], chan_1.3);
4921 mine_transaction(&nodes[1], &node_txn[1]);
4922 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4924 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4925 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4926 assert_eq!(spend_txn.len(), 1);
4927 assert_eq!(spend_txn[0].input.len(), 1);
4928 check_spends!(spend_txn[0], node_txn[1]);
4932 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4933 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4934 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4939 // Create some initial channels
4940 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4942 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4943 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4944 assert_eq!(revoked_local_txn[0].input.len(), 1);
4945 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4947 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4948 assert_eq!(revoked_local_txn[0].output.len(), 2);
4950 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4952 // B will generate HTLC-Success from revoked commitment tx
4953 mine_transaction(&nodes[1], &revoked_local_txn[0]);
4954 check_closed_broadcast!(nodes[1], false);
4955 check_added_monitors!(nodes[1], 1);
4956 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4958 assert_eq!(revoked_htlc_txn.len(), 2);
4959 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4960 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4961 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4963 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4964 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4965 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4967 // A will generate justice tx from B's revoked commitment/HTLC tx
4968 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4969 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
4970 check_closed_broadcast!(nodes[0], false);
4971 check_added_monitors!(nodes[0], 1);
4973 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4974 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4976 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4977 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4978 // transactions next...
4979 assert_eq!(node_txn[0].input.len(), 2);
4980 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4981 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4982 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4984 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4985 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4988 assert_eq!(node_txn[1].input.len(), 1);
4989 check_spends!(node_txn[1], revoked_htlc_txn[0]);
4991 check_spends!(node_txn[2], chan_1.3);
4993 mine_transaction(&nodes[0], &node_txn[1]);
4994 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4996 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4997 // didn't try to generate any new transactions.
4999 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5000 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5001 assert_eq!(spend_txn.len(), 3);
5002 assert_eq!(spend_txn[0].input.len(), 1);
5003 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5004 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5005 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5006 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5010 fn test_onchain_to_onchain_claim() {
5011 // Test that in case of channel closure, we detect the state of output and claim HTLC
5012 // on downstream peer's remote commitment tx.
5013 // First, have C claim an HTLC against its own latest commitment transaction.
5014 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5016 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5019 let chanmon_cfgs = create_chanmon_cfgs(3);
5020 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5021 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5022 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5024 // Create some initial channels
5025 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5026 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5028 // Rebalance the network a bit by relaying one payment through all the channels ...
5029 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5030 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5032 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5033 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5034 check_spends!(commitment_tx[0], chan_2.3);
5035 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5036 check_added_monitors!(nodes[2], 1);
5037 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5038 assert!(updates.update_add_htlcs.is_empty());
5039 assert!(updates.update_fail_htlcs.is_empty());
5040 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5041 assert!(updates.update_fail_malformed_htlcs.is_empty());
5043 mine_transaction(&nodes[2], &commitment_tx[0]);
5044 check_closed_broadcast!(nodes[2], false);
5045 check_added_monitors!(nodes[2], 1);
5047 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5048 assert_eq!(c_txn.len(), 3);
5049 assert_eq!(c_txn[0], c_txn[2]);
5050 assert_eq!(commitment_tx[0], c_txn[1]);
5051 check_spends!(c_txn[1], chan_2.3);
5052 check_spends!(c_txn[2], c_txn[1]);
5053 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5054 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5055 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5056 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5058 // 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
5059 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5060 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, nodes[1].best_block_info().1 + 1);
5062 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5063 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5064 assert_eq!(b_txn.len(), 3);
5065 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5066 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5067 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5068 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5069 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5070 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5071 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5072 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5073 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5076 check_added_monitors!(nodes[1], 1);
5077 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5078 check_added_monitors!(nodes[1], 1);
5079 match msg_events[0] {
5080 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5081 _ => panic!("Unexpected event"),
5083 match msg_events[1] {
5084 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, .. } } => {
5085 assert!(update_add_htlcs.is_empty());
5086 assert!(update_fail_htlcs.is_empty());
5087 assert_eq!(update_fulfill_htlcs.len(), 1);
5088 assert!(update_fail_malformed_htlcs.is_empty());
5089 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5091 _ => panic!("Unexpected event"),
5093 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5094 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5095 mine_transaction(&nodes[1], &commitment_tx[0]);
5096 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5097 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5098 assert_eq!(b_txn.len(), 3);
5099 check_spends!(b_txn[1], chan_1.3);
5100 check_spends!(b_txn[2], b_txn[1]);
5101 check_spends!(b_txn[0], commitment_tx[0]);
5102 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5103 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5104 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5106 check_closed_broadcast!(nodes[1], false);
5107 check_added_monitors!(nodes[1], 1);
5111 fn test_duplicate_payment_hash_one_failure_one_success() {
5112 // Topology : A --> B --> C
5113 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5114 let chanmon_cfgs = create_chanmon_cfgs(3);
5115 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5116 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5117 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5119 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5120 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5122 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5123 *nodes[0].network_payment_count.borrow_mut() -= 1;
5124 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5126 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5127 assert_eq!(commitment_txn[0].input.len(), 1);
5128 check_spends!(commitment_txn[0], chan_2.3);
5130 mine_transaction(&nodes[1], &commitment_txn[0]);
5131 check_closed_broadcast!(nodes[1], false);
5132 check_added_monitors!(nodes[1], 1);
5134 let htlc_timeout_tx;
5135 { // Extract one of the two HTLC-Timeout transaction
5136 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5137 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5138 assert_eq!(node_txn.len(), 5);
5139 check_spends!(node_txn[0], commitment_txn[0]);
5140 assert_eq!(node_txn[0].input.len(), 1);
5141 check_spends!(node_txn[1], commitment_txn[0]);
5142 assert_eq!(node_txn[1].input.len(), 1);
5143 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5144 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5145 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5146 check_spends!(node_txn[2], chan_2.3);
5147 check_spends!(node_txn[3], node_txn[2]);
5148 check_spends!(node_txn[4], node_txn[2]);
5149 htlc_timeout_tx = node_txn[1].clone();
5152 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5153 mine_transaction(&nodes[2], &commitment_txn[0]);
5154 check_added_monitors!(nodes[2], 3);
5155 let events = nodes[2].node.get_and_clear_pending_msg_events();
5157 MessageSendEvent::UpdateHTLCs { .. } => {},
5158 _ => panic!("Unexpected event"),
5161 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5162 _ => panic!("Unexepected event"),
5164 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5165 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)
5166 check_spends!(htlc_success_txn[2], chan_2.3);
5167 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5168 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5169 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5170 assert_eq!(htlc_success_txn[0].input.len(), 1);
5171 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5172 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5173 assert_eq!(htlc_success_txn[1].input.len(), 1);
5174 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5175 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5176 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5177 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5179 mine_transaction(&nodes[1], &htlc_timeout_tx);
5180 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5181 expect_pending_htlcs_forwardable!(nodes[1]);
5182 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5183 assert!(htlc_updates.update_add_htlcs.is_empty());
5184 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5185 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5186 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5187 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5188 check_added_monitors!(nodes[1], 1);
5190 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5191 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5193 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5194 let events = nodes[0].node.get_and_clear_pending_msg_events();
5195 assert_eq!(events.len(), 1);
5197 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5199 _ => { panic!("Unexpected event"); }
5202 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5204 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5205 mine_transaction(&nodes[1], &htlc_success_txn[0]);
5206 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5207 assert!(updates.update_add_htlcs.is_empty());
5208 assert!(updates.update_fail_htlcs.is_empty());
5209 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5210 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5211 assert!(updates.update_fail_malformed_htlcs.is_empty());
5212 check_added_monitors!(nodes[1], 1);
5214 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5215 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5217 let events = nodes[0].node.get_and_clear_pending_events();
5219 Event::PaymentSent { ref payment_preimage } => {
5220 assert_eq!(*payment_preimage, our_payment_preimage);
5222 _ => panic!("Unexpected event"),
5227 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5228 let chanmon_cfgs = create_chanmon_cfgs(2);
5229 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5230 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5231 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5233 // Create some initial channels
5234 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5236 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5237 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5238 assert_eq!(local_txn.len(), 1);
5239 assert_eq!(local_txn[0].input.len(), 1);
5240 check_spends!(local_txn[0], chan_1.3);
5242 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5243 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5244 check_added_monitors!(nodes[1], 1);
5245 mine_transaction(&nodes[1], &local_txn[0]);
5246 check_added_monitors!(nodes[1], 1);
5247 let events = nodes[1].node.get_and_clear_pending_msg_events();
5249 MessageSendEvent::UpdateHTLCs { .. } => {},
5250 _ => panic!("Unexpected event"),
5253 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5254 _ => panic!("Unexepected event"),
5257 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5258 assert_eq!(node_txn.len(), 3);
5259 assert_eq!(node_txn[0], node_txn[2]);
5260 assert_eq!(node_txn[1], local_txn[0]);
5261 assert_eq!(node_txn[0].input.len(), 1);
5262 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5263 check_spends!(node_txn[0], local_txn[0]);
5267 mine_transaction(&nodes[1], &node_tx);
5268 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5270 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5271 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5272 assert_eq!(spend_txn.len(), 1);
5273 check_spends!(spend_txn[0], node_tx);
5276 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5277 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5278 // unrevoked commitment transaction.
5279 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5280 // a remote RAA before they could be failed backwards (and combinations thereof).
5281 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5282 // use the same payment hashes.
5283 // Thus, we use a six-node network:
5288 // And test where C fails back to A/B when D announces its latest commitment transaction
5289 let chanmon_cfgs = create_chanmon_cfgs(6);
5290 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5291 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5292 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5293 let logger = test_utils::TestLogger::new();
5295 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5296 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5297 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5298 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5299 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5301 // Rebalance and check output sanity...
5302 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5303 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5304 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5306 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5308 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
5310 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
5311 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5312 let our_node_id = &nodes[1].node.get_our_node_id();
5313 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();
5315 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
5317 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
5319 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5321 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5322 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();
5324 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5326 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5329 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5331 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();
5332 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
5335 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
5337 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();
5338 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5340 // Double-check that six of the new HTLC were added
5341 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5342 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5343 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5344 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5346 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5347 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5348 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5349 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5350 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5351 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5352 check_added_monitors!(nodes[4], 0);
5353 expect_pending_htlcs_forwardable!(nodes[4]);
5354 check_added_monitors!(nodes[4], 1);
5356 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5357 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5358 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5359 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5360 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5361 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5363 // Fail 3rd below-dust and 7th above-dust HTLCs
5364 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5365 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5366 check_added_monitors!(nodes[5], 0);
5367 expect_pending_htlcs_forwardable!(nodes[5]);
5368 check_added_monitors!(nodes[5], 1);
5370 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5371 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5372 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5373 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5375 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5377 expect_pending_htlcs_forwardable!(nodes[3]);
5378 check_added_monitors!(nodes[3], 1);
5379 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5380 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5381 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5382 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5383 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5384 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5385 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5386 if deliver_last_raa {
5387 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5389 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5392 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5393 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5394 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5395 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5397 // We now broadcast the latest commitment transaction, which *should* result in failures for
5398 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5399 // the non-broadcast above-dust HTLCs.
5401 // Alternatively, we may broadcast the previous commitment transaction, which should only
5402 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5403 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5405 if announce_latest {
5406 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5408 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5410 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5411 check_closed_broadcast!(nodes[2], false);
5412 expect_pending_htlcs_forwardable!(nodes[2]);
5413 check_added_monitors!(nodes[2], 3);
5415 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5416 assert_eq!(cs_msgs.len(), 2);
5417 let mut a_done = false;
5418 for msg in cs_msgs {
5420 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5421 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5422 // should be failed-backwards here.
5423 let target = if *node_id == nodes[0].node.get_our_node_id() {
5424 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5425 for htlc in &updates.update_fail_htlcs {
5426 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 });
5428 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5433 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5434 for htlc in &updates.update_fail_htlcs {
5435 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5437 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5438 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5441 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5442 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5443 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5444 if announce_latest {
5445 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5446 if *node_id == nodes[0].node.get_our_node_id() {
5447 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5450 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5452 _ => panic!("Unexpected event"),
5456 let as_events = nodes[0].node.get_and_clear_pending_events();
5457 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5458 let mut as_failds = HashSet::new();
5459 for event in as_events.iter() {
5460 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5461 assert!(as_failds.insert(*payment_hash));
5462 if *payment_hash != payment_hash_2 {
5463 assert_eq!(*rejected_by_dest, deliver_last_raa);
5465 assert!(!rejected_by_dest);
5467 } else { panic!("Unexpected event"); }
5469 assert!(as_failds.contains(&payment_hash_1));
5470 assert!(as_failds.contains(&payment_hash_2));
5471 if announce_latest {
5472 assert!(as_failds.contains(&payment_hash_3));
5473 assert!(as_failds.contains(&payment_hash_5));
5475 assert!(as_failds.contains(&payment_hash_6));
5477 let bs_events = nodes[1].node.get_and_clear_pending_events();
5478 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5479 let mut bs_failds = HashSet::new();
5480 for event in bs_events.iter() {
5481 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5482 assert!(bs_failds.insert(*payment_hash));
5483 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5484 assert_eq!(*rejected_by_dest, deliver_last_raa);
5486 assert!(!rejected_by_dest);
5488 } else { panic!("Unexpected event"); }
5490 assert!(bs_failds.contains(&payment_hash_1));
5491 assert!(bs_failds.contains(&payment_hash_2));
5492 if announce_latest {
5493 assert!(bs_failds.contains(&payment_hash_4));
5495 assert!(bs_failds.contains(&payment_hash_5));
5497 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5498 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5499 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5500 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5501 // PaymentFailureNetworkUpdates.
5502 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5503 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5504 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5505 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5506 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5508 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5509 _ => panic!("Unexpected event"),
5515 fn test_fail_backwards_latest_remote_announce_a() {
5516 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5520 fn test_fail_backwards_latest_remote_announce_b() {
5521 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5525 fn test_fail_backwards_previous_remote_announce() {
5526 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5527 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5528 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5532 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5533 let chanmon_cfgs = create_chanmon_cfgs(2);
5534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5536 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5538 // Create some initial channels
5539 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5541 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5542 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5543 assert_eq!(local_txn[0].input.len(), 1);
5544 check_spends!(local_txn[0], chan_1.3);
5546 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5547 mine_transaction(&nodes[0], &local_txn[0]);
5548 check_closed_broadcast!(nodes[0], false);
5549 check_added_monitors!(nodes[0], 1);
5551 let htlc_timeout = {
5552 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5553 assert_eq!(node_txn[0].input.len(), 1);
5554 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5555 check_spends!(node_txn[0], local_txn[0]);
5559 mine_transaction(&nodes[0], &htlc_timeout);
5560 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5561 expect_payment_failed!(nodes[0], our_payment_hash, true);
5563 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5564 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5565 assert_eq!(spend_txn.len(), 3);
5566 check_spends!(spend_txn[0], local_txn[0]);
5567 check_spends!(spend_txn[1], htlc_timeout);
5568 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5572 fn test_key_derivation_params() {
5573 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5574 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5575 // let us re-derive the channel key set to then derive a delayed_payment_key.
5577 let chanmon_cfgs = create_chanmon_cfgs(3);
5579 // We manually create the node configuration to backup the seed.
5580 let seed = [42; 32];
5581 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5582 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);
5583 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 };
5584 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5585 node_cfgs.remove(0);
5586 node_cfgs.insert(0, node);
5588 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5589 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5591 // Create some initial channels
5592 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5594 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5595 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5596 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5598 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5599 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5600 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5601 assert_eq!(local_txn_1[0].input.len(), 1);
5602 check_spends!(local_txn_1[0], chan_1.3);
5604 // We check funding pubkey are unique
5605 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]));
5606 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]));
5607 if from_0_funding_key_0 == from_1_funding_key_0
5608 || from_0_funding_key_0 == from_1_funding_key_1
5609 || from_0_funding_key_1 == from_1_funding_key_0
5610 || from_0_funding_key_1 == from_1_funding_key_1 {
5611 panic!("Funding pubkeys aren't unique");
5614 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5615 mine_transaction(&nodes[0], &local_txn_1[0]);
5616 check_closed_broadcast!(nodes[0], false);
5617 check_added_monitors!(nodes[0], 1);
5619 let htlc_timeout = {
5620 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5621 assert_eq!(node_txn[0].input.len(), 1);
5622 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5623 check_spends!(node_txn[0], local_txn_1[0]);
5627 mine_transaction(&nodes[0], &htlc_timeout);
5628 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5629 expect_payment_failed!(nodes[0], our_payment_hash, true);
5631 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5632 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5633 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5634 assert_eq!(spend_txn.len(), 3);
5635 check_spends!(spend_txn[0], local_txn_1[0]);
5636 check_spends!(spend_txn[1], htlc_timeout);
5637 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5641 fn test_static_output_closing_tx() {
5642 let chanmon_cfgs = create_chanmon_cfgs(2);
5643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5645 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5647 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5649 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5650 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5652 mine_transaction(&nodes[0], &closing_tx);
5653 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5655 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5656 assert_eq!(spend_txn.len(), 1);
5657 check_spends!(spend_txn[0], closing_tx);
5659 mine_transaction(&nodes[1], &closing_tx);
5660 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5662 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5663 assert_eq!(spend_txn.len(), 1);
5664 check_spends!(spend_txn[0], closing_tx);
5667 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5668 let chanmon_cfgs = create_chanmon_cfgs(2);
5669 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5670 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5671 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5672 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5674 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5676 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5677 // present in B's local commitment transaction, but none of A's commitment transactions.
5678 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5679 check_added_monitors!(nodes[1], 1);
5681 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5682 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5683 let events = nodes[0].node.get_and_clear_pending_events();
5684 assert_eq!(events.len(), 1);
5686 Event::PaymentSent { payment_preimage } => {
5687 assert_eq!(payment_preimage, our_payment_preimage);
5689 _ => panic!("Unexpected event"),
5692 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5693 check_added_monitors!(nodes[0], 1);
5694 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5695 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5696 check_added_monitors!(nodes[1], 1);
5698 let starting_block = nodes[1].best_block_info();
5699 let mut block = Block {
5700 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5703 for i in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5704 connect_block(&nodes[1], &block, i);
5705 block.header.prev_blockhash = block.block_hash();
5707 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5708 check_closed_broadcast!(nodes[1], false);
5709 check_added_monitors!(nodes[1], 1);
5712 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5713 let chanmon_cfgs = create_chanmon_cfgs(2);
5714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5716 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5717 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5718 let logger = test_utils::TestLogger::new();
5720 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5721 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5722 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();
5723 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5724 check_added_monitors!(nodes[0], 1);
5726 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5728 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5729 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5730 // to "time out" the HTLC.
5732 let starting_block = nodes[1].best_block_info();
5733 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5735 for i in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5736 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5737 header.prev_blockhash = header.block_hash();
5739 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5740 check_closed_broadcast!(nodes[0], false);
5741 check_added_monitors!(nodes[0], 1);
5744 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5745 let chanmon_cfgs = create_chanmon_cfgs(3);
5746 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5747 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5748 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5749 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5751 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5752 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5753 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5754 // actually revoked.
5755 let htlc_value = if use_dust { 50000 } else { 3000000 };
5756 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5757 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5758 expect_pending_htlcs_forwardable!(nodes[1]);
5759 check_added_monitors!(nodes[1], 1);
5761 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5762 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5763 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5764 check_added_monitors!(nodes[0], 1);
5765 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5766 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5767 check_added_monitors!(nodes[1], 1);
5768 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5769 check_added_monitors!(nodes[1], 1);
5770 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5772 if check_revoke_no_close {
5773 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5774 check_added_monitors!(nodes[0], 1);
5777 let starting_block = nodes[1].best_block_info();
5778 let mut block = Block {
5779 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5782 for i in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5783 connect_block(&nodes[0], &block, i);
5784 block.header.prev_blockhash = block.block_hash();
5786 if !check_revoke_no_close {
5787 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5788 check_closed_broadcast!(nodes[0], false);
5789 check_added_monitors!(nodes[0], 1);
5791 expect_payment_failed!(nodes[0], our_payment_hash, true);
5795 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5796 // There are only a few cases to test here:
5797 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5798 // broadcastable commitment transactions result in channel closure,
5799 // * its included in an unrevoked-but-previous remote commitment transaction,
5800 // * its included in the latest remote or local commitment transactions.
5801 // We test each of the three possible commitment transactions individually and use both dust and
5803 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5804 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5805 // tested for at least one of the cases in other tests.
5807 fn htlc_claim_single_commitment_only_a() {
5808 do_htlc_claim_local_commitment_only(true);
5809 do_htlc_claim_local_commitment_only(false);
5811 do_htlc_claim_current_remote_commitment_only(true);
5812 do_htlc_claim_current_remote_commitment_only(false);
5816 fn htlc_claim_single_commitment_only_b() {
5817 do_htlc_claim_previous_remote_commitment_only(true, false);
5818 do_htlc_claim_previous_remote_commitment_only(false, false);
5819 do_htlc_claim_previous_remote_commitment_only(true, true);
5820 do_htlc_claim_previous_remote_commitment_only(false, true);
5825 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5826 let chanmon_cfgs = create_chanmon_cfgs(2);
5827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5829 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5830 //Force duplicate channel ids
5831 for node in nodes.iter() {
5832 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5835 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5836 let channel_value_satoshis=10000;
5837 let push_msat=10001;
5838 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5839 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5840 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5842 //Create a second channel with a channel_id collision
5843 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5847 fn bolt2_open_channel_sending_node_checks_part2() {
5848 let chanmon_cfgs = create_chanmon_cfgs(2);
5849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5851 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5853 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5854 let channel_value_satoshis=2^24;
5855 let push_msat=10001;
5856 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5858 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5859 let channel_value_satoshis=10000;
5860 // Test when push_msat is equal to 1000 * funding_satoshis.
5861 let push_msat=1000*channel_value_satoshis+1;
5862 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5864 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5865 let channel_value_satoshis=10000;
5866 let push_msat=10001;
5867 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
5868 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5869 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5871 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5872 // 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
5873 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5875 // 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.
5876 assert!(BREAKDOWN_TIMEOUT>0);
5877 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5879 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5880 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5881 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5883 // 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.
5884 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5885 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5886 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5887 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5888 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5891 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5892 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5893 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5894 // is no longer affordable once it's freed.
5896 fn test_fail_holding_cell_htlc_upon_free() {
5897 let chanmon_cfgs = create_chanmon_cfgs(2);
5898 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5899 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5900 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5901 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5902 let logger = test_utils::TestLogger::new();
5904 // First nodes[0] generates an update_fee, setting the channel's
5905 // pending_update_fee.
5906 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5907 check_added_monitors!(nodes[0], 1);
5909 let events = nodes[0].node.get_and_clear_pending_msg_events();
5910 assert_eq!(events.len(), 1);
5911 let (update_msg, commitment_signed) = match events[0] {
5912 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5913 (update_fee.as_ref(), commitment_signed)
5915 _ => panic!("Unexpected event"),
5918 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5920 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5921 let channel_reserve = chan_stat.channel_reserve_msat;
5922 let feerate = get_feerate!(nodes[0], chan.2);
5924 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5925 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5926 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5927 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5928 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();
5930 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5931 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5932 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5933 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5935 // Flush the pending fee update.
5936 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5937 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5938 check_added_monitors!(nodes[1], 1);
5939 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5940 check_added_monitors!(nodes[0], 1);
5942 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5943 // HTLC, but now that the fee has been raised the payment will now fail, causing
5944 // us to surface its failure to the user.
5945 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5946 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5947 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
5948 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);
5949 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
5951 // Check that the payment failed to be sent out.
5952 let events = nodes[0].node.get_and_clear_pending_events();
5953 assert_eq!(events.len(), 1);
5955 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
5956 assert_eq!(our_payment_hash.clone(), *payment_hash);
5957 assert_eq!(*rejected_by_dest, false);
5958 assert_eq!(*error_code, None);
5959 assert_eq!(*error_data, None);
5961 _ => panic!("Unexpected event"),
5965 // Test that if multiple HTLCs are released from the holding cell and one is
5966 // valid but the other is no longer valid upon release, the valid HTLC can be
5967 // successfully completed while the other one fails as expected.
5969 fn test_free_and_fail_holding_cell_htlcs() {
5970 let chanmon_cfgs = create_chanmon_cfgs(2);
5971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5973 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5974 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5975 let logger = test_utils::TestLogger::new();
5977 // First nodes[0] generates an update_fee, setting the channel's
5978 // pending_update_fee.
5979 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
5980 check_added_monitors!(nodes[0], 1);
5982 let events = nodes[0].node.get_and_clear_pending_msg_events();
5983 assert_eq!(events.len(), 1);
5984 let (update_msg, commitment_signed) = match events[0] {
5985 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5986 (update_fee.as_ref(), commitment_signed)
5988 _ => panic!("Unexpected event"),
5991 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5993 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5994 let channel_reserve = chan_stat.channel_reserve_msat;
5995 let feerate = get_feerate!(nodes[0], chan.2);
5997 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5998 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6000 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6001 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6002 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6003 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();
6004 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();
6006 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6007 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6008 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6009 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6010 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6011 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6012 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6014 // Flush the pending fee update.
6015 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6016 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6017 check_added_monitors!(nodes[1], 1);
6018 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6019 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6020 check_added_monitors!(nodes[0], 2);
6022 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6023 // but now that the fee has been raised the second payment will now fail, causing us
6024 // to surface its failure to the user. The first payment should succeed.
6025 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6026 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6027 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6028 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);
6029 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6031 // Check that the second payment failed to be sent out.
6032 let events = nodes[0].node.get_and_clear_pending_events();
6033 assert_eq!(events.len(), 1);
6035 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6036 assert_eq!(payment_hash_2.clone(), *payment_hash);
6037 assert_eq!(*rejected_by_dest, false);
6038 assert_eq!(*error_code, None);
6039 assert_eq!(*error_data, None);
6041 _ => panic!("Unexpected event"),
6044 // Complete the first payment and the RAA from the fee update.
6045 let (payment_event, send_raa_event) = {
6046 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6047 assert_eq!(msgs.len(), 2);
6048 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6050 let raa = match send_raa_event {
6051 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6052 _ => panic!("Unexpected event"),
6054 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6055 check_added_monitors!(nodes[1], 1);
6056 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6057 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6058 let events = nodes[1].node.get_and_clear_pending_events();
6059 assert_eq!(events.len(), 1);
6061 Event::PendingHTLCsForwardable { .. } => {},
6062 _ => panic!("Unexpected event"),
6064 nodes[1].node.process_pending_htlc_forwards();
6065 let events = nodes[1].node.get_and_clear_pending_events();
6066 assert_eq!(events.len(), 1);
6068 Event::PaymentReceived { .. } => {},
6069 _ => panic!("Unexpected event"),
6071 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6072 check_added_monitors!(nodes[1], 1);
6073 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6074 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6075 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6076 let events = nodes[0].node.get_and_clear_pending_events();
6077 assert_eq!(events.len(), 1);
6079 Event::PaymentSent { ref payment_preimage } => {
6080 assert_eq!(*payment_preimage, payment_preimage_1);
6082 _ => panic!("Unexpected event"),
6086 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6087 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6088 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6091 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6092 let chanmon_cfgs = create_chanmon_cfgs(3);
6093 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6094 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6095 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6096 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6097 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6098 let logger = test_utils::TestLogger::new();
6100 // First nodes[1] generates an update_fee, setting the channel's
6101 // pending_update_fee.
6102 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6103 check_added_monitors!(nodes[1], 1);
6105 let events = nodes[1].node.get_and_clear_pending_msg_events();
6106 assert_eq!(events.len(), 1);
6107 let (update_msg, commitment_signed) = match events[0] {
6108 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6109 (update_fee.as_ref(), commitment_signed)
6111 _ => panic!("Unexpected event"),
6114 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6116 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6117 let channel_reserve = chan_stat.channel_reserve_msat;
6118 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6120 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6122 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6123 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6124 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6125 let payment_event = {
6126 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6127 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();
6128 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6129 check_added_monitors!(nodes[0], 1);
6131 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6132 assert_eq!(events.len(), 1);
6134 SendEvent::from_event(events.remove(0))
6136 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6137 check_added_monitors!(nodes[1], 0);
6138 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6139 expect_pending_htlcs_forwardable!(nodes[1]);
6141 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6142 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6144 // Flush the pending fee update.
6145 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6146 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6147 check_added_monitors!(nodes[2], 1);
6148 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6149 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6150 check_added_monitors!(nodes[1], 2);
6152 // A final RAA message is generated to finalize the fee update.
6153 let events = nodes[1].node.get_and_clear_pending_msg_events();
6154 assert_eq!(events.len(), 1);
6156 let raa_msg = match &events[0] {
6157 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6160 _ => panic!("Unexpected event"),
6163 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6164 check_added_monitors!(nodes[2], 1);
6165 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6167 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6168 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6169 assert_eq!(process_htlc_forwards_event.len(), 1);
6170 match &process_htlc_forwards_event[0] {
6171 &Event::PendingHTLCsForwardable { .. } => {},
6172 _ => panic!("Unexpected event"),
6175 // In response, we call ChannelManager's process_pending_htlc_forwards
6176 nodes[1].node.process_pending_htlc_forwards();
6177 check_added_monitors!(nodes[1], 1);
6179 // This causes the HTLC to be failed backwards.
6180 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6181 assert_eq!(fail_event.len(), 1);
6182 let (fail_msg, commitment_signed) = match &fail_event[0] {
6183 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6184 assert_eq!(updates.update_add_htlcs.len(), 0);
6185 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6186 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6187 assert_eq!(updates.update_fail_htlcs.len(), 1);
6188 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6190 _ => panic!("Unexpected event"),
6193 // Pass the failure messages back to nodes[0].
6194 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6195 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6197 // Complete the HTLC failure+removal process.
6198 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6199 check_added_monitors!(nodes[0], 1);
6200 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6201 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6202 check_added_monitors!(nodes[1], 2);
6203 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6204 assert_eq!(final_raa_event.len(), 1);
6205 let raa = match &final_raa_event[0] {
6206 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6207 _ => panic!("Unexpected event"),
6209 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6210 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6211 assert_eq!(fail_msg_event.len(), 1);
6212 match &fail_msg_event[0] {
6213 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6214 _ => panic!("Unexpected event"),
6216 let failure_event = nodes[0].node.get_and_clear_pending_events();
6217 assert_eq!(failure_event.len(), 1);
6218 match &failure_event[0] {
6219 &Event::PaymentFailed { rejected_by_dest, .. } => {
6220 assert!(!rejected_by_dest);
6222 _ => panic!("Unexpected event"),
6224 check_added_monitors!(nodes[0], 1);
6227 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6228 // 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.
6229 //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.
6232 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6233 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6234 let chanmon_cfgs = create_chanmon_cfgs(2);
6235 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6236 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6237 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6238 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6240 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6241 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6242 let logger = test_utils::TestLogger::new();
6243 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();
6244 route.paths[0][0].fee_msat = 100;
6246 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6247 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6248 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6249 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6253 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6254 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6255 let chanmon_cfgs = create_chanmon_cfgs(2);
6256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6258 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6259 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6260 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6262 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6263 let logger = test_utils::TestLogger::new();
6264 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();
6265 route.paths[0][0].fee_msat = 0;
6266 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6267 assert_eq!(err, "Cannot send 0-msat HTLC"));
6269 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6270 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6274 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6275 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6276 let chanmon_cfgs = create_chanmon_cfgs(2);
6277 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6278 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6279 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6280 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6282 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6283 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6284 let logger = test_utils::TestLogger::new();
6285 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();
6286 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6287 check_added_monitors!(nodes[0], 1);
6288 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6289 updates.update_add_htlcs[0].amount_msat = 0;
6291 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6292 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6293 check_closed_broadcast!(nodes[1], true).unwrap();
6294 check_added_monitors!(nodes[1], 1);
6298 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6299 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6300 //It is enforced when constructing a route.
6301 let chanmon_cfgs = create_chanmon_cfgs(2);
6302 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6303 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6304 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6305 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6306 let logger = test_utils::TestLogger::new();
6308 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6310 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6311 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();
6312 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6313 assert_eq!(err, &"Channel CLTV overflowed?"));
6317 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6318 //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.
6319 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6320 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6321 let chanmon_cfgs = create_chanmon_cfgs(2);
6322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6324 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6325 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6326 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6328 let logger = test_utils::TestLogger::new();
6329 for i in 0..max_accepted_htlcs {
6330 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6331 let payment_event = {
6332 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6333 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();
6334 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6335 check_added_monitors!(nodes[0], 1);
6337 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6338 assert_eq!(events.len(), 1);
6339 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6340 assert_eq!(htlcs[0].htlc_id, i);
6344 SendEvent::from_event(events.remove(0))
6346 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6347 check_added_monitors!(nodes[1], 0);
6348 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6350 expect_pending_htlcs_forwardable!(nodes[1]);
6351 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6353 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6354 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6355 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();
6356 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6357 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6359 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6360 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6364 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6365 //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.
6366 let chanmon_cfgs = create_chanmon_cfgs(2);
6367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6370 let channel_value = 100000;
6371 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6372 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6374 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6376 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6377 // Manually create a route over our max in flight (which our router normally automatically
6379 let route = Route { paths: vec![vec![RouteHop {
6380 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6381 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6382 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6384 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6385 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)));
6387 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6388 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);
6390 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6393 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6395 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6396 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6397 let chanmon_cfgs = create_chanmon_cfgs(2);
6398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6400 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6401 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6402 let htlc_minimum_msat: u64;
6404 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6405 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6406 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6409 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6410 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6411 let logger = test_utils::TestLogger::new();
6412 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();
6413 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6414 check_added_monitors!(nodes[0], 1);
6415 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6416 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6417 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6418 assert!(nodes[1].node.list_channels().is_empty());
6419 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6420 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()));
6421 check_added_monitors!(nodes[1], 1);
6425 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6426 //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
6427 let chanmon_cfgs = create_chanmon_cfgs(2);
6428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6430 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6431 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6432 let logger = test_utils::TestLogger::new();
6434 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6435 let channel_reserve = chan_stat.channel_reserve_msat;
6436 let feerate = get_feerate!(nodes[0], chan.2);
6437 // The 2* and +1 are for the fee spike reserve.
6438 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6440 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6441 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6442 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6443 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();
6444 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6445 check_added_monitors!(nodes[0], 1);
6446 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6448 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6449 // at this time channel-initiatee receivers are not required to enforce that senders
6450 // respect the fee_spike_reserve.
6451 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6452 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6454 assert!(nodes[1].node.list_channels().is_empty());
6455 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6456 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6457 check_added_monitors!(nodes[1], 1);
6461 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6462 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6463 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6464 let chanmon_cfgs = create_chanmon_cfgs(2);
6465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6467 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6468 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6469 let logger = test_utils::TestLogger::new();
6471 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6472 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6474 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6475 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();
6477 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6478 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6479 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6480 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6482 let mut msg = msgs::UpdateAddHTLC {
6486 payment_hash: our_payment_hash,
6487 cltv_expiry: htlc_cltv,
6488 onion_routing_packet: onion_packet.clone(),
6491 for i in 0..super::channel::OUR_MAX_HTLCS {
6492 msg.htlc_id = i as u64;
6493 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6495 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6496 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6498 assert!(nodes[1].node.list_channels().is_empty());
6499 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6500 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6501 check_added_monitors!(nodes[1], 1);
6505 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6506 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6507 let chanmon_cfgs = create_chanmon_cfgs(2);
6508 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6509 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6510 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6511 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6512 let logger = test_utils::TestLogger::new();
6514 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6515 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6516 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();
6517 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6518 check_added_monitors!(nodes[0], 1);
6519 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6520 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6521 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6523 assert!(nodes[1].node.list_channels().is_empty());
6524 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6525 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6526 check_added_monitors!(nodes[1], 1);
6530 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6531 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6532 let chanmon_cfgs = create_chanmon_cfgs(2);
6533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6535 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6536 let logger = test_utils::TestLogger::new();
6538 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6539 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6540 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6541 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();
6542 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6543 check_added_monitors!(nodes[0], 1);
6544 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6545 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6546 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6548 assert!(nodes[1].node.list_channels().is_empty());
6549 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6550 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6551 check_added_monitors!(nodes[1], 1);
6555 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6556 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6557 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6558 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6559 let chanmon_cfgs = create_chanmon_cfgs(2);
6560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6562 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6563 let logger = test_utils::TestLogger::new();
6565 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6566 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6567 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6568 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();
6569 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6570 check_added_monitors!(nodes[0], 1);
6571 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6572 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6574 //Disconnect and Reconnect
6575 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6576 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6577 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6578 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6579 assert_eq!(reestablish_1.len(), 1);
6580 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6581 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6582 assert_eq!(reestablish_2.len(), 1);
6583 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6584 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6585 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6586 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6589 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6590 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6591 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6592 check_added_monitors!(nodes[1], 1);
6593 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6595 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6597 assert!(nodes[1].node.list_channels().is_empty());
6598 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6599 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6600 check_added_monitors!(nodes[1], 1);
6604 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6605 //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.
6607 let chanmon_cfgs = create_chanmon_cfgs(2);
6608 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6609 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6610 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6611 let logger = test_utils::TestLogger::new();
6612 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6613 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6614 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6615 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();
6616 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6618 check_added_monitors!(nodes[0], 1);
6619 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6620 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6622 let update_msg = msgs::UpdateFulfillHTLC{
6625 payment_preimage: our_payment_preimage,
6628 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6630 assert!(nodes[0].node.list_channels().is_empty());
6631 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6632 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()));
6633 check_added_monitors!(nodes[0], 1);
6637 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6638 //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.
6640 let chanmon_cfgs = create_chanmon_cfgs(2);
6641 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6642 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6643 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6644 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6645 let logger = test_utils::TestLogger::new();
6647 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6648 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6649 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();
6650 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6651 check_added_monitors!(nodes[0], 1);
6652 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6653 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6655 let update_msg = msgs::UpdateFailHTLC{
6658 reason: msgs::OnionErrorPacket { data: Vec::new()},
6661 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6663 assert!(nodes[0].node.list_channels().is_empty());
6664 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6665 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()));
6666 check_added_monitors!(nodes[0], 1);
6670 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6671 //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.
6673 let chanmon_cfgs = create_chanmon_cfgs(2);
6674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6676 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6677 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6678 let logger = test_utils::TestLogger::new();
6680 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6681 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6682 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();
6683 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6684 check_added_monitors!(nodes[0], 1);
6685 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6686 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6687 let update_msg = msgs::UpdateFailMalformedHTLC{
6690 sha256_of_onion: [1; 32],
6691 failure_code: 0x8000,
6694 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6696 assert!(nodes[0].node.list_channels().is_empty());
6697 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6698 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()));
6699 check_added_monitors!(nodes[0], 1);
6703 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6704 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6706 let chanmon_cfgs = create_chanmon_cfgs(2);
6707 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6708 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6709 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6710 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6712 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6714 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6715 check_added_monitors!(nodes[1], 1);
6717 let events = nodes[1].node.get_and_clear_pending_msg_events();
6718 assert_eq!(events.len(), 1);
6719 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6721 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, .. } } => {
6722 assert!(update_add_htlcs.is_empty());
6723 assert_eq!(update_fulfill_htlcs.len(), 1);
6724 assert!(update_fail_htlcs.is_empty());
6725 assert!(update_fail_malformed_htlcs.is_empty());
6726 assert!(update_fee.is_none());
6727 update_fulfill_htlcs[0].clone()
6729 _ => panic!("Unexpected event"),
6733 update_fulfill_msg.htlc_id = 1;
6735 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6737 assert!(nodes[0].node.list_channels().is_empty());
6738 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6739 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6740 check_added_monitors!(nodes[0], 1);
6744 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6745 //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.
6747 let chanmon_cfgs = create_chanmon_cfgs(2);
6748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6750 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6751 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6753 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6755 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6756 check_added_monitors!(nodes[1], 1);
6758 let events = nodes[1].node.get_and_clear_pending_msg_events();
6759 assert_eq!(events.len(), 1);
6760 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6762 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, .. } } => {
6763 assert!(update_add_htlcs.is_empty());
6764 assert_eq!(update_fulfill_htlcs.len(), 1);
6765 assert!(update_fail_htlcs.is_empty());
6766 assert!(update_fail_malformed_htlcs.is_empty());
6767 assert!(update_fee.is_none());
6768 update_fulfill_htlcs[0].clone()
6770 _ => panic!("Unexpected event"),
6774 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6776 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6778 assert!(nodes[0].node.list_channels().is_empty());
6779 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6780 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6781 check_added_monitors!(nodes[0], 1);
6785 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6786 //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.
6788 let chanmon_cfgs = create_chanmon_cfgs(2);
6789 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6790 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6791 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6792 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6793 let logger = test_utils::TestLogger::new();
6795 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6796 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6797 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();
6798 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6799 check_added_monitors!(nodes[0], 1);
6801 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6802 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6804 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6805 check_added_monitors!(nodes[1], 0);
6806 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6808 let events = nodes[1].node.get_and_clear_pending_msg_events();
6810 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6812 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, .. } } => {
6813 assert!(update_add_htlcs.is_empty());
6814 assert!(update_fulfill_htlcs.is_empty());
6815 assert!(update_fail_htlcs.is_empty());
6816 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6817 assert!(update_fee.is_none());
6818 update_fail_malformed_htlcs[0].clone()
6820 _ => panic!("Unexpected event"),
6823 update_msg.failure_code &= !0x8000;
6824 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6826 assert!(nodes[0].node.list_channels().is_empty());
6827 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6828 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6829 check_added_monitors!(nodes[0], 1);
6833 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6834 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6835 // * 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.
6837 let chanmon_cfgs = create_chanmon_cfgs(3);
6838 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6839 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6840 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6841 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6842 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6843 let logger = test_utils::TestLogger::new();
6845 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6848 let mut payment_event = {
6849 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6850 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();
6851 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6852 check_added_monitors!(nodes[0], 1);
6853 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6854 assert_eq!(events.len(), 1);
6855 SendEvent::from_event(events.remove(0))
6857 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6858 check_added_monitors!(nodes[1], 0);
6859 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6860 expect_pending_htlcs_forwardable!(nodes[1]);
6861 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6862 assert_eq!(events_2.len(), 1);
6863 check_added_monitors!(nodes[1], 1);
6864 payment_event = SendEvent::from_event(events_2.remove(0));
6865 assert_eq!(payment_event.msgs.len(), 1);
6868 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6869 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6870 check_added_monitors!(nodes[2], 0);
6871 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6873 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6874 assert_eq!(events_3.len(), 1);
6875 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6877 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6878 assert!(update_add_htlcs.is_empty());
6879 assert!(update_fulfill_htlcs.is_empty());
6880 assert!(update_fail_htlcs.is_empty());
6881 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6882 assert!(update_fee.is_none());
6883 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6885 _ => panic!("Unexpected event"),
6889 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6891 check_added_monitors!(nodes[1], 0);
6892 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6893 expect_pending_htlcs_forwardable!(nodes[1]);
6894 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6895 assert_eq!(events_4.len(), 1);
6897 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6899 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, .. } } => {
6900 assert!(update_add_htlcs.is_empty());
6901 assert!(update_fulfill_htlcs.is_empty());
6902 assert_eq!(update_fail_htlcs.len(), 1);
6903 assert!(update_fail_malformed_htlcs.is_empty());
6904 assert!(update_fee.is_none());
6906 _ => panic!("Unexpected event"),
6909 check_added_monitors!(nodes[1], 1);
6912 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6913 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6914 // 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
6915 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6917 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6918 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6919 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6920 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6921 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6922 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6924 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6926 // We route 2 dust-HTLCs between A and B
6927 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6928 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6929 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6931 // Cache one local commitment tx as previous
6932 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6934 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6935 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6936 check_added_monitors!(nodes[1], 0);
6937 expect_pending_htlcs_forwardable!(nodes[1]);
6938 check_added_monitors!(nodes[1], 1);
6940 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6941 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6942 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6943 check_added_monitors!(nodes[0], 1);
6945 // Cache one local commitment tx as lastest
6946 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6948 let events = nodes[0].node.get_and_clear_pending_msg_events();
6950 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6951 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6953 _ => panic!("Unexpected event"),
6956 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6957 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6959 _ => panic!("Unexpected event"),
6962 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6963 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6964 if announce_latest {
6965 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
6967 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
6970 check_closed_broadcast!(nodes[0], false);
6971 check_added_monitors!(nodes[0], 1);
6973 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6974 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
6975 let events = nodes[0].node.get_and_clear_pending_events();
6976 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6977 assert_eq!(events.len(), 2);
6978 let mut first_failed = false;
6979 for event in events {
6981 Event::PaymentFailed { payment_hash, .. } => {
6982 if payment_hash == payment_hash_1 {
6983 assert!(!first_failed);
6984 first_failed = true;
6986 assert_eq!(payment_hash, payment_hash_2);
6989 _ => panic!("Unexpected event"),
6995 fn test_failure_delay_dust_htlc_local_commitment() {
6996 do_test_failure_delay_dust_htlc_local_commitment(true);
6997 do_test_failure_delay_dust_htlc_local_commitment(false);
7000 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7001 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7002 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7003 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7004 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7005 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7006 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7008 let chanmon_cfgs = create_chanmon_cfgs(3);
7009 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7010 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7011 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7012 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7014 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7016 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7017 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7019 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7020 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7022 // We revoked bs_commitment_tx
7024 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7025 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7028 let mut timeout_tx = Vec::new();
7030 // We fail dust-HTLC 1 by broadcast of local commitment tx
7031 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7032 check_closed_broadcast!(nodes[0], false);
7033 check_added_monitors!(nodes[0], 1);
7034 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7035 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7036 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7037 expect_payment_failed!(nodes[0], dust_hash, true);
7038 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7039 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7040 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7041 mine_transaction(&nodes[0], &timeout_tx[0]);
7042 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7043 expect_payment_failed!(nodes[0], non_dust_hash, true);
7045 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7046 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7047 check_closed_broadcast!(nodes[0], false);
7048 check_added_monitors!(nodes[0], 1);
7049 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7050 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7051 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7053 expect_payment_failed!(nodes[0], dust_hash, true);
7054 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7055 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7056 mine_transaction(&nodes[0], &timeout_tx[0]);
7057 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7058 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7059 expect_payment_failed!(nodes[0], non_dust_hash, true);
7061 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7063 let events = nodes[0].node.get_and_clear_pending_events();
7064 assert_eq!(events.len(), 2);
7067 Event::PaymentFailed { payment_hash, .. } => {
7068 if payment_hash == dust_hash { first = true; }
7069 else { first = false; }
7071 _ => panic!("Unexpected event"),
7074 Event::PaymentFailed { payment_hash, .. } => {
7075 if first { assert_eq!(payment_hash, non_dust_hash); }
7076 else { assert_eq!(payment_hash, dust_hash); }
7078 _ => panic!("Unexpected event"),
7085 fn test_sweep_outbound_htlc_failure_update() {
7086 do_test_sweep_outbound_htlc_failure_update(false, true);
7087 do_test_sweep_outbound_htlc_failure_update(false, false);
7088 do_test_sweep_outbound_htlc_failure_update(true, false);
7092 fn test_upfront_shutdown_script() {
7093 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7094 // enforce it at shutdown message
7096 let mut config = UserConfig::default();
7097 config.channel_options.announced_channel = true;
7098 config.peer_channel_config_limits.force_announced_channel_preference = false;
7099 config.channel_options.commit_upfront_shutdown_pubkey = false;
7100 let user_cfgs = [None, Some(config), None];
7101 let chanmon_cfgs = create_chanmon_cfgs(3);
7102 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7103 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7104 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7106 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7107 let flags = InitFeatures::known();
7108 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7109 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7110 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7111 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7112 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7113 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7114 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()));
7115 check_added_monitors!(nodes[2], 1);
7117 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7118 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7119 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7120 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7121 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7122 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7123 let events = nodes[2].node.get_and_clear_pending_msg_events();
7124 assert_eq!(events.len(), 1);
7126 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7127 _ => panic!("Unexpected event"),
7130 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7131 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7132 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7133 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7134 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7135 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7136 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7137 let events = nodes[1].node.get_and_clear_pending_msg_events();
7138 assert_eq!(events.len(), 1);
7140 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7141 _ => panic!("Unexpected event"),
7144 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7145 // channel smoothly, opt-out is from channel initiator here
7146 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7147 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7148 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7149 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7150 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7151 let events = nodes[0].node.get_and_clear_pending_msg_events();
7152 assert_eq!(events.len(), 1);
7154 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7155 _ => panic!("Unexpected event"),
7158 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7159 //// channel smoothly
7160 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7161 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7162 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7163 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7164 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7165 let events = nodes[0].node.get_and_clear_pending_msg_events();
7166 assert_eq!(events.len(), 2);
7168 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7169 _ => panic!("Unexpected event"),
7172 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7173 _ => panic!("Unexpected event"),
7178 fn test_upfront_shutdown_script_unsupport_segwit() {
7179 // We test that channel is closed early
7180 // if a segwit program is passed as upfront shutdown script,
7181 // but the peer does not support segwit.
7182 let chanmon_cfgs = create_chanmon_cfgs(2);
7183 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7184 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7185 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7187 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7189 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7190 open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7191 .push_slice(&[0, 0])
7194 let features = InitFeatures::known().clear_shutdown_anysegwit();
7195 nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7197 let events = nodes[0].node.get_and_clear_pending_msg_events();
7198 assert_eq!(events.len(), 1);
7200 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7201 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7202 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));
7204 _ => panic!("Unexpected event"),
7209 fn test_shutdown_script_any_segwit_allowed() {
7210 let mut config = UserConfig::default();
7211 config.channel_options.announced_channel = true;
7212 config.peer_channel_config_limits.force_announced_channel_preference = false;
7213 config.channel_options.commit_upfront_shutdown_pubkey = false;
7214 let user_cfgs = [None, Some(config), None];
7215 let chanmon_cfgs = create_chanmon_cfgs(3);
7216 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7217 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7218 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7220 //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7221 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7222 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7223 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7224 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7225 .push_slice(&[0, 0])
7227 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7228 let events = nodes[0].node.get_and_clear_pending_msg_events();
7229 assert_eq!(events.len(), 2);
7231 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7232 _ => panic!("Unexpected event"),
7235 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7236 _ => panic!("Unexpected event"),
7241 fn test_shutdown_script_any_segwit_not_allowed() {
7242 let mut config = UserConfig::default();
7243 config.channel_options.announced_channel = true;
7244 config.peer_channel_config_limits.force_announced_channel_preference = false;
7245 config.channel_options.commit_upfront_shutdown_pubkey = false;
7246 let user_cfgs = [None, Some(config), None];
7247 let chanmon_cfgs = create_chanmon_cfgs(3);
7248 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7249 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7250 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7252 //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7253 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7254 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7255 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7256 // Make an any segwit version script
7257 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7258 .push_slice(&[0, 0])
7260 let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7261 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7262 let events = nodes[0].node.get_and_clear_pending_msg_events();
7263 assert_eq!(events.len(), 2);
7265 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7266 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7267 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7269 _ => panic!("Unexpected event"),
7271 check_added_monitors!(nodes[0], 1);
7275 fn test_shutdown_script_segwit_but_not_anysegwit() {
7276 let mut config = UserConfig::default();
7277 config.channel_options.announced_channel = true;
7278 config.peer_channel_config_limits.force_announced_channel_preference = false;
7279 config.channel_options.commit_upfront_shutdown_pubkey = false;
7280 let user_cfgs = [None, Some(config), None];
7281 let chanmon_cfgs = create_chanmon_cfgs(3);
7282 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7283 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7284 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7286 //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7287 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7288 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7289 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7290 // Make a segwit script that is not a valid as any segwit
7291 node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7292 .push_slice(&[0, 0])
7294 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7295 let events = nodes[0].node.get_and_clear_pending_msg_events();
7296 assert_eq!(events.len(), 2);
7298 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7299 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7300 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7302 _ => panic!("Unexpected event"),
7304 check_added_monitors!(nodes[0], 1);
7308 fn test_user_configurable_csv_delay() {
7309 // We test our channel constructors yield errors when we pass them absurd csv delay
7311 let mut low_our_to_self_config = UserConfig::default();
7312 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7313 let mut high_their_to_self_config = UserConfig::default();
7314 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7315 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7316 let chanmon_cfgs = create_chanmon_cfgs(2);
7317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7319 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7321 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7322 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) {
7324 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())); },
7325 _ => panic!("Unexpected event"),
7327 } else { assert!(false) }
7329 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7330 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7331 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7332 open_channel.to_self_delay = 200;
7333 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) {
7335 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())); },
7336 _ => panic!("Unexpected event"),
7338 } else { assert!(false); }
7340 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7341 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7342 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()));
7343 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7344 accept_channel.to_self_delay = 200;
7345 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7346 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7348 &ErrorAction::SendErrorMessage { ref msg } => {
7349 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()));
7351 _ => { assert!(false); }
7353 } else { assert!(false); }
7355 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7356 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7357 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7358 open_channel.to_self_delay = 200;
7359 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) {
7361 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())); },
7362 _ => panic!("Unexpected event"),
7364 } else { assert!(false); }
7368 fn test_data_loss_protect() {
7369 // We want to be sure that :
7370 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7371 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7372 // * we close channel in case of detecting other being fallen behind
7373 // * we are able to claim our own outputs thanks to to_remote being static
7374 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7380 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7381 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7382 // during signing due to revoked tx
7383 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7384 let keys_manager = &chanmon_cfgs[0].keys_manager;
7387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7389 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7391 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7393 // Cache node A state before any channel update
7394 let previous_node_state = nodes[0].node.encode();
7395 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7396 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7398 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7399 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7401 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7402 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7404 // Restore node A from previous state
7405 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7406 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7407 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7408 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7409 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7410 persister = test_utils::TestPersister::new();
7411 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7413 let mut channel_monitors = HashMap::new();
7414 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7415 <(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 {
7416 keys_manager: keys_manager,
7417 fee_estimator: &fee_estimator,
7418 chain_monitor: &monitor,
7420 tx_broadcaster: &tx_broadcaster,
7421 default_config: UserConfig::default(),
7425 nodes[0].node = &node_state_0;
7426 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7427 nodes[0].chain_monitor = &monitor;
7428 nodes[0].chain_source = &chain_source;
7430 check_added_monitors!(nodes[0], 1);
7432 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7433 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7435 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7437 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7438 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7439 check_added_monitors!(nodes[0], 1);
7442 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7443 assert_eq!(node_txn.len(), 0);
7446 let mut reestablish_1 = Vec::with_capacity(1);
7447 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7448 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7449 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7450 reestablish_1.push(msg.clone());
7451 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7452 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7454 &ErrorAction::SendErrorMessage { ref msg } => {
7455 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");
7457 _ => panic!("Unexpected event!"),
7460 panic!("Unexpected event")
7464 // Check we close channel detecting A is fallen-behind
7465 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7466 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7467 check_added_monitors!(nodes[1], 1);
7470 // Check A is able to claim to_remote output
7471 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7472 assert_eq!(node_txn.len(), 1);
7473 check_spends!(node_txn[0], chan.3);
7474 assert_eq!(node_txn[0].output.len(), 2);
7475 mine_transaction(&nodes[0], &node_txn[0]);
7476 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7477 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7478 assert_eq!(spend_txn.len(), 1);
7479 check_spends!(spend_txn[0], node_txn[0]);
7483 fn test_check_htlc_underpaying() {
7484 // Send payment through A -> B but A is maliciously
7485 // sending a probe payment (i.e less than expected value0
7486 // to B, B should refuse payment.
7488 let chanmon_cfgs = create_chanmon_cfgs(2);
7489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7491 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7493 // Create some initial channels
7494 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7496 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7498 // Node 3 is expecting payment of 100_000 but receive 10_000,
7499 // fail htlc like we didn't know the preimage.
7500 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7501 nodes[1].node.process_pending_htlc_forwards();
7503 let events = nodes[1].node.get_and_clear_pending_msg_events();
7504 assert_eq!(events.len(), 1);
7505 let (update_fail_htlc, commitment_signed) = match events[0] {
7506 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 } } => {
7507 assert!(update_add_htlcs.is_empty());
7508 assert!(update_fulfill_htlcs.is_empty());
7509 assert_eq!(update_fail_htlcs.len(), 1);
7510 assert!(update_fail_malformed_htlcs.is_empty());
7511 assert!(update_fee.is_none());
7512 (update_fail_htlcs[0].clone(), commitment_signed)
7514 _ => panic!("Unexpected event"),
7516 check_added_monitors!(nodes[1], 1);
7518 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7519 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7521 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7522 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7523 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7524 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7525 nodes[1].node.get_and_clear_pending_events();
7529 fn test_announce_disable_channels() {
7530 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7531 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7533 let chanmon_cfgs = create_chanmon_cfgs(2);
7534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7536 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7538 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7539 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7540 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7543 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7544 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7546 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7547 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7548 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7549 assert_eq!(msg_events.len(), 3);
7550 for e in msg_events {
7552 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7553 let short_id = msg.contents.short_channel_id;
7554 // Check generated channel_update match list in PendingChannelUpdate
7555 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7556 panic!("Generated ChannelUpdate for wrong chan!");
7559 _ => panic!("Unexpected event"),
7563 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7564 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7565 assert_eq!(reestablish_1.len(), 3);
7566 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7567 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7568 assert_eq!(reestablish_2.len(), 3);
7570 // Reestablish chan_1
7571 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7572 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7573 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7574 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7575 // Reestablish chan_2
7576 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7577 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7578 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7579 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7580 // Reestablish chan_3
7581 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7582 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7583 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7584 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7586 nodes[0].node.timer_chan_freshness_every_min();
7587 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7591 fn test_bump_penalty_txn_on_revoked_commitment() {
7592 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7593 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7595 let chanmon_cfgs = create_chanmon_cfgs(2);
7596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7598 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7600 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7601 let logger = test_utils::TestLogger::new();
7603 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7604 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7605 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();
7606 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7608 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7609 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7610 assert_eq!(revoked_txn[0].output.len(), 4);
7611 assert_eq!(revoked_txn[0].input.len(), 1);
7612 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7613 let revoked_txid = revoked_txn[0].txid();
7615 let mut penalty_sum = 0;
7616 for outp in revoked_txn[0].output.iter() {
7617 if outp.script_pubkey.is_v0_p2wsh() {
7618 penalty_sum += outp.value;
7622 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7623 let starting_height = nodes[1].best_block_info().1;
7624 let header_114 = connect_blocks(&nodes[1], 14);
7626 // Actually revoke tx by claiming a HTLC
7627 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7628 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7629 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 15 + starting_height);
7630 check_added_monitors!(nodes[1], 1);
7632 // One or more justice tx should have been broadcast, check it
7636 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7637 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7638 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7639 assert_eq!(node_txn[0].output.len(), 1);
7640 check_spends!(node_txn[0], revoked_txn[0]);
7641 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7642 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7643 penalty_1 = node_txn[0].txid();
7647 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7648 connect_blocks(&nodes[1], 15);
7649 let mut penalty_2 = penalty_1;
7650 let mut feerate_2 = 0;
7652 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7653 assert_eq!(node_txn.len(), 1);
7654 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7655 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7656 assert_eq!(node_txn[0].output.len(), 1);
7657 check_spends!(node_txn[0], revoked_txn[0]);
7658 penalty_2 = node_txn[0].txid();
7659 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7660 assert_ne!(penalty_2, penalty_1);
7661 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7662 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7663 // Verify 25% bump heuristic
7664 assert!(feerate_2 * 100 >= feerate_1 * 125);
7668 assert_ne!(feerate_2, 0);
7670 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7671 connect_blocks(&nodes[1], 1);
7673 let mut feerate_3 = 0;
7675 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7676 assert_eq!(node_txn.len(), 1);
7677 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7678 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7679 assert_eq!(node_txn[0].output.len(), 1);
7680 check_spends!(node_txn[0], revoked_txn[0]);
7681 penalty_3 = node_txn[0].txid();
7682 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7683 assert_ne!(penalty_3, penalty_2);
7684 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7685 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7686 // Verify 25% bump heuristic
7687 assert!(feerate_3 * 100 >= feerate_2 * 125);
7691 assert_ne!(feerate_3, 0);
7693 nodes[1].node.get_and_clear_pending_events();
7694 nodes[1].node.get_and_clear_pending_msg_events();
7698 fn test_bump_penalty_txn_on_revoked_htlcs() {
7699 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7700 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7702 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7703 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7704 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7705 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7706 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7708 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7709 // Lock HTLC in both directions
7710 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7711 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7713 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7714 assert_eq!(revoked_local_txn[0].input.len(), 1);
7715 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7717 // Revoke local commitment tx
7718 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7720 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7721 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7722 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, CHAN_CONFIRM_DEPTH + 1);
7723 check_closed_broadcast!(nodes[1], false);
7724 check_added_monitors!(nodes[1], 1);
7726 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7727 assert_eq!(revoked_htlc_txn.len(), 4);
7728 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7729 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7730 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7731 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7732 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7733 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7734 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7735 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7736 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7737 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7738 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7739 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7740 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7741 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7744 // Broadcast set of revoked txn on A
7745 let hash_128 = connect_blocks(&nodes[0], 40);
7746 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7747 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] }, CHAN_CONFIRM_DEPTH + 40 + 1);
7748 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7749 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, CHAN_CONFIRM_DEPTH + 40 + 2);
7750 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7755 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7756 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7757 // Verify claim tx are spending revoked HTLC txn
7759 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7760 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7761 // which are included in the same block (they are broadcasted because we scan the
7762 // transactions linearly and generate claims as we go, they likely should be removed in the
7764 assert_eq!(node_txn[0].input.len(), 1);
7765 check_spends!(node_txn[0], revoked_local_txn[0]);
7766 assert_eq!(node_txn[1].input.len(), 1);
7767 check_spends!(node_txn[1], revoked_local_txn[0]);
7768 assert_eq!(node_txn[2].input.len(), 1);
7769 check_spends!(node_txn[2], revoked_local_txn[0]);
7771 // Each of the three justice transactions claim a separate (single) output of the three
7772 // available, which we check here:
7773 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7774 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7775 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7777 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7778 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7780 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7781 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7782 // a remote commitment tx has already been confirmed).
7783 check_spends!(node_txn[3], chan.3);
7785 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7786 // output, checked above).
7787 assert_eq!(node_txn[4].input.len(), 2);
7788 assert_eq!(node_txn[4].output.len(), 1);
7789 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7791 first = node_txn[4].txid();
7792 // Store both feerates for later comparison
7793 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7794 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7795 penalty_txn = vec![node_txn[2].clone()];
7799 // Connect one more block to see if bumped penalty are issued for HTLC txn
7800 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7801 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, CHAN_CONFIRM_DEPTH + 40 + 3);
7802 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7803 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, CHAN_CONFIRM_DEPTH + 40 + 4);
7805 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7806 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7808 check_spends!(node_txn[0], revoked_local_txn[0]);
7809 check_spends!(node_txn[1], revoked_local_txn[0]);
7810 // Note that these are both bogus - they spend outputs already claimed in block 129:
7811 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7812 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7814 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7815 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7821 // Few more blocks to confirm penalty txn
7822 connect_blocks(&nodes[0], 4);
7823 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7824 let header_144 = connect_blocks(&nodes[0], 9);
7826 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7827 assert_eq!(node_txn.len(), 1);
7829 assert_eq!(node_txn[0].input.len(), 2);
7830 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7831 // Verify bumped tx is different and 25% bump heuristic
7832 assert_ne!(first, node_txn[0].txid());
7833 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7834 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7835 assert!(feerate_2 * 100 > feerate_1 * 125);
7836 let txn = vec![node_txn[0].clone()];
7840 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7841 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7842 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, CHAN_CONFIRM_DEPTH + 40 + 8 + 10);
7843 connect_blocks(&nodes[0], 20);
7845 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7846 // We verify than no new transaction has been broadcast because previously
7847 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7848 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7849 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7850 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7851 // up bumped justice generation.
7852 assert_eq!(node_txn.len(), 0);
7855 check_closed_broadcast!(nodes[0], false);
7856 check_added_monitors!(nodes[0], 1);
7860 fn test_bump_penalty_txn_on_remote_commitment() {
7861 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7862 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7865 // Provide preimage for one
7866 // Check aggregation
7868 let chanmon_cfgs = create_chanmon_cfgs(2);
7869 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7870 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7871 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7873 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7874 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7875 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7877 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7878 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7879 assert_eq!(remote_txn[0].output.len(), 4);
7880 assert_eq!(remote_txn[0].input.len(), 1);
7881 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7883 // Claim a HTLC without revocation (provide B monitor with preimage)
7884 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7885 mine_transaction(&nodes[1], &remote_txn[0]);
7886 check_added_monitors!(nodes[1], 2);
7888 // One or more claim tx should have been broadcast, check it
7891 let feerate_timeout;
7892 let feerate_preimage;
7894 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7895 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7896 assert_eq!(node_txn[0].input.len(), 1);
7897 assert_eq!(node_txn[1].input.len(), 1);
7898 check_spends!(node_txn[0], remote_txn[0]);
7899 check_spends!(node_txn[1], remote_txn[0]);
7900 check_spends!(node_txn[2], chan.3);
7901 check_spends!(node_txn[3], node_txn[2]);
7902 check_spends!(node_txn[4], node_txn[2]);
7903 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7904 timeout = node_txn[0].txid();
7905 let index = node_txn[0].input[0].previous_output.vout;
7906 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7907 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7909 preimage = node_txn[1].txid();
7910 let index = node_txn[1].input[0].previous_output.vout;
7911 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7912 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7914 timeout = node_txn[1].txid();
7915 let index = node_txn[1].input[0].previous_output.vout;
7916 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7917 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7919 preimage = node_txn[0].txid();
7920 let index = node_txn[0].input[0].previous_output.vout;
7921 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7922 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7926 assert_ne!(feerate_timeout, 0);
7927 assert_ne!(feerate_preimage, 0);
7929 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7930 connect_blocks(&nodes[1], 15);
7932 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7933 assert_eq!(node_txn.len(), 2);
7934 assert_eq!(node_txn[0].input.len(), 1);
7935 assert_eq!(node_txn[1].input.len(), 1);
7936 check_spends!(node_txn[0], remote_txn[0]);
7937 check_spends!(node_txn[1], remote_txn[0]);
7938 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7939 let index = node_txn[0].input[0].previous_output.vout;
7940 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7941 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7942 assert!(new_feerate * 100 > feerate_timeout * 125);
7943 assert_ne!(timeout, node_txn[0].txid());
7945 let index = node_txn[1].input[0].previous_output.vout;
7946 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7947 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7948 assert!(new_feerate * 100 > feerate_preimage * 125);
7949 assert_ne!(preimage, node_txn[1].txid());
7951 let index = node_txn[1].input[0].previous_output.vout;
7952 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7953 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7954 assert!(new_feerate * 100 > feerate_timeout * 125);
7955 assert_ne!(timeout, node_txn[1].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 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7960 assert!(new_feerate * 100 > feerate_preimage * 125);
7961 assert_ne!(preimage, node_txn[0].txid());
7966 nodes[1].node.get_and_clear_pending_events();
7967 nodes[1].node.get_and_clear_pending_msg_events();
7971 fn test_counterparty_raa_skip_no_crash() {
7972 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7973 // commitment transaction, we would have happily carried on and provided them the next
7974 // commitment transaction based on one RAA forward. This would probably eventually have led to
7975 // channel closure, but it would not have resulted in funds loss. Still, our
7976 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
7977 // check simply that the channel is closed in response to such an RAA, but don't check whether
7978 // we decide to punish our counterparty for revoking their funds (as we don't currently
7980 let chanmon_cfgs = create_chanmon_cfgs(2);
7981 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7982 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7983 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7984 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7986 let mut guard = nodes[0].node.channel_state.lock().unwrap();
7987 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
7988 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7989 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7990 // Must revoke without gaps
7991 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7992 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7993 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7995 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7996 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7997 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7998 check_added_monitors!(nodes[1], 1);
8002 fn test_bump_txn_sanitize_tracking_maps() {
8003 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8004 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8006 let chanmon_cfgs = create_chanmon_cfgs(2);
8007 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8008 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8009 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8011 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8012 // Lock HTLC in both directions
8013 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8014 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8016 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8017 assert_eq!(revoked_local_txn[0].input.len(), 1);
8018 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8020 // Revoke local commitment tx
8021 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8023 // Broadcast set of revoked txn on A
8024 connect_blocks(&nodes[0], 52 - CHAN_CONFIRM_DEPTH);
8025 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8026 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
8028 mine_transaction(&nodes[0], &revoked_local_txn[0]);
8029 check_closed_broadcast!(nodes[0], false);
8030 check_added_monitors!(nodes[0], 1);
8032 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8033 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8034 check_spends!(node_txn[0], revoked_local_txn[0]);
8035 check_spends!(node_txn[1], revoked_local_txn[0]);
8036 check_spends!(node_txn[2], revoked_local_txn[0]);
8037 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8041 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8042 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, nodes[0].best_block_info().1 + 1);
8043 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8045 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8046 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8047 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8048 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8054 fn test_override_channel_config() {
8055 let chanmon_cfgs = create_chanmon_cfgs(2);
8056 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8057 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8058 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8060 // Node0 initiates a channel to node1 using the override config.
8061 let mut override_config = UserConfig::default();
8062 override_config.own_channel_config.our_to_self_delay = 200;
8064 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8066 // Assert the channel created by node0 is using the override config.
8067 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8068 assert_eq!(res.channel_flags, 0);
8069 assert_eq!(res.to_self_delay, 200);
8073 fn test_override_0msat_htlc_minimum() {
8074 let mut zero_config = UserConfig::default();
8075 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8076 let chanmon_cfgs = create_chanmon_cfgs(2);
8077 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8078 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8079 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8081 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8082 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8083 assert_eq!(res.htlc_minimum_msat, 1);
8085 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8086 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8087 assert_eq!(res.htlc_minimum_msat, 1);
8091 fn test_simple_payment_secret() {
8092 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8093 // features, however.
8094 let chanmon_cfgs = create_chanmon_cfgs(3);
8095 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8096 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8097 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8099 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8100 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8101 let logger = test_utils::TestLogger::new();
8103 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8104 let payment_secret = PaymentSecret([0xdb; 32]);
8105 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8106 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();
8107 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8108 // Claiming with all the correct values but the wrong secret should result in nothing...
8109 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8110 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8111 // ...but with the right secret we should be able to claim all the way back
8112 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8116 fn test_simple_mpp() {
8117 // Simple test of sending a multi-path payment.
8118 let chanmon_cfgs = create_chanmon_cfgs(4);
8119 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8120 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8121 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8123 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8124 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8125 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8126 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8127 let logger = test_utils::TestLogger::new();
8129 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8130 let payment_secret = PaymentSecret([0xdb; 32]);
8131 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8132 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();
8133 let path = route.paths[0].clone();
8134 route.paths.push(path);
8135 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8136 route.paths[0][0].short_channel_id = chan_1_id;
8137 route.paths[0][1].short_channel_id = chan_3_id;
8138 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8139 route.paths[1][0].short_channel_id = chan_2_id;
8140 route.paths[1][1].short_channel_id = chan_4_id;
8141 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8142 // Claiming with all the correct values but the wrong secret should result in nothing...
8143 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8144 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8145 // ...but with the right secret we should be able to claim all the way back
8146 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8150 fn test_update_err_monitor_lockdown() {
8151 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8152 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8153 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8155 // This scenario may happen in a watchtower setup, where watchtower process a block height
8156 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8157 // commitment at same time.
8159 let chanmon_cfgs = create_chanmon_cfgs(2);
8160 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8161 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8162 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8164 // Create some initial channel
8165 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8166 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8168 // Rebalance the network to generate htlc in the two directions
8169 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8171 // Route a HTLC from node 0 to node 1 (but don't settle)
8172 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8174 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8175 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8176 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8177 let persister = test_utils::TestPersister::new();
8179 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8180 let monitor = monitors.get(&outpoint).unwrap();
8181 let mut w = test_utils::TestVecWriter(Vec::new());
8182 monitor.write(&mut w).unwrap();
8183 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8184 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8185 assert!(new_monitor == *monitor);
8186 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);
8187 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8190 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8191 watchtower.chain_monitor.block_connected(&header, &[], 200);
8193 // Try to update ChannelMonitor
8194 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8195 check_added_monitors!(nodes[1], 1);
8196 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8197 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8198 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8199 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8200 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8201 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8202 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8203 } else { assert!(false); }
8204 } else { assert!(false); };
8205 // Our local monitor is in-sync and hasn't processed yet timeout
8206 check_added_monitors!(nodes[0], 1);
8207 let events = nodes[0].node.get_and_clear_pending_events();
8208 assert_eq!(events.len(), 1);
8212 fn test_concurrent_monitor_claim() {
8213 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8214 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8215 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8216 // state N+1 confirms. Alice claims output from state N+1.
8218 let chanmon_cfgs = create_chanmon_cfgs(2);
8219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8221 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8223 // Create some initial channel
8224 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8225 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8227 // Rebalance the network to generate htlc in the two directions
8228 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8230 // Route a HTLC from node 0 to node 1 (but don't settle)
8231 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8233 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8234 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8235 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8236 let persister = test_utils::TestPersister::new();
8237 let watchtower_alice = {
8238 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8239 let monitor = monitors.get(&outpoint).unwrap();
8240 let mut w = test_utils::TestVecWriter(Vec::new());
8241 monitor.write(&mut w).unwrap();
8242 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8243 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8244 assert!(new_monitor == *monitor);
8245 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);
8246 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8249 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8250 watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8252 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8254 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8255 assert_eq!(txn.len(), 2);
8259 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8260 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8261 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8262 let persister = test_utils::TestPersister::new();
8263 let watchtower_bob = {
8264 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8265 let monitor = monitors.get(&outpoint).unwrap();
8266 let mut w = test_utils::TestVecWriter(Vec::new());
8267 monitor.write(&mut w).unwrap();
8268 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8269 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8270 assert!(new_monitor == *monitor);
8271 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);
8272 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8275 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8276 watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8278 // Route another payment to generate another update with still previous HTLC pending
8279 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8281 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8282 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();
8283 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8285 check_added_monitors!(nodes[1], 1);
8287 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8288 assert_eq!(updates.update_add_htlcs.len(), 1);
8289 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8290 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8291 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8292 // Watchtower Alice should already have seen the block and reject the update
8293 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8294 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8295 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8296 } else { assert!(false); }
8297 } else { assert!(false); };
8298 // Our local monitor is in-sync and hasn't processed yet timeout
8299 check_added_monitors!(nodes[0], 1);
8301 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8302 watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8304 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8307 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8308 assert_eq!(txn.len(), 2);
8309 bob_state_y = txn[0].clone();
8313 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8314 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8316 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8317 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8318 // the onchain detection of the HTLC output
8319 assert_eq!(htlc_txn.len(), 2);
8320 check_spends!(htlc_txn[0], bob_state_y);
8321 check_spends!(htlc_txn[1], bob_state_y);
8326 fn test_pre_lockin_no_chan_closed_update() {
8327 // Test that if a peer closes a channel in response to a funding_created message we don't
8328 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8331 // Doing so would imply a channel monitor update before the initial channel monitor
8332 // registration, violating our API guarantees.
8334 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8335 // then opening a second channel with the same funding output as the first (which is not
8336 // rejected because the first channel does not exist in the ChannelManager) and closing it
8337 // before receiving funding_signed.
8338 let chanmon_cfgs = create_chanmon_cfgs(2);
8339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8341 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8343 // Create an initial channel
8344 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8345 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8346 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8347 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8348 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8350 // Move the first channel through the funding flow...
8351 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8353 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8354 check_added_monitors!(nodes[0], 0);
8356 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8357 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8358 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8359 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8363 fn test_htlc_no_detection() {
8364 // This test is a mutation to underscore the detection logic bug we had
8365 // before #653. HTLC value routed is above the remaining balance, thus
8366 // inverting HTLC and `to_remote` output. HTLC will come second and
8367 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8368 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8369 // outputs order detection for correct spending children filtring.
8371 let chanmon_cfgs = create_chanmon_cfgs(2);
8372 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8373 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8374 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8376 // Create some initial channels
8377 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8379 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8380 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8381 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8382 assert_eq!(local_txn[0].input.len(), 1);
8383 assert_eq!(local_txn[0].output.len(), 3);
8384 check_spends!(local_txn[0], chan_1.3);
8386 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8387 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8388 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, nodes[0].best_block_info().1 + 1);
8389 // We deliberately connect the local tx twice as this should provoke a failure calling
8390 // this test before #653 fix.
8391 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);
8392 check_closed_broadcast!(nodes[0], false);
8393 check_added_monitors!(nodes[0], 1);
8395 let htlc_timeout = {
8396 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8397 assert_eq!(node_txn[0].input.len(), 1);
8398 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8399 check_spends!(node_txn[0], local_txn[0]);
8403 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8404 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, nodes[0].best_block_info().1 + 1);
8405 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8406 expect_payment_failed!(nodes[0], our_payment_hash, true);
8409 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8410 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8411 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8412 // Carol, Alice would be the upstream node, and Carol the downstream.)
8414 // Steps of the test:
8415 // 1) Alice sends a HTLC to Carol through Bob.
8416 // 2) Carol doesn't settle the HTLC.
8417 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8418 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8419 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8420 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8421 // 5) Carol release the preimage to Bob off-chain.
8422 // 6) Bob claims the offered output on the broadcasted commitment.
8423 let chanmon_cfgs = create_chanmon_cfgs(3);
8424 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8425 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8426 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8428 // Create some initial channels
8429 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8430 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8432 // Steps (1) and (2):
8433 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8434 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8436 // Check that Alice's commitment transaction now contains an output for this HTLC.
8437 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8438 check_spends!(alice_txn[0], chan_ab.3);
8439 assert_eq!(alice_txn[0].output.len(), 2);
8440 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8441 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8442 assert_eq!(alice_txn.len(), 2);
8444 // Steps (3) and (4):
8445 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8446 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8447 let mut force_closing_node = 0; // Alice force-closes
8448 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8449 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8450 check_closed_broadcast!(nodes[force_closing_node], false);
8451 check_added_monitors!(nodes[force_closing_node], 1);
8452 if go_onchain_before_fulfill {
8453 let txn_to_broadcast = match broadcast_alice {
8454 true => alice_txn.clone(),
8455 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8457 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8458 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, CHAN_CONFIRM_DEPTH * 2 + 1);
8459 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8460 if broadcast_alice {
8461 check_closed_broadcast!(nodes[1], false);
8462 check_added_monitors!(nodes[1], 1);
8464 assert_eq!(bob_txn.len(), 1);
8465 check_spends!(bob_txn[0], chan_ab.3);
8469 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8470 // process of removing the HTLC from their commitment transactions.
8471 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8472 check_added_monitors!(nodes[2], 1);
8473 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8474 assert!(carol_updates.update_add_htlcs.is_empty());
8475 assert!(carol_updates.update_fail_htlcs.is_empty());
8476 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8477 assert!(carol_updates.update_fee.is_none());
8478 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8480 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8481 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8482 if !go_onchain_before_fulfill && broadcast_alice {
8483 let events = nodes[1].node.get_and_clear_pending_msg_events();
8484 assert_eq!(events.len(), 1);
8486 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8487 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8489 _ => panic!("Unexpected event"),
8492 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8493 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8494 // Carol<->Bob's updated commitment transaction info.
8495 check_added_monitors!(nodes[1], 2);
8497 let events = nodes[1].node.get_and_clear_pending_msg_events();
8498 assert_eq!(events.len(), 2);
8499 let bob_revocation = match events[0] {
8500 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8501 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8504 _ => panic!("Unexpected event"),
8506 let bob_updates = match events[1] {
8507 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8508 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8511 _ => panic!("Unexpected event"),
8514 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8515 check_added_monitors!(nodes[2], 1);
8516 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8517 check_added_monitors!(nodes[2], 1);
8519 let events = nodes[2].node.get_and_clear_pending_msg_events();
8520 assert_eq!(events.len(), 1);
8521 let carol_revocation = match events[0] {
8522 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8523 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8526 _ => panic!("Unexpected event"),
8528 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8529 check_added_monitors!(nodes[1], 1);
8531 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8532 // here's where we put said channel's commitment tx on-chain.
8533 let mut txn_to_broadcast = alice_txn.clone();
8534 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8535 if !go_onchain_before_fulfill {
8536 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8537 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, CHAN_CONFIRM_DEPTH * 2 + 1);
8538 // If Bob was the one to force-close, he will have already passed these checks earlier.
8539 if broadcast_alice {
8540 check_closed_broadcast!(nodes[1], false);
8541 check_added_monitors!(nodes[1], 1);
8543 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8544 if broadcast_alice {
8545 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8546 // new block being connected. The ChannelManager being notified triggers a monitor update,
8547 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8548 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8550 assert_eq!(bob_txn.len(), 3);
8551 check_spends!(bob_txn[1], chan_ab.3);
8553 assert_eq!(bob_txn.len(), 2);
8554 check_spends!(bob_txn[0], chan_ab.3);
8559 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8560 // broadcasted commitment transaction.
8562 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8563 if go_onchain_before_fulfill {
8564 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8565 assert_eq!(bob_txn.len(), 2);
8567 let script_weight = match broadcast_alice {
8568 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8569 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8571 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8572 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8573 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8574 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8575 if broadcast_alice && !go_onchain_before_fulfill {
8576 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8577 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8579 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8580 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8586 fn test_onchain_htlc_settlement_after_close() {
8587 do_test_onchain_htlc_settlement_after_close(true, true);
8588 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8589 do_test_onchain_htlc_settlement_after_close(true, false);
8590 do_test_onchain_htlc_settlement_after_close(false, false);
8594 fn test_duplicate_chan_id() {
8595 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8596 // already open we reject it and keep the old channel.
8598 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8599 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8600 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8601 // updating logic for the existing channel.
8602 let chanmon_cfgs = create_chanmon_cfgs(2);
8603 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8604 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8605 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8607 // Create an initial channel
8608 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8609 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8610 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8611 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()));
8613 // Try to create a second channel with the same temporary_channel_id as the first and check
8614 // that it is rejected.
8615 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8617 let events = nodes[1].node.get_and_clear_pending_msg_events();
8618 assert_eq!(events.len(), 1);
8620 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8621 // Technically, at this point, nodes[1] would be justified in thinking both the
8622 // first (valid) and second (invalid) channels are closed, given they both have
8623 // the same non-temporary channel_id. However, currently we do not, so we just
8624 // move forward with it.
8625 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8626 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8628 _ => panic!("Unexpected event"),
8632 // Move the first channel through the funding flow...
8633 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8635 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8636 check_added_monitors!(nodes[0], 0);
8638 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8639 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8641 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8642 assert_eq!(added_monitors.len(), 1);
8643 assert_eq!(added_monitors[0].0, funding_output);
8644 added_monitors.clear();
8646 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8648 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8649 let channel_id = funding_outpoint.to_channel_id();
8651 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8654 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8655 // Technically this is allowed by the spec, but we don't support it and there's little reason
8656 // to. Still, it shouldn't cause any other issues.
8657 open_chan_msg.temporary_channel_id = channel_id;
8658 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8660 let events = nodes[1].node.get_and_clear_pending_msg_events();
8661 assert_eq!(events.len(), 1);
8663 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8664 // Technically, at this point, nodes[1] would be justified in thinking both
8665 // channels are closed, but currently we do not, so we just move forward with it.
8666 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8667 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8669 _ => panic!("Unexpected event"),
8673 // Now try to create a second channel which has a duplicate funding output.
8674 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8675 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8676 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8677 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()));
8678 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8680 let funding_created = {
8681 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8682 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8683 let logger = test_utils::TestLogger::new();
8684 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8686 check_added_monitors!(nodes[0], 0);
8687 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8688 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8689 // still needs to be cleared here.
8690 check_added_monitors!(nodes[1], 1);
8692 // ...still, nodes[1] will reject the duplicate channel.
8694 let events = nodes[1].node.get_and_clear_pending_msg_events();
8695 assert_eq!(events.len(), 1);
8697 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8698 // Technically, at this point, nodes[1] would be justified in thinking both
8699 // channels are closed, but currently we do not, so we just move forward with it.
8700 assert_eq!(msg.channel_id, channel_id);
8701 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8703 _ => panic!("Unexpected event"),
8707 // finally, finish creating the original channel and send a payment over it to make sure
8708 // everything is functional.
8709 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8711 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8712 assert_eq!(added_monitors.len(), 1);
8713 assert_eq!(added_monitors[0].0, funding_output);
8714 added_monitors.clear();
8717 let events_4 = nodes[0].node.get_and_clear_pending_events();
8718 assert_eq!(events_4.len(), 1);
8720 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8721 assert_eq!(user_channel_id, 42);
8722 assert_eq!(*funding_txo, funding_output);
8724 _ => panic!("Unexpected event"),
8727 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8728 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8729 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8730 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8734 fn test_error_chans_closed() {
8735 // Test that we properly handle error messages, closing appropriate channels.
8737 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8738 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8739 // we can test various edge cases around it to ensure we don't regress.
8740 let chanmon_cfgs = create_chanmon_cfgs(3);
8741 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8742 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8743 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8745 // Create some initial channels
8746 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8747 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8748 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8750 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8751 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8752 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8754 // Closing a channel from a different peer has no effect
8755 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8756 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8758 // Closing one channel doesn't impact others
8759 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8760 check_added_monitors!(nodes[0], 1);
8761 check_closed_broadcast!(nodes[0], false);
8762 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8763 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);
8764 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);
8766 // A null channel ID should close all channels
8767 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8768 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8769 check_added_monitors!(nodes[0], 2);
8770 let events = nodes[0].node.get_and_clear_pending_msg_events();
8771 assert_eq!(events.len(), 2);
8773 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8774 assert_eq!(msg.contents.flags & 2, 2);
8776 _ => panic!("Unexpected event"),
8779 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8780 assert_eq!(msg.contents.flags & 2, 2);
8782 _ => panic!("Unexpected event"),
8784 // Note that at this point users of a standard PeerHandler will end up calling
8785 // peer_disconnected with no_connection_possible set to false, duplicating the
8786 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8787 // users with their own peer handling logic. We duplicate the call here, however.
8788 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8789 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8791 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8792 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8793 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);