1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::channelmonitor;
16 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
17 use chain::transaction::OutPoint;
18 use chain::keysinterface::{Sign, KeysInterface};
19 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
20 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
21 use ln::channel::{Channel, ChannelError};
22 use ln::{chan_utils, onion_utils};
23 use routing::router::{Route, RouteHop, get_route};
24 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
27 use util::enforcing_trait_impls::EnforcingSigner;
28 use util::{byte_utils, test_utils};
29 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
30 use util::errors::APIError;
31 use util::ser::{Writeable, ReadableArgs};
32 use util::config::UserConfig;
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hash_types::{Txid, BlockHash};
36 use bitcoin::blockdata::block::{Block, BlockHeader};
37 use bitcoin::blockdata::script::Builder;
38 use bitcoin::blockdata::opcodes;
39 use bitcoin::blockdata::constants::genesis_block;
40 use bitcoin::network::constants::Network;
42 use bitcoin::hashes::sha256::Hash as Sha256;
43 use bitcoin::hashes::Hash;
45 use bitcoin::secp256k1::{Secp256k1, Message};
46 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
50 use std::collections::{BTreeSet, HashMap, HashSet};
51 use std::default::Default;
53 use std::sync::atomic::Ordering;
55 use ln::functional_test_utils::*;
56 use ln::chan_utils::CommitmentTransaction;
57 use ln::msgs::OptionalField::Present;
60 fn test_insane_channel_opens() {
61 // Stand up a network of 2 nodes
62 let chanmon_cfgs = create_chanmon_cfgs(2);
63 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
64 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
65 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67 // Instantiate channel parameters where we push the maximum msats given our
69 let channel_value_sat = 31337; // same as funding satoshis
70 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
71 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73 // Have node0 initiate a channel to node1 with aforementioned parameters
74 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76 // Extract the channel open message from node0 to node1
77 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79 // Test helper that asserts we get the correct error string given a mutator
80 // that supposedly makes the channel open message insane
81 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
82 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
83 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
84 assert_eq!(msg_events.len(), 1);
85 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
86 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88 &ErrorAction::SendErrorMessage { .. } => {
89 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91 _ => panic!("unexpected event!"),
93 } else { assert!(false); }
96 use ln::channel::MAX_FUNDING_SATOSHIS;
97 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99 // Test all mutations that would make the channel open message insane
100 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 fn test_async_inbound_update_fee() {
121 let chanmon_cfgs = create_chanmon_cfgs(2);
122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
125 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
126 let logger = test_utils::TestLogger::new();
127 let channel_id = chan.2;
130 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
134 // send (1) commitment_signed -.
135 // <- update_add_htlc/commitment_signed
136 // send (2) RAA (awaiting remote revoke) -.
137 // (1) commitment_signed is delivered ->
138 // .- send (3) RAA (awaiting remote revoke)
139 // (2) RAA is delivered ->
140 // .- send (4) commitment_signed
141 // <- (3) RAA is delivered
142 // send (5) commitment_signed -.
143 // <- (4) commitment_signed is delivered
145 // (5) commitment_signed is delivered ->
147 // (6) RAA is delivered ->
149 // First nodes[0] generates an update_fee
150 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
151 check_added_monitors!(nodes[0], 1);
153 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
154 assert_eq!(events_0.len(), 1);
155 let (update_msg, commitment_signed) = match events_0[0] { // (1)
156 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
157 (update_fee.as_ref(), commitment_signed)
159 _ => panic!("Unexpected event"),
162 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
165 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
166 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
167 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
168 check_added_monitors!(nodes[1], 1);
170 let payment_event = {
171 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
172 assert_eq!(events_1.len(), 1);
173 SendEvent::from_event(events_1.remove(0))
175 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
176 assert_eq!(payment_event.msgs.len(), 1);
178 // ...now when the messages get delivered everyone should be happy
179 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
180 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
181 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
182 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
183 check_added_monitors!(nodes[0], 1);
185 // deliver(1), generate (3):
186 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
187 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
188 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
189 check_added_monitors!(nodes[1], 1);
191 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
192 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
193 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
194 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
195 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
196 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
197 assert!(bs_update.update_fee.is_none()); // (4)
198 check_added_monitors!(nodes[1], 1);
200 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
201 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
202 assert!(as_update.update_add_htlcs.is_empty()); // (5)
203 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
204 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
205 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
206 assert!(as_update.update_fee.is_none()); // (5)
207 check_added_monitors!(nodes[0], 1);
209 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
210 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
211 // only (6) so get_event_msg's assert(len == 1) passes
212 check_added_monitors!(nodes[0], 1);
214 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
215 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
216 check_added_monitors!(nodes[1], 1);
218 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
219 check_added_monitors!(nodes[0], 1);
221 let events_2 = nodes[0].node.get_and_clear_pending_events();
222 assert_eq!(events_2.len(), 1);
224 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
225 _ => panic!("Unexpected event"),
228 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
229 check_added_monitors!(nodes[1], 1);
233 fn test_update_fee_unordered_raa() {
234 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
235 // crash in an earlier version of the update_fee patch)
236 let chanmon_cfgs = create_chanmon_cfgs(2);
237 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
238 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
239 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
240 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
241 let channel_id = chan.2;
242 let logger = test_utils::TestLogger::new();
245 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247 // First nodes[0] generates an update_fee
248 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
249 check_added_monitors!(nodes[0], 1);
251 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
252 assert_eq!(events_0.len(), 1);
253 let update_msg = match events_0[0] { // (1)
254 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
257 _ => panic!("Unexpected event"),
260 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
263 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
264 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
265 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
266 check_added_monitors!(nodes[1], 1);
268 let payment_event = {
269 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
270 assert_eq!(events_1.len(), 1);
271 SendEvent::from_event(events_1.remove(0))
273 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
274 assert_eq!(payment_event.msgs.len(), 1);
276 // ...now when the messages get delivered everyone should be happy
277 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
278 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
279 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
280 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
281 check_added_monitors!(nodes[0], 1);
283 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
284 check_added_monitors!(nodes[1], 1);
286 // We can't continue, sadly, because our (1) now has a bogus signature
290 fn test_multi_flight_update_fee() {
291 let chanmon_cfgs = create_chanmon_cfgs(2);
292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
294 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
295 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
296 let channel_id = chan.2;
299 // update_fee/commitment_signed ->
300 // .- send (1) RAA and (2) commitment_signed
301 // update_fee (never committed) ->
303 // We have to manually generate the above update_fee, it is allowed by the protocol but we
304 // don't track which updates correspond to which revoke_and_ack responses so we're in
305 // AwaitingRAA mode and will not generate the update_fee yet.
306 // <- (1) RAA delivered
307 // (3) is generated and send (4) CS -.
308 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
309 // know the per_commitment_point to use for it.
310 // <- (2) commitment_signed delivered
312 // B should send no response here
313 // (4) commitment_signed delivered ->
314 // <- RAA/commitment_signed delivered
317 // First nodes[0] generates an update_fee
318 let initial_feerate = get_feerate!(nodes[0], channel_id);
319 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
320 check_added_monitors!(nodes[0], 1);
322 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
323 assert_eq!(events_0.len(), 1);
324 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
325 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
326 (update_fee.as_ref().unwrap(), commitment_signed)
328 _ => panic!("Unexpected event"),
331 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
332 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
333 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
334 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
335 check_added_monitors!(nodes[1], 1);
337 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
340 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
341 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343 // Create the (3) update_fee message that nodes[0] will generate before it does...
344 let mut update_msg_2 = msgs::UpdateFee {
345 channel_id: update_msg_1.channel_id.clone(),
346 feerate_per_kw: (initial_feerate + 30) as u32,
349 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355 // Deliver (1), generating (3) and (4)
356 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
357 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
358 check_added_monitors!(nodes[0], 1);
359 assert!(as_second_update.update_add_htlcs.is_empty());
360 assert!(as_second_update.update_fulfill_htlcs.is_empty());
361 assert!(as_second_update.update_fail_htlcs.is_empty());
362 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
363 // Check that the update_fee newly generated matches what we delivered:
364 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
365 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367 // Deliver (2) commitment_signed
368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
369 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370 check_added_monitors!(nodes[0], 1);
371 // No commitment_signed so get_event_msg's assert(len == 1) passes
373 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
374 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
375 check_added_monitors!(nodes[1], 1);
378 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
379 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
380 check_added_monitors!(nodes[1], 1);
382 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
383 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
384 check_added_monitors!(nodes[0], 1);
386 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
387 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
388 // No commitment_signed so get_event_msg's assert(len == 1) passes
389 check_added_monitors!(nodes[0], 1);
391 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
392 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
393 check_added_monitors!(nodes[1], 1);
397 fn test_1_conf_open() {
398 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
399 // tests that we properly send one in that case.
400 let mut alice_config = UserConfig::default();
401 alice_config.own_channel_config.minimum_depth = 1;
402 alice_config.channel_options.announced_channel = true;
403 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
404 let mut bob_config = UserConfig::default();
405 bob_config.own_channel_config.minimum_depth = 1;
406 bob_config.channel_options.announced_channel = true;
407 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
408 let chanmon_cfgs = create_chanmon_cfgs(2);
409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
411 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
413 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
418 connect_block(&nodes[1], &block, 1);
419 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()));
421 connect_block(&nodes[0], &block, 1);
422 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
423 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
426 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
427 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
428 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
432 fn do_test_sanity_on_in_flight_opens(steps: u8) {
433 // Previously, we had issues deserializing channels when we hadn't connected the first block
434 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
435 // serialization round-trips and simply do steps towards opening a channel and then drop the
438 let chanmon_cfgs = create_chanmon_cfgs(2);
439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
441 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
443 if steps & 0b1000_0000 != 0{
445 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
448 connect_block(&nodes[0], &block, 1);
449 connect_block(&nodes[1], &block, 1);
452 if steps & 0x0f == 0 { return; }
453 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
454 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
456 if steps & 0x0f == 1 { return; }
457 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
458 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
460 if steps & 0x0f == 2 { return; }
461 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
463 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
465 if steps & 0x0f == 3 { return; }
466 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
467 check_added_monitors!(nodes[0], 0);
468 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
470 if steps & 0x0f == 4 { return; }
471 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
473 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
474 assert_eq!(added_monitors.len(), 1);
475 assert_eq!(added_monitors[0].0, funding_output);
476 added_monitors.clear();
478 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
480 if steps & 0x0f == 5 { return; }
481 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
483 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
484 assert_eq!(added_monitors.len(), 1);
485 assert_eq!(added_monitors[0].0, funding_output);
486 added_monitors.clear();
489 let events_4 = nodes[0].node.get_and_clear_pending_events();
490 assert_eq!(events_4.len(), 1);
492 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
493 assert_eq!(user_channel_id, 42);
494 assert_eq!(*funding_txo, funding_output);
496 _ => panic!("Unexpected event"),
499 if steps & 0x0f == 6 { return; }
500 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
502 if steps & 0x0f == 7 { return; }
503 confirm_transaction(&nodes[0], &tx);
504 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
508 fn test_sanity_on_in_flight_opens() {
509 do_test_sanity_on_in_flight_opens(0);
510 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
511 do_test_sanity_on_in_flight_opens(1);
512 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
513 do_test_sanity_on_in_flight_opens(2);
514 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
515 do_test_sanity_on_in_flight_opens(3);
516 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
517 do_test_sanity_on_in_flight_opens(4);
518 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
519 do_test_sanity_on_in_flight_opens(5);
520 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
521 do_test_sanity_on_in_flight_opens(6);
522 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
523 do_test_sanity_on_in_flight_opens(7);
524 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
525 do_test_sanity_on_in_flight_opens(8);
526 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
530 fn test_update_fee_vanilla() {
531 let chanmon_cfgs = create_chanmon_cfgs(2);
532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
534 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
535 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
536 let channel_id = chan.2;
538 let feerate = get_feerate!(nodes[0], channel_id);
539 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
540 check_added_monitors!(nodes[0], 1);
542 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
543 assert_eq!(events_0.len(), 1);
544 let (update_msg, commitment_signed) = match events_0[0] {
545 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 } } => {
546 (update_fee.as_ref(), commitment_signed)
548 _ => panic!("Unexpected event"),
550 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
552 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
553 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
554 check_added_monitors!(nodes[1], 1);
556 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
557 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
558 check_added_monitors!(nodes[0], 1);
560 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
561 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
562 // No commitment_signed so get_event_msg's assert(len == 1) passes
563 check_added_monitors!(nodes[0], 1);
565 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
566 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
567 check_added_monitors!(nodes[1], 1);
571 fn test_update_fee_that_funder_cannot_afford() {
572 let chanmon_cfgs = create_chanmon_cfgs(2);
573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
575 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
576 let channel_value = 1888;
577 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
578 let channel_id = chan.2;
581 nodes[0].node.update_fee(channel_id, feerate).unwrap();
582 check_added_monitors!(nodes[0], 1);
583 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
585 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
587 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
589 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
590 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
592 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
594 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
595 let num_htlcs = commitment_tx.output.len() - 2;
596 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
597 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
598 actual_fee = channel_value - actual_fee;
599 assert_eq!(total_fee, actual_fee);
602 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
603 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
604 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
605 check_added_monitors!(nodes[0], 1);
607 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
609 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
611 //While producing the commitment_signed response after handling a received update_fee request the
612 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
613 //Should produce and error.
614 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
615 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
616 check_added_monitors!(nodes[1], 1);
617 check_closed_broadcast!(nodes[1], true);
621 fn test_update_fee_with_fundee_update_add_htlc() {
622 let chanmon_cfgs = create_chanmon_cfgs(2);
623 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
624 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
625 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
626 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
627 let channel_id = chan.2;
628 let logger = test_utils::TestLogger::new();
631 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
633 let feerate = get_feerate!(nodes[0], channel_id);
634 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
635 check_added_monitors!(nodes[0], 1);
637 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
638 assert_eq!(events_0.len(), 1);
639 let (update_msg, commitment_signed) = match events_0[0] {
640 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 } } => {
641 (update_fee.as_ref(), commitment_signed)
643 _ => panic!("Unexpected event"),
645 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
646 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
647 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
648 check_added_monitors!(nodes[1], 1);
650 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
651 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
652 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();
654 // nothing happens since node[1] is in AwaitingRemoteRevoke
655 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
657 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
658 assert_eq!(added_monitors.len(), 0);
659 added_monitors.clear();
661 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
662 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
663 // node[1] has nothing to do
665 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
666 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
667 check_added_monitors!(nodes[0], 1);
669 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
670 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
671 // No commitment_signed so get_event_msg's assert(len == 1) passes
672 check_added_monitors!(nodes[0], 1);
673 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
674 check_added_monitors!(nodes[1], 1);
675 // AwaitingRemoteRevoke ends here
677 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
678 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
679 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
680 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
681 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
682 assert_eq!(commitment_update.update_fee.is_none(), true);
684 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
685 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
686 check_added_monitors!(nodes[0], 1);
687 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
689 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
690 check_added_monitors!(nodes[1], 1);
691 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
693 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
694 check_added_monitors!(nodes[1], 1);
695 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
696 // No commitment_signed so get_event_msg's assert(len == 1) passes
698 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
699 check_added_monitors!(nodes[0], 1);
700 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
702 expect_pending_htlcs_forwardable!(nodes[0]);
704 let events = nodes[0].node.get_and_clear_pending_events();
705 assert_eq!(events.len(), 1);
707 Event::PaymentReceived { .. } => { },
708 _ => panic!("Unexpected event"),
711 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
713 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
714 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
715 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
719 fn test_update_fee() {
720 let chanmon_cfgs = create_chanmon_cfgs(2);
721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
723 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
724 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
725 let channel_id = chan.2;
728 // (1) update_fee/commitment_signed ->
729 // <- (2) revoke_and_ack
730 // .- send (3) commitment_signed
731 // (4) update_fee/commitment_signed ->
732 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
733 // <- (3) commitment_signed delivered
734 // send (6) revoke_and_ack -.
735 // <- (5) deliver revoke_and_ack
736 // (6) deliver revoke_and_ack ->
737 // .- send (7) commitment_signed in response to (4)
738 // <- (7) deliver commitment_signed
741 // Create and deliver (1)...
742 let feerate = get_feerate!(nodes[0], channel_id);
743 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
744 check_added_monitors!(nodes[0], 1);
746 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
747 assert_eq!(events_0.len(), 1);
748 let (update_msg, commitment_signed) = match events_0[0] {
749 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 } } => {
750 (update_fee.as_ref(), commitment_signed)
752 _ => panic!("Unexpected event"),
754 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
756 // Generate (2) and (3):
757 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
758 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
759 check_added_monitors!(nodes[1], 1);
762 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
763 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
764 check_added_monitors!(nodes[0], 1);
766 // Create and deliver (4)...
767 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
768 check_added_monitors!(nodes[0], 1);
769 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770 assert_eq!(events_0.len(), 1);
771 let (update_msg, commitment_signed) = match events_0[0] {
772 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 } } => {
773 (update_fee.as_ref(), commitment_signed)
775 _ => panic!("Unexpected event"),
778 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
779 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
780 check_added_monitors!(nodes[1], 1);
782 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
783 // No commitment_signed so get_event_msg's assert(len == 1) passes
785 // Handle (3), creating (6):
786 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
787 check_added_monitors!(nodes[0], 1);
788 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
789 // No commitment_signed so get_event_msg's assert(len == 1) passes
792 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
793 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
794 check_added_monitors!(nodes[0], 1);
796 // Deliver (6), creating (7):
797 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
798 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799 assert!(commitment_update.update_add_htlcs.is_empty());
800 assert!(commitment_update.update_fulfill_htlcs.is_empty());
801 assert!(commitment_update.update_fail_htlcs.is_empty());
802 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
803 assert!(commitment_update.update_fee.is_none());
804 check_added_monitors!(nodes[1], 1);
807 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
808 check_added_monitors!(nodes[0], 1);
809 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
810 // No commitment_signed so get_event_msg's assert(len == 1) passes
812 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
813 check_added_monitors!(nodes[1], 1);
814 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
816 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
817 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
818 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
822 fn pre_funding_lock_shutdown_test() {
823 // Test sending a shutdown prior to funding_locked after funding generation
824 let chanmon_cfgs = create_chanmon_cfgs(2);
825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
827 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
828 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
829 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
830 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
831 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
833 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
834 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
835 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
836 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
837 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
839 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
840 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
841 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
842 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
843 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
844 assert!(node_0_none.is_none());
846 assert!(nodes[0].node.list_channels().is_empty());
847 assert!(nodes[1].node.list_channels().is_empty());
851 fn updates_shutdown_wait() {
852 // Test sending a shutdown with outstanding updates pending
853 let chanmon_cfgs = create_chanmon_cfgs(3);
854 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
855 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
856 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
857 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
858 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
859 let logger = test_utils::TestLogger::new();
861 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
863 nodes[0].node.close_channel(&chan_1.2).unwrap();
864 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
865 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
866 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
867 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
872 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
874 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
875 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
876 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();
877 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();
878 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
879 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
881 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
882 check_added_monitors!(nodes[2], 1);
883 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
884 assert!(updates.update_add_htlcs.is_empty());
885 assert!(updates.update_fail_htlcs.is_empty());
886 assert!(updates.update_fail_malformed_htlcs.is_empty());
887 assert!(updates.update_fee.is_none());
888 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
889 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
890 check_added_monitors!(nodes[1], 1);
891 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
894 assert!(updates_2.update_add_htlcs.is_empty());
895 assert!(updates_2.update_fail_htlcs.is_empty());
896 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
897 assert!(updates_2.update_fee.is_none());
898 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
899 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
900 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
902 let events = nodes[0].node.get_and_clear_pending_events();
903 assert_eq!(events.len(), 1);
905 Event::PaymentSent { ref payment_preimage } => {
906 assert_eq!(our_payment_preimage, *payment_preimage);
908 _ => panic!("Unexpected event"),
911 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
912 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
913 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
914 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
915 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
916 assert!(node_0_none.is_none());
918 assert!(nodes[0].node.list_channels().is_empty());
920 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
921 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
922 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
923 assert!(nodes[1].node.list_channels().is_empty());
924 assert!(nodes[2].node.list_channels().is_empty());
928 fn htlc_fail_async_shutdown() {
929 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
930 let chanmon_cfgs = create_chanmon_cfgs(3);
931 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
932 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
933 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
934 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
935 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
936 let logger = test_utils::TestLogger::new();
938 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
939 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
940 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();
941 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
942 check_added_monitors!(nodes[0], 1);
943 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
944 assert_eq!(updates.update_add_htlcs.len(), 1);
945 assert!(updates.update_fulfill_htlcs.is_empty());
946 assert!(updates.update_fail_htlcs.is_empty());
947 assert!(updates.update_fail_malformed_htlcs.is_empty());
948 assert!(updates.update_fee.is_none());
950 nodes[1].node.close_channel(&chan_1.2).unwrap();
951 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
952 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
953 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
955 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
956 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
957 check_added_monitors!(nodes[1], 1);
958 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
959 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
961 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
962 assert!(updates_2.update_add_htlcs.is_empty());
963 assert!(updates_2.update_fulfill_htlcs.is_empty());
964 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
965 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
966 assert!(updates_2.update_fee.is_none());
968 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
969 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
971 expect_payment_failed!(nodes[0], our_payment_hash, false);
973 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
974 assert_eq!(msg_events.len(), 2);
975 let node_0_closing_signed = match msg_events[0] {
976 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
977 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
980 _ => panic!("Unexpected event"),
982 match msg_events[1] {
983 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
984 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
986 _ => panic!("Unexpected event"),
989 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
990 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
991 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
992 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
993 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
994 assert!(node_0_none.is_none());
996 assert!(nodes[0].node.list_channels().is_empty());
998 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
999 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1000 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1001 assert!(nodes[1].node.list_channels().is_empty());
1002 assert!(nodes[2].node.list_channels().is_empty());
1005 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1006 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1007 // messages delivered prior to disconnect
1008 let chanmon_cfgs = create_chanmon_cfgs(3);
1009 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1010 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1011 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1012 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1013 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1015 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1017 nodes[1].node.close_channel(&chan_1.2).unwrap();
1018 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1020 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1021 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1023 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1027 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1030 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1031 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1032 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1033 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1035 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1036 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1037 assert!(node_1_shutdown == node_1_2nd_shutdown);
1039 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1040 let node_0_2nd_shutdown = if recv_count > 0 {
1041 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1042 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1045 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1046 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1047 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1049 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1051 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1052 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1054 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1055 check_added_monitors!(nodes[2], 1);
1056 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1057 assert!(updates.update_add_htlcs.is_empty());
1058 assert!(updates.update_fail_htlcs.is_empty());
1059 assert!(updates.update_fail_malformed_htlcs.is_empty());
1060 assert!(updates.update_fee.is_none());
1061 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1062 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1063 check_added_monitors!(nodes[1], 1);
1064 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1067 assert!(updates_2.update_add_htlcs.is_empty());
1068 assert!(updates_2.update_fail_htlcs.is_empty());
1069 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1070 assert!(updates_2.update_fee.is_none());
1071 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1072 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1073 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1075 let events = nodes[0].node.get_and_clear_pending_events();
1076 assert_eq!(events.len(), 1);
1078 Event::PaymentSent { ref payment_preimage } => {
1079 assert_eq!(our_payment_preimage, *payment_preimage);
1081 _ => panic!("Unexpected event"),
1084 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1086 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1087 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1088 assert!(node_1_closing_signed.is_some());
1091 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1092 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1094 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1095 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1096 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1097 if recv_count == 0 {
1098 // If all closing_signeds weren't delivered we can just resume where we left off...
1099 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1101 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1102 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1103 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1105 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1106 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1107 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1109 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1110 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1112 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1113 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1114 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1116 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1117 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1118 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1119 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1120 assert!(node_0_none.is_none());
1122 // If one node, however, received + responded with an identical closing_signed we end
1123 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1124 // There isn't really anything better we can do simply, but in the future we might
1125 // explore storing a set of recently-closed channels that got disconnected during
1126 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1127 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1129 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1131 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1132 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1133 assert_eq!(msg_events.len(), 1);
1134 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1136 &ErrorAction::SendErrorMessage { ref msg } => {
1137 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1138 assert_eq!(msg.channel_id, chan_1.2);
1140 _ => panic!("Unexpected event!"),
1142 } else { panic!("Needed SendErrorMessage close"); }
1144 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1145 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1146 // closing_signed so we do it ourselves
1147 check_closed_broadcast!(nodes[0], false);
1148 check_added_monitors!(nodes[0], 1);
1151 assert!(nodes[0].node.list_channels().is_empty());
1153 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1154 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1155 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1156 assert!(nodes[1].node.list_channels().is_empty());
1157 assert!(nodes[2].node.list_channels().is_empty());
1161 fn test_shutdown_rebroadcast() {
1162 do_test_shutdown_rebroadcast(0);
1163 do_test_shutdown_rebroadcast(1);
1164 do_test_shutdown_rebroadcast(2);
1168 fn fake_network_test() {
1169 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1170 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1171 let chanmon_cfgs = create_chanmon_cfgs(4);
1172 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1173 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1174 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1176 // Create some initial channels
1177 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1178 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1179 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1181 // Rebalance the network a bit by relaying one payment through all the channels...
1182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1183 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1184 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1185 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1187 // Send some more payments
1188 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1189 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1190 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1192 // Test failure packets
1193 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1194 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1196 // Add a new channel that skips 3
1197 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1199 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1200 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_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);
1203 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1204 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1205 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207 // Do some rebalance loop payments, simultaneously
1208 let mut hops = Vec::with_capacity(3);
1209 hops.push(RouteHop {
1210 pubkey: nodes[2].node.get_our_node_id(),
1211 node_features: NodeFeatures::empty(),
1212 short_channel_id: chan_2.0.contents.short_channel_id,
1213 channel_features: ChannelFeatures::empty(),
1215 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1217 hops.push(RouteHop {
1218 pubkey: nodes[3].node.get_our_node_id(),
1219 node_features: NodeFeatures::empty(),
1220 short_channel_id: chan_3.0.contents.short_channel_id,
1221 channel_features: ChannelFeatures::empty(),
1223 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1225 hops.push(RouteHop {
1226 pubkey: nodes[1].node.get_our_node_id(),
1227 node_features: NodeFeatures::empty(),
1228 short_channel_id: chan_4.0.contents.short_channel_id,
1229 channel_features: ChannelFeatures::empty(),
1231 cltv_expiry_delta: TEST_FINAL_CLTV,
1233 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;
1234 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;
1235 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1237 let mut hops = Vec::with_capacity(3);
1238 hops.push(RouteHop {
1239 pubkey: nodes[3].node.get_our_node_id(),
1240 node_features: NodeFeatures::empty(),
1241 short_channel_id: chan_4.0.contents.short_channel_id,
1242 channel_features: ChannelFeatures::empty(),
1244 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1246 hops.push(RouteHop {
1247 pubkey: nodes[2].node.get_our_node_id(),
1248 node_features: NodeFeatures::empty(),
1249 short_channel_id: chan_3.0.contents.short_channel_id,
1250 channel_features: ChannelFeatures::empty(),
1252 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1254 hops.push(RouteHop {
1255 pubkey: nodes[1].node.get_our_node_id(),
1256 node_features: NodeFeatures::empty(),
1257 short_channel_id: chan_2.0.contents.short_channel_id,
1258 channel_features: ChannelFeatures::empty(),
1260 cltv_expiry_delta: TEST_FINAL_CLTV,
1262 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;
1263 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;
1264 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1266 // Claim the rebalances...
1267 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1268 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1270 // Add a duplicate new channel from 2 to 4
1271 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1273 // Send some payments across both channels
1274 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1275 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1276 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1280 let events = nodes[0].node.get_and_clear_pending_msg_events();
1281 assert_eq!(events.len(), 0);
1282 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);
1284 //TODO: Test that routes work again here as we've been notified that the channel is full
1286 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1287 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1288 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1290 // Close down the channels...
1291 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1292 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1293 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1294 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1295 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1299 fn holding_cell_htlc_counting() {
1300 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1301 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1302 // commitment dance rounds.
1303 let chanmon_cfgs = create_chanmon_cfgs(3);
1304 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1305 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1306 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1307 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1308 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1309 let logger = test_utils::TestLogger::new();
1311 let mut payments = Vec::new();
1312 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1313 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1314 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1315 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();
1316 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1317 payments.push((payment_preimage, payment_hash));
1319 check_added_monitors!(nodes[1], 1);
1321 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1322 assert_eq!(events.len(), 1);
1323 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1324 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1326 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1327 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1329 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1331 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1332 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();
1333 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1334 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1335 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1336 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1339 // This should also be true if we try to forward a payment.
1340 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1342 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1343 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();
1344 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1345 check_added_monitors!(nodes[0], 1);
1348 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1349 assert_eq!(events.len(), 1);
1350 let payment_event = SendEvent::from_event(events.pop().unwrap());
1351 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1354 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1355 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1356 // fails), the second will process the resulting failure and fail the HTLC backward.
1357 expect_pending_htlcs_forwardable!(nodes[1]);
1358 expect_pending_htlcs_forwardable!(nodes[1]);
1359 check_added_monitors!(nodes[1], 1);
1361 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1362 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1363 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1365 let events = nodes[0].node.get_and_clear_pending_msg_events();
1366 assert_eq!(events.len(), 1);
1368 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1369 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1371 _ => panic!("Unexpected event"),
1374 expect_payment_failed!(nodes[0], payment_hash_2, false);
1376 // Now forward all the pending HTLCs and claim them back
1377 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1378 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1379 check_added_monitors!(nodes[2], 1);
1381 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1382 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1383 check_added_monitors!(nodes[1], 1);
1384 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1386 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1387 check_added_monitors!(nodes[1], 1);
1388 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1390 for ref update in as_updates.update_add_htlcs.iter() {
1391 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1393 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1394 check_added_monitors!(nodes[2], 1);
1395 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1396 check_added_monitors!(nodes[2], 1);
1397 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1399 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1400 check_added_monitors!(nodes[1], 1);
1401 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1402 check_added_monitors!(nodes[1], 1);
1403 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1405 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1406 check_added_monitors!(nodes[2], 1);
1408 expect_pending_htlcs_forwardable!(nodes[2]);
1410 let events = nodes[2].node.get_and_clear_pending_events();
1411 assert_eq!(events.len(), payments.len());
1412 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1414 &Event::PaymentReceived { ref payment_hash, .. } => {
1415 assert_eq!(*payment_hash, *hash);
1417 _ => panic!("Unexpected event"),
1421 for (preimage, _) in payments.drain(..) {
1422 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1425 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1429 fn duplicate_htlc_test() {
1430 // Test that we accept duplicate payment_hash HTLCs across the network and that
1431 // claiming/failing them are all separate and don't affect each other
1432 let chanmon_cfgs = create_chanmon_cfgs(6);
1433 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1434 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1435 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1437 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1438 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1439 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1440 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1441 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1442 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1444 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1446 *nodes[0].network_payment_count.borrow_mut() -= 1;
1447 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1449 *nodes[0].network_payment_count.borrow_mut() -= 1;
1450 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1452 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1453 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1454 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1458 fn test_duplicate_htlc_different_direction_onchain() {
1459 // Test that ChannelMonitor doesn't generate 2 preimage txn
1460 // when we have 2 HTLCs with same preimage that go across a node
1461 // in opposite directions.
1462 let chanmon_cfgs = create_chanmon_cfgs(2);
1463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1467 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1468 let logger = test_utils::TestLogger::new();
1471 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1473 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1475 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1476 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();
1477 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1479 // Provide preimage to node 0 by claiming payment
1480 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1481 check_added_monitors!(nodes[0], 1);
1483 // Broadcast node 1 commitment txn
1484 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1486 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1487 let mut has_both_htlcs = 0; // check htlcs match ones committed
1488 for outp in remote_txn[0].output.iter() {
1489 if outp.value == 800_000 / 1000 {
1490 has_both_htlcs += 1;
1491 } else if outp.value == 900_000 / 1000 {
1492 has_both_htlcs += 1;
1495 assert_eq!(has_both_htlcs, 2);
1497 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1498 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1499 check_added_monitors!(nodes[0], 1);
1501 // Check we only broadcast 1 timeout tx
1502 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1503 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()) };
1504 assert_eq!(claim_txn.len(), 5);
1505 check_spends!(claim_txn[2], chan_1.3);
1506 check_spends!(claim_txn[3], claim_txn[2]);
1507 assert_eq!(htlc_pair.0.input.len(), 1);
1508 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1509 check_spends!(htlc_pair.0, remote_txn[0]);
1510 assert_eq!(htlc_pair.1.input.len(), 1);
1511 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1512 check_spends!(htlc_pair.1, remote_txn[0]);
1514 let events = nodes[0].node.get_and_clear_pending_msg_events();
1515 assert_eq!(events.len(), 2);
1518 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1519 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, .. } } => {
1520 assert!(update_add_htlcs.is_empty());
1521 assert!(update_fail_htlcs.is_empty());
1522 assert_eq!(update_fulfill_htlcs.len(), 1);
1523 assert!(update_fail_malformed_htlcs.is_empty());
1524 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1526 _ => panic!("Unexpected event"),
1532 fn test_basic_channel_reserve() {
1533 let chanmon_cfgs = create_chanmon_cfgs(2);
1534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1536 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1537 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1538 let logger = test_utils::TestLogger::new();
1540 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1541 let channel_reserve = chan_stat.channel_reserve_msat;
1543 // The 2* and +1 are for the fee spike reserve.
1544 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1545 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1546 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1547 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1548 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();
1549 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1551 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1553 &APIError::ChannelUnavailable{ref err} =>
1554 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1555 _ => panic!("Unexpected error variant"),
1558 _ => panic!("Unexpected error variant"),
1560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1561 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);
1563 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1567 fn test_fee_spike_violation_fails_htlc() {
1568 let chanmon_cfgs = create_chanmon_cfgs(2);
1569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1573 let logger = test_utils::TestLogger::new();
1575 macro_rules! get_route_and_payment_hash {
1576 ($recv_value: expr) => {{
1577 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1578 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1579 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();
1580 (route, payment_hash, payment_preimage)
1584 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1585 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1586 let secp_ctx = Secp256k1::new();
1587 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1589 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1591 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1592 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1593 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1594 let msg = msgs::UpdateAddHTLC {
1597 amount_msat: htlc_msat,
1598 payment_hash: payment_hash,
1599 cltv_expiry: htlc_cltv,
1600 onion_routing_packet: onion_packet,
1603 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1605 // Now manually create the commitment_signed message corresponding to the update_add
1606 // nodes[0] just sent. In the code for construction of this message, "local" refers
1607 // to the sender of the message, and "remote" refers to the receiver.
1609 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1611 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1613 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1614 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1615 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1616 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1617 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1618 let chan_signer = local_chan.get_signer();
1619 let pubkeys = chan_signer.pubkeys();
1620 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1621 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1622 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1624 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1625 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1626 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1627 let chan_signer = remote_chan.get_signer();
1628 let pubkeys = chan_signer.pubkeys();
1629 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1630 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1633 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1634 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1635 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1637 // Build the remote commitment transaction so we can sign it, and then later use the
1638 // signature for the commitment_signed message.
1639 let local_chan_balance = 1313;
1641 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1643 amount_msat: 3460001,
1644 cltv_expiry: htlc_cltv,
1646 transaction_output_index: Some(1),
1649 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1652 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1653 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1654 let local_chan_signer = local_chan.get_signer();
1655 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1659 commit_tx_keys.clone(),
1661 &mut vec![(accepted_htlc_info, ())],
1662 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1664 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1667 let commit_signed_msg = msgs::CommitmentSigned {
1670 htlc_signatures: res.1
1673 // Send the commitment_signed message to the nodes[1].
1674 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1675 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1677 // Send the RAA to nodes[1].
1678 let raa_msg = msgs::RevokeAndACK {
1680 per_commitment_secret: local_secret,
1681 next_per_commitment_point: next_local_point
1683 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1685 let events = nodes[1].node.get_and_clear_pending_msg_events();
1686 assert_eq!(events.len(), 1);
1687 // Make sure the HTLC failed in the way we expect.
1689 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1690 assert_eq!(update_fail_htlcs.len(), 1);
1691 update_fail_htlcs[0].clone()
1693 _ => panic!("Unexpected event"),
1695 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1697 check_added_monitors!(nodes[1], 2);
1701 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1702 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1703 // Set the fee rate for the channel very high, to the point where the fundee
1704 // sending any above-dust amount would result in a channel reserve violation.
1705 // In this test we check that we would be prevented from sending an HTLC in
1707 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1708 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1711 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1712 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1713 let logger = test_utils::TestLogger::new();
1715 macro_rules! get_route_and_payment_hash {
1716 ($recv_value: expr) => {{
1717 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1718 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1719 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();
1720 (route, payment_hash, payment_preimage)
1724 let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1725 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1726 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1727 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1728 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);
1732 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1733 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1734 // Set the fee rate for the channel very high, to the point where the funder
1735 // receiving 1 update_add_htlc would result in them closing the channel due
1736 // to channel reserve violation. This close could also happen if the fee went
1737 // up a more realistic amount, but many HTLCs were outstanding at the time of
1738 // the update_add_htlc.
1739 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1740 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1741 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1742 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1743 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1745 let logger = test_utils::TestLogger::new();
1747 macro_rules! get_route_and_payment_hash {
1748 ($recv_value: expr) => {{
1749 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1750 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1751 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();
1752 (route, payment_hash, payment_preimage)
1756 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1757 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1758 let secp_ctx = Secp256k1::new();
1759 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1760 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1761 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1762 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1763 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1764 let msg = msgs::UpdateAddHTLC {
1767 amount_msat: htlc_msat + 1,
1768 payment_hash: payment_hash,
1769 cltv_expiry: htlc_cltv,
1770 onion_routing_packet: onion_packet,
1773 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1774 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1775 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);
1776 assert_eq!(nodes[0].node.list_channels().len(), 0);
1777 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1778 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1779 check_added_monitors!(nodes[0], 1);
1783 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1784 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1785 // calculating our commitment transaction fee (this was previously broken).
1786 let chanmon_cfgs = create_chanmon_cfgs(2);
1787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1789 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1791 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1792 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1793 // transaction fee with 0 HTLCs (183 sats)).
1794 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1796 let dust_amt = 546000; // Dust amount
1797 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1798 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1799 // commitment transaction fee.
1800 let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1804 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1805 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1806 // calculating our counterparty's commitment transaction fee (this was previously broken).
1807 let chanmon_cfgs = create_chanmon_cfgs(2);
1808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1810 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1813 let payment_amt = 46000; // Dust amount
1814 // In the previous code, these first four payments would succeed.
1815 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1817 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1820 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1821 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1823 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1824 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1825 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1827 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1828 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1829 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1830 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1834 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1835 let chanmon_cfgs = create_chanmon_cfgs(3);
1836 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1838 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1840 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1841 let logger = test_utils::TestLogger::new();
1843 macro_rules! get_route_and_payment_hash {
1844 ($recv_value: expr) => {{
1845 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1846 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1847 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();
1848 (route, payment_hash, payment_preimage)
1853 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1854 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1855 let feerate = get_feerate!(nodes[0], chan.2);
1857 // Add a 2* and +1 for the fee spike reserve.
1858 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1859 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;
1860 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1862 // Add a pending HTLC.
1863 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1864 let payment_event_1 = {
1865 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1866 check_added_monitors!(nodes[0], 1);
1868 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1869 assert_eq!(events.len(), 1);
1870 SendEvent::from_event(events.remove(0))
1872 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1874 // Attempt to trigger a channel reserve violation --> payment failure.
1875 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1876 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;
1877 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1878 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1880 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1881 let secp_ctx = Secp256k1::new();
1882 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1883 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1884 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1885 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1886 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1887 let msg = msgs::UpdateAddHTLC {
1890 amount_msat: htlc_msat + 1,
1891 payment_hash: our_payment_hash_1,
1892 cltv_expiry: htlc_cltv,
1893 onion_routing_packet: onion_packet,
1896 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1897 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1898 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1899 assert_eq!(nodes[1].node.list_channels().len(), 1);
1900 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1901 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1902 check_added_monitors!(nodes[1], 1);
1906 fn test_inbound_outbound_capacity_is_not_zero() {
1907 let chanmon_cfgs = create_chanmon_cfgs(2);
1908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1911 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1912 let channels0 = node_chanmgrs[0].list_channels();
1913 let channels1 = node_chanmgrs[1].list_channels();
1914 assert_eq!(channels0.len(), 1);
1915 assert_eq!(channels1.len(), 1);
1917 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1918 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1920 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1921 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1924 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1925 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1929 fn test_channel_reserve_holding_cell_htlcs() {
1930 let chanmon_cfgs = create_chanmon_cfgs(3);
1931 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1932 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1933 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1934 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1935 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1936 let logger = test_utils::TestLogger::new();
1938 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1939 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1941 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1942 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1944 macro_rules! get_route_and_payment_hash {
1945 ($recv_value: expr) => {{
1946 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1947 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1948 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();
1949 (route, payment_hash, payment_preimage)
1953 macro_rules! expect_forward {
1955 let mut events = $node.node.get_and_clear_pending_msg_events();
1956 assert_eq!(events.len(), 1);
1957 check_added_monitors!($node, 1);
1958 let payment_event = SendEvent::from_event(events.remove(0));
1963 let feemsat = 239; // somehow we know?
1964 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1965 let feerate = get_feerate!(nodes[0], chan_1.2);
1967 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1969 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1971 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1972 route.paths[0].last_mut().unwrap().fee_msat += 1;
1973 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1974 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1975 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)));
1976 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1977 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);
1980 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1981 // nodes[0]'s wealth
1983 let amt_msat = recv_value_0 + total_fee_msat;
1984 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1985 // Also, ensure that each payment has enough to be over the dust limit to
1986 // ensure it'll be included in each commit tx fee calculation.
1987 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1988 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1989 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1992 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1994 let (stat01_, stat11_, stat12_, stat22_) = (
1995 get_channel_value_stat!(nodes[0], chan_1.2),
1996 get_channel_value_stat!(nodes[1], chan_1.2),
1997 get_channel_value_stat!(nodes[1], chan_2.2),
1998 get_channel_value_stat!(nodes[2], chan_2.2),
2001 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2002 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2003 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2004 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2005 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2008 // adding pending output.
2009 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2010 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2011 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2012 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2013 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2014 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2015 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2016 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2017 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2019 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2020 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2021 let amt_msat_1 = recv_value_1 + total_fee_msat;
2023 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2024 let payment_event_1 = {
2025 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2026 check_added_monitors!(nodes[0], 1);
2028 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2029 assert_eq!(events.len(), 1);
2030 SendEvent::from_event(events.remove(0))
2032 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2034 // channel reserve test with htlc pending output > 0
2035 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2037 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2038 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2039 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2043 // split the rest to test holding cell
2044 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2045 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2046 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2047 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2049 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2050 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);
2053 // now see if they go through on both sides
2054 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2055 // but this will stuck in the holding cell
2056 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2057 check_added_monitors!(nodes[0], 0);
2058 let events = nodes[0].node.get_and_clear_pending_events();
2059 assert_eq!(events.len(), 0);
2061 // test with outbound holding cell amount > 0
2063 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2064 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2065 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2066 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2067 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);
2070 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2071 // this will also stuck in the holding cell
2072 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2073 check_added_monitors!(nodes[0], 0);
2074 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2075 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2077 // flush the pending htlc
2078 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2079 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2080 check_added_monitors!(nodes[1], 1);
2082 // the pending htlc should be promoted to committed
2083 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2084 check_added_monitors!(nodes[0], 1);
2085 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2087 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2088 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2089 // No commitment_signed so get_event_msg's assert(len == 1) passes
2090 check_added_monitors!(nodes[0], 1);
2092 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2093 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2094 check_added_monitors!(nodes[1], 1);
2096 expect_pending_htlcs_forwardable!(nodes[1]);
2098 let ref payment_event_11 = expect_forward!(nodes[1]);
2099 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2100 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2102 expect_pending_htlcs_forwardable!(nodes[2]);
2103 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2105 // flush the htlcs in the holding cell
2106 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2107 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2108 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2109 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2110 expect_pending_htlcs_forwardable!(nodes[1]);
2112 let ref payment_event_3 = expect_forward!(nodes[1]);
2113 assert_eq!(payment_event_3.msgs.len(), 2);
2114 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2115 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2117 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2118 expect_pending_htlcs_forwardable!(nodes[2]);
2120 let events = nodes[2].node.get_and_clear_pending_events();
2121 assert_eq!(events.len(), 2);
2123 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2124 assert_eq!(our_payment_hash_21, *payment_hash);
2125 assert_eq!(*payment_secret, None);
2126 assert_eq!(recv_value_21, amt);
2128 _ => panic!("Unexpected event"),
2131 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2132 assert_eq!(our_payment_hash_22, *payment_hash);
2133 assert_eq!(None, *payment_secret);
2134 assert_eq!(recv_value_22, amt);
2136 _ => panic!("Unexpected event"),
2139 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2140 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2141 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2143 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2144 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2145 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2147 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2148 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);
2149 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2150 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2151 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2153 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2154 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2158 fn channel_reserve_in_flight_removes() {
2159 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2160 // can send to its counterparty, but due to update ordering, the other side may not yet have
2161 // considered those HTLCs fully removed.
2162 // This tests that we don't count HTLCs which will not be included in the next remote
2163 // commitment transaction towards the reserve value (as it implies no commitment transaction
2164 // will be generated which violates the remote reserve value).
2165 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2167 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2168 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2169 // you only consider the value of the first HTLC, it may not),
2170 // * start routing a third HTLC from A to B,
2171 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2172 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2173 // * deliver the first fulfill from B
2174 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2176 // * deliver A's response CS and RAA.
2177 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2178 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2179 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2180 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2181 let chanmon_cfgs = create_chanmon_cfgs(2);
2182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2184 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2185 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2186 let logger = test_utils::TestLogger::new();
2188 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2189 // Route the first two HTLCs.
2190 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2191 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2193 // Start routing the third HTLC (this is just used to get everyone in the right state).
2194 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2196 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2197 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();
2198 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2199 check_added_monitors!(nodes[0], 1);
2200 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2201 assert_eq!(events.len(), 1);
2202 SendEvent::from_event(events.remove(0))
2205 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2206 // initial fulfill/CS.
2207 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2208 check_added_monitors!(nodes[1], 1);
2209 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2211 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2212 // remove the second HTLC when we send the HTLC back from B to A.
2213 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2214 check_added_monitors!(nodes[1], 1);
2215 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2217 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2218 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2219 check_added_monitors!(nodes[0], 1);
2220 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2221 expect_payment_sent!(nodes[0], payment_preimage_1);
2223 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2224 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2225 check_added_monitors!(nodes[1], 1);
2226 // B is already AwaitingRAA, so cant generate a CS here
2227 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2229 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2230 check_added_monitors!(nodes[1], 1);
2231 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2233 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2234 check_added_monitors!(nodes[0], 1);
2235 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2237 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2238 check_added_monitors!(nodes[1], 1);
2239 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2241 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2242 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2243 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2244 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2245 // on-chain as necessary).
2246 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2247 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2248 check_added_monitors!(nodes[0], 1);
2249 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2250 expect_payment_sent!(nodes[0], payment_preimage_2);
2252 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2253 check_added_monitors!(nodes[1], 1);
2254 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2256 expect_pending_htlcs_forwardable!(nodes[1]);
2257 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2259 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2260 // resolve the second HTLC from A's point of view.
2261 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2262 check_added_monitors!(nodes[0], 1);
2263 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2265 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2266 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2267 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2269 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2270 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();
2271 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2272 check_added_monitors!(nodes[1], 1);
2273 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2274 assert_eq!(events.len(), 1);
2275 SendEvent::from_event(events.remove(0))
2278 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2279 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2280 check_added_monitors!(nodes[0], 1);
2281 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2283 // Now just resolve all the outstanding messages/HTLCs for completeness...
2285 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2286 check_added_monitors!(nodes[1], 1);
2287 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2289 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2290 check_added_monitors!(nodes[1], 1);
2292 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2293 check_added_monitors!(nodes[0], 1);
2294 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2296 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2297 check_added_monitors!(nodes[1], 1);
2298 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2300 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2301 check_added_monitors!(nodes[0], 1);
2303 expect_pending_htlcs_forwardable!(nodes[0]);
2304 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2306 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2307 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2311 fn channel_monitor_network_test() {
2312 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2313 // tests that ChannelMonitor is able to recover from various states.
2314 let chanmon_cfgs = create_chanmon_cfgs(5);
2315 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2316 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2317 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2319 // Create some initial channels
2320 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2321 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2322 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2323 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2325 // Rebalance the network a bit by relaying one payment through all the channels...
2326 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2327 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2328 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2329 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2331 // Simple case with no pending HTLCs:
2332 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2333 check_added_monitors!(nodes[1], 1);
2335 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2336 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2337 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2338 check_added_monitors!(nodes[0], 1);
2339 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2341 get_announce_close_broadcast_events(&nodes, 0, 1);
2342 assert_eq!(nodes[0].node.list_channels().len(), 0);
2343 assert_eq!(nodes[1].node.list_channels().len(), 1);
2345 // One pending HTLC is discarded by the force-close:
2346 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2348 // Simple case of one pending HTLC to HTLC-Timeout
2349 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2350 check_added_monitors!(nodes[1], 1);
2352 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2353 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2354 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2355 check_added_monitors!(nodes[2], 1);
2356 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2358 get_announce_close_broadcast_events(&nodes, 1, 2);
2359 assert_eq!(nodes[1].node.list_channels().len(), 0);
2360 assert_eq!(nodes[2].node.list_channels().len(), 1);
2362 macro_rules! claim_funds {
2363 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2365 assert!($node.node.claim_funds($preimage, &None, $amount));
2366 check_added_monitors!($node, 1);
2368 let events = $node.node.get_and_clear_pending_msg_events();
2369 assert_eq!(events.len(), 1);
2371 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2372 assert!(update_add_htlcs.is_empty());
2373 assert!(update_fail_htlcs.is_empty());
2374 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2376 _ => panic!("Unexpected event"),
2382 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2383 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2384 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2385 check_added_monitors!(nodes[2], 1);
2386 let node2_commitment_txid;
2388 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2389 node2_commitment_txid = node_txn[0].txid();
2391 // Claim the payment on nodes[3], giving it knowledge of the preimage
2392 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2394 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2395 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2396 check_added_monitors!(nodes[3], 1);
2398 check_preimage_claim(&nodes[3], &node_txn);
2400 get_announce_close_broadcast_events(&nodes, 2, 3);
2401 assert_eq!(nodes[2].node.list_channels().len(), 0);
2402 assert_eq!(nodes[3].node.list_channels().len(), 1);
2404 { // Cheat and reset nodes[4]'s height to 1
2405 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2406 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2409 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2410 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2411 // One pending HTLC to time out:
2412 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2413 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2416 let (close_chan_update_1, close_chan_update_2) = {
2417 let mut block = Block {
2418 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2421 connect_block(&nodes[3], &block, 2);
2422 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2424 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2427 connect_block(&nodes[3], &block, i);
2429 let events = nodes[3].node.get_and_clear_pending_msg_events();
2430 assert_eq!(events.len(), 1);
2431 let close_chan_update_1 = match events[0] {
2432 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2435 _ => panic!("Unexpected event"),
2437 check_added_monitors!(nodes[3], 1);
2439 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2441 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442 node_txn.retain(|tx| {
2443 if tx.input[0].previous_output.txid == node2_commitment_txid {
2449 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2451 // Claim the payment on nodes[4], giving it knowledge of the preimage
2452 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2455 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2459 connect_block(&nodes[4], &block, 2);
2460 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2462 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2465 connect_block(&nodes[4], &block, i);
2467 let events = nodes[4].node.get_and_clear_pending_msg_events();
2468 assert_eq!(events.len(), 1);
2469 let close_chan_update_2 = match events[0] {
2470 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2473 _ => panic!("Unexpected event"),
2475 check_added_monitors!(nodes[4], 1);
2476 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2479 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2480 txdata: vec![node_txn[0].clone()],
2482 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2484 check_preimage_claim(&nodes[4], &node_txn);
2485 (close_chan_update_1, close_chan_update_2)
2487 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2488 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2489 assert_eq!(nodes[3].node.list_channels().len(), 0);
2490 assert_eq!(nodes[4].node.list_channels().len(), 0);
2494 fn test_justice_tx() {
2495 // Test justice txn built on revoked HTLC-Success tx, against both sides
2496 let mut alice_config = UserConfig::default();
2497 alice_config.channel_options.announced_channel = true;
2498 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2499 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2500 let mut bob_config = UserConfig::default();
2501 bob_config.channel_options.announced_channel = true;
2502 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2503 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2504 let user_cfgs = [Some(alice_config), Some(bob_config)];
2505 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2506 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2507 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2508 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2509 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2510 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2511 // Create some new channels:
2512 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2514 // A pending HTLC which will be revoked:
2515 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2516 // Get the will-be-revoked local txn from nodes[0]
2517 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2518 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2519 assert_eq!(revoked_local_txn[0].input.len(), 1);
2520 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2521 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2522 assert_eq!(revoked_local_txn[1].input.len(), 1);
2523 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2524 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2525 // Revoke the old state
2526 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2529 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2530 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2532 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2533 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2534 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2536 check_spends!(node_txn[0], revoked_local_txn[0]);
2537 node_txn.swap_remove(0);
2538 node_txn.truncate(1);
2540 check_added_monitors!(nodes[1], 1);
2541 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2543 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2544 // Verify broadcast of revoked HTLC-timeout
2545 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2546 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2547 check_added_monitors!(nodes[0], 1);
2548 // Broadcast revoked HTLC-timeout on node 1
2549 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2550 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2552 get_announce_close_broadcast_events(&nodes, 0, 1);
2554 assert_eq!(nodes[0].node.list_channels().len(), 0);
2555 assert_eq!(nodes[1].node.list_channels().len(), 0);
2557 // We test justice_tx build by A on B's revoked HTLC-Success tx
2558 // Create some new channels:
2559 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2561 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2565 // A pending HTLC which will be revoked:
2566 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2567 // Get the will-be-revoked local txn from B
2568 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2569 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2570 assert_eq!(revoked_local_txn[0].input.len(), 1);
2571 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2572 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2573 // Revoke the old state
2574 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2576 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2577 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2579 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2580 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2581 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2583 check_spends!(node_txn[0], revoked_local_txn[0]);
2584 node_txn.swap_remove(0);
2586 check_added_monitors!(nodes[0], 1);
2587 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2589 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2590 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2591 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2592 check_added_monitors!(nodes[1], 1);
2593 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2594 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2596 get_announce_close_broadcast_events(&nodes, 0, 1);
2597 assert_eq!(nodes[0].node.list_channels().len(), 0);
2598 assert_eq!(nodes[1].node.list_channels().len(), 0);
2602 fn revoked_output_claim() {
2603 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2604 // transaction is broadcast by its counterparty
2605 let chanmon_cfgs = create_chanmon_cfgs(2);
2606 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2607 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2608 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2609 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2610 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2611 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2612 assert_eq!(revoked_local_txn.len(), 1);
2613 // Only output is the full channel value back to nodes[0]:
2614 assert_eq!(revoked_local_txn[0].output.len(), 1);
2615 // Send a payment through, updating everyone's latest commitment txn
2616 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2618 // Inform nodes[1] that nodes[0] broadcast a stale tx
2619 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2620 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2621 check_added_monitors!(nodes[1], 1);
2622 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2623 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2625 check_spends!(node_txn[0], revoked_local_txn[0]);
2626 check_spends!(node_txn[1], chan_1.3);
2628 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2629 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2630 get_announce_close_broadcast_events(&nodes, 0, 1);
2631 check_added_monitors!(nodes[0], 1)
2635 fn claim_htlc_outputs_shared_tx() {
2636 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2637 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2638 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2641 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2643 // Create some new channel:
2644 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2646 // Rebalance the network to generate htlc in the two directions
2647 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2648 // 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
2649 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2650 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2652 // Get the will-be-revoked local txn from node[0]
2653 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2654 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2655 assert_eq!(revoked_local_txn[0].input.len(), 1);
2656 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2657 assert_eq!(revoked_local_txn[1].input.len(), 1);
2658 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2659 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2660 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2662 //Revoke the old state
2663 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2666 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2667 check_added_monitors!(nodes[0], 1);
2668 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2669 check_added_monitors!(nodes[1], 1);
2670 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, CHAN_CONFIRM_DEPTH + 1, false, Default::default());
2671 expect_payment_failed!(nodes[1], payment_hash_2, true);
2673 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2674 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2676 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2677 check_spends!(node_txn[0], revoked_local_txn[0]);
2679 let mut witness_lens = BTreeSet::new();
2680 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2681 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2682 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2683 assert_eq!(witness_lens.len(), 3);
2684 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2685 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2686 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2688 // Next nodes[1] broadcasts its current local tx state:
2689 assert_eq!(node_txn[1].input.len(), 1);
2690 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2692 assert_eq!(node_txn[2].input.len(), 1);
2693 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2694 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2695 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2696 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2697 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2699 get_announce_close_broadcast_events(&nodes, 0, 1);
2700 assert_eq!(nodes[0].node.list_channels().len(), 0);
2701 assert_eq!(nodes[1].node.list_channels().len(), 0);
2705 fn claim_htlc_outputs_single_tx() {
2706 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2707 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2708 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2711 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2713 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2715 // Rebalance the network to generate htlc in the two directions
2716 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2717 // 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
2718 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2719 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2720 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2722 // Get the will-be-revoked local txn from node[0]
2723 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2725 //Revoke the old state
2726 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2729 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2730 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2731 check_added_monitors!(nodes[0], 1);
2732 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2733 check_added_monitors!(nodes[1], 1);
2734 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2736 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2737 expect_payment_failed!(nodes[1], payment_hash_2, true);
2739 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2740 assert_eq!(node_txn.len(), 9);
2741 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2742 // ChannelManager: local commmitment + local HTLC-timeout (2)
2743 // 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)
2744 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2746 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2747 assert_eq!(node_txn[2].input.len(), 1);
2748 check_spends!(node_txn[2], chan_1.3);
2749 assert_eq!(node_txn[3].input.len(), 1);
2750 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2751 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2752 check_spends!(node_txn[3], node_txn[2]);
2754 // Justice transactions are indices 1-2-4
2755 assert_eq!(node_txn[0].input.len(), 1);
2756 assert_eq!(node_txn[1].input.len(), 1);
2757 assert_eq!(node_txn[4].input.len(), 1);
2759 check_spends!(node_txn[0], revoked_local_txn[0]);
2760 check_spends!(node_txn[1], revoked_local_txn[0]);
2761 check_spends!(node_txn[4], revoked_local_txn[0]);
2763 let mut witness_lens = BTreeSet::new();
2764 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2765 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2766 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2767 assert_eq!(witness_lens.len(), 3);
2768 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2769 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2770 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2772 get_announce_close_broadcast_events(&nodes, 0, 1);
2773 assert_eq!(nodes[0].node.list_channels().len(), 0);
2774 assert_eq!(nodes[1].node.list_channels().len(), 0);
2778 fn test_htlc_on_chain_success() {
2779 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2780 // the preimage backward accordingly. So here we test that ChannelManager is
2781 // broadcasting the right event to other nodes in payment path.
2782 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2783 // A --------------------> B ----------------------> C (preimage)
2784 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2785 // commitment transaction was broadcast.
2786 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2788 // B should be able to claim via preimage if A then broadcasts its local tx.
2789 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2790 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2791 // PaymentSent event).
2793 let chanmon_cfgs = create_chanmon_cfgs(3);
2794 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2795 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2796 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2798 // Create some initial channels
2799 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2800 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2802 // Rebalance the network a bit by relaying one payment through all the channels...
2803 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2804 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2806 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2807 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2808 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2810 // Broadcast legit commitment tx from C on B's chain
2811 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2812 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2813 assert_eq!(commitment_tx.len(), 1);
2814 check_spends!(commitment_tx[0], chan_2.3);
2815 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2816 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2817 check_added_monitors!(nodes[2], 2);
2818 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2819 assert!(updates.update_add_htlcs.is_empty());
2820 assert!(updates.update_fail_htlcs.is_empty());
2821 assert!(updates.update_fail_malformed_htlcs.is_empty());
2822 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2824 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2825 check_closed_broadcast!(nodes[2], false);
2826 check_added_monitors!(nodes[2], 1);
2827 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)
2828 assert_eq!(node_txn.len(), 5);
2829 assert_eq!(node_txn[0], node_txn[3]);
2830 assert_eq!(node_txn[1], node_txn[4]);
2831 assert_eq!(node_txn[2], commitment_tx[0]);
2832 check_spends!(node_txn[0], commitment_tx[0]);
2833 check_spends!(node_txn[1], commitment_tx[0]);
2834 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2835 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2836 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2837 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2838 assert_eq!(node_txn[0].lock_time, 0);
2839 assert_eq!(node_txn[1].lock_time, 0);
2841 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2842 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2844 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2845 assert_eq!(added_monitors.len(), 1);
2846 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2847 added_monitors.clear();
2849 let events = nodes[1].node.get_and_clear_pending_msg_events();
2851 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2852 assert_eq!(added_monitors.len(), 2);
2853 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2854 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2855 added_monitors.clear();
2857 assert_eq!(events.len(), 2);
2859 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2860 _ => panic!("Unexpected event"),
2863 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, .. } } => {
2864 assert!(update_add_htlcs.is_empty());
2865 assert!(update_fail_htlcs.is_empty());
2866 assert_eq!(update_fulfill_htlcs.len(), 1);
2867 assert!(update_fail_malformed_htlcs.is_empty());
2868 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2870 _ => panic!("Unexpected event"),
2872 macro_rules! check_tx_local_broadcast {
2873 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2874 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2875 assert_eq!(node_txn.len(), 5);
2876 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2877 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2878 check_spends!(node_txn[0], $commitment_tx);
2879 check_spends!(node_txn[1], $commitment_tx);
2880 assert_ne!(node_txn[0].lock_time, 0);
2881 assert_ne!(node_txn[1].lock_time, 0);
2883 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2886 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2889 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2890 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2891 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2893 check_spends!(node_txn[2], $chan_tx);
2894 check_spends!(node_txn[3], node_txn[2]);
2895 check_spends!(node_txn[4], node_txn[2]);
2896 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2897 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2898 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2899 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2900 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2901 assert_ne!(node_txn[3].lock_time, 0);
2902 assert_ne!(node_txn[4].lock_time, 0);
2906 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2907 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2908 // timeout-claim of the output that nodes[2] just claimed via success.
2909 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2911 // Broadcast legit commitment tx from A on B's chain
2912 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2913 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2914 check_spends!(commitment_tx[0], chan_1.3);
2915 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2916 check_closed_broadcast!(nodes[1], false);
2917 check_added_monitors!(nodes[1], 1);
2918 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2919 assert_eq!(node_txn.len(), 4);
2920 check_spends!(node_txn[0], commitment_tx[0]);
2921 assert_eq!(node_txn[0].input.len(), 2);
2922 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2923 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2924 assert_eq!(node_txn[0].lock_time, 0);
2925 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2926 check_spends!(node_txn[1], chan_1.3);
2927 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2928 check_spends!(node_txn[2], node_txn[1]);
2929 check_spends!(node_txn[3], node_txn[1]);
2930 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2931 // we already checked the same situation with A.
2933 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2934 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2935 check_closed_broadcast!(nodes[0], false);
2936 check_added_monitors!(nodes[0], 1);
2937 let events = nodes[0].node.get_and_clear_pending_events();
2938 assert_eq!(events.len(), 2);
2939 let mut first_claimed = false;
2940 for event in events {
2942 Event::PaymentSent { payment_preimage } => {
2943 if payment_preimage == our_payment_preimage {
2944 assert!(!first_claimed);
2945 first_claimed = true;
2947 assert_eq!(payment_preimage, our_payment_preimage_2);
2950 _ => panic!("Unexpected event"),
2953 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2957 fn test_htlc_on_chain_timeout() {
2958 // Test that in case of a unilateral close onchain, we detect the state of output and
2959 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2960 // broadcasting the right event to other nodes in payment path.
2961 // A ------------------> B ----------------------> C (timeout)
2962 // B's commitment tx C's commitment tx
2964 // B's HTLC timeout tx B's timeout tx
2966 let chanmon_cfgs = create_chanmon_cfgs(3);
2967 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2968 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2969 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2971 // Create some intial channels
2972 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2973 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2975 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2976 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2977 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2979 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2981 // Broadcast legit commitment tx from C on B's chain
2982 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2983 check_spends!(commitment_tx[0], chan_2.3);
2984 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2985 check_added_monitors!(nodes[2], 0);
2986 expect_pending_htlcs_forwardable!(nodes[2]);
2987 check_added_monitors!(nodes[2], 1);
2989 let events = nodes[2].node.get_and_clear_pending_msg_events();
2990 assert_eq!(events.len(), 1);
2992 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, .. } } => {
2993 assert!(update_add_htlcs.is_empty());
2994 assert!(!update_fail_htlcs.is_empty());
2995 assert!(update_fulfill_htlcs.is_empty());
2996 assert!(update_fail_malformed_htlcs.is_empty());
2997 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2999 _ => panic!("Unexpected event"),
3001 let last_block = nodes[2].best_block_info();
3002 mine_transaction(&nodes[2], &commitment_tx[0]);
3003 check_closed_broadcast!(nodes[2], false);
3004 check_added_monitors!(nodes[2], 1);
3005 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3006 assert_eq!(node_txn.len(), 1);
3007 check_spends!(node_txn[0], chan_2.3);
3008 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3010 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3011 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3012 connect_blocks(&nodes[1], 200 - last_block.1 - 1, last_block.1, false, Default::default());
3013 mine_transaction(&nodes[1], &commitment_tx[0]);
3016 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3017 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3018 assert_eq!(node_txn[0], node_txn[3]);
3019 assert_eq!(node_txn[1], node_txn[4]);
3021 check_spends!(node_txn[2], commitment_tx[0]);
3022 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3024 check_spends!(node_txn[0], chan_2.3);
3025 check_spends!(node_txn[1], node_txn[0]);
3026 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
3027 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3029 timeout_tx = node_txn[2].clone();
3033 mine_transaction(&nodes[1], &timeout_tx);
3034 check_added_monitors!(nodes[1], 1);
3035 check_closed_broadcast!(nodes[1], false);
3037 // B will rebroadcast a fee-bumped timeout transaction here.
3038 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3039 assert_eq!(node_txn.len(), 1);
3040 check_spends!(node_txn[0], commitment_tx[0]);
3043 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, false, Default::default());
3045 // B will rebroadcast its own holder commitment transaction here...just because
3046 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
3047 assert_eq!(node_txn.len(), 1);
3048 check_spends!(node_txn[0], chan_2.3);
3051 expect_pending_htlcs_forwardable!(nodes[1]);
3052 check_added_monitors!(nodes[1], 1);
3053 let events = nodes[1].node.get_and_clear_pending_msg_events();
3054 assert_eq!(events.len(), 1);
3056 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, .. } } => {
3057 assert!(update_add_htlcs.is_empty());
3058 assert!(!update_fail_htlcs.is_empty());
3059 assert!(update_fulfill_htlcs.is_empty());
3060 assert!(update_fail_malformed_htlcs.is_empty());
3061 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3063 _ => panic!("Unexpected event"),
3066 // Broadcast legit commitment tx from B on A's chain
3067 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3068 check_spends!(commitment_tx[0], chan_1.3);
3070 mine_transaction(&nodes[0], &commitment_tx[0]);
3072 check_closed_broadcast!(nodes[0], false);
3073 check_added_monitors!(nodes[0], 1);
3074 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3075 assert_eq!(node_txn.len(), 3);
3076 check_spends!(node_txn[0], commitment_tx[0]);
3077 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3078 check_spends!(node_txn[1], chan_1.3);
3079 check_spends!(node_txn[2], node_txn[1]);
3080 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3081 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3085 fn test_simple_commitment_revoked_fail_backward() {
3086 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3087 // and fail backward accordingly.
3089 let chanmon_cfgs = create_chanmon_cfgs(3);
3090 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3091 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3092 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3094 // Create some initial channels
3095 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3096 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3098 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3099 // Get the will-be-revoked local txn from nodes[2]
3100 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3101 // Revoke the old state
3102 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3104 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3106 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3107 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3108 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3109 check_added_monitors!(nodes[1], 1);
3110 check_closed_broadcast!(nodes[1], false);
3112 expect_pending_htlcs_forwardable!(nodes[1]);
3113 check_added_monitors!(nodes[1], 1);
3114 let events = nodes[1].node.get_and_clear_pending_msg_events();
3115 assert_eq!(events.len(), 1);
3117 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, .. } } => {
3118 assert!(update_add_htlcs.is_empty());
3119 assert_eq!(update_fail_htlcs.len(), 1);
3120 assert!(update_fulfill_htlcs.is_empty());
3121 assert!(update_fail_malformed_htlcs.is_empty());
3122 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3124 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3125 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3127 let events = nodes[0].node.get_and_clear_pending_msg_events();
3128 assert_eq!(events.len(), 1);
3130 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3131 _ => panic!("Unexpected event"),
3133 expect_payment_failed!(nodes[0], payment_hash, false);
3135 _ => panic!("Unexpected event"),
3139 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3140 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3141 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3142 // commitment transaction anymore.
3143 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3144 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3145 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3146 // technically disallowed and we should probably handle it reasonably.
3147 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3148 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3150 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3151 // commitment_signed (implying it will be in the latest remote commitment transaction).
3152 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3153 // and once they revoke the previous commitment transaction (allowing us to send a new
3154 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3155 let chanmon_cfgs = create_chanmon_cfgs(3);
3156 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3157 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3158 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3160 // Create some initial channels
3161 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3162 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3164 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3165 // Get the will-be-revoked local txn from nodes[2]
3166 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3167 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3168 // Revoke the old state
3169 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3171 let value = if use_dust {
3172 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3173 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3174 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3177 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3178 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3179 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3181 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3182 expect_pending_htlcs_forwardable!(nodes[2]);
3183 check_added_monitors!(nodes[2], 1);
3184 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3185 assert!(updates.update_add_htlcs.is_empty());
3186 assert!(updates.update_fulfill_htlcs.is_empty());
3187 assert!(updates.update_fail_malformed_htlcs.is_empty());
3188 assert_eq!(updates.update_fail_htlcs.len(), 1);
3189 assert!(updates.update_fee.is_none());
3190 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3191 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3192 // Drop the last RAA from 3 -> 2
3194 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3195 expect_pending_htlcs_forwardable!(nodes[2]);
3196 check_added_monitors!(nodes[2], 1);
3197 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3198 assert!(updates.update_add_htlcs.is_empty());
3199 assert!(updates.update_fulfill_htlcs.is_empty());
3200 assert!(updates.update_fail_malformed_htlcs.is_empty());
3201 assert_eq!(updates.update_fail_htlcs.len(), 1);
3202 assert!(updates.update_fee.is_none());
3203 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3204 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3205 check_added_monitors!(nodes[1], 1);
3206 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3207 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3208 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3209 check_added_monitors!(nodes[2], 1);
3211 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3212 expect_pending_htlcs_forwardable!(nodes[2]);
3213 check_added_monitors!(nodes[2], 1);
3214 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3215 assert!(updates.update_add_htlcs.is_empty());
3216 assert!(updates.update_fulfill_htlcs.is_empty());
3217 assert!(updates.update_fail_malformed_htlcs.is_empty());
3218 assert_eq!(updates.update_fail_htlcs.len(), 1);
3219 assert!(updates.update_fee.is_none());
3220 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3221 // At this point first_payment_hash has dropped out of the latest two commitment
3222 // transactions that nodes[1] is tracking...
3223 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3224 check_added_monitors!(nodes[1], 1);
3225 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3226 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3227 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3228 check_added_monitors!(nodes[2], 1);
3230 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3231 // on nodes[2]'s RAA.
3232 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3233 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3234 let logger = test_utils::TestLogger::new();
3235 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();
3236 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3237 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3238 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3239 check_added_monitors!(nodes[1], 0);
3242 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3243 // One monitor for the new revocation preimage, no second on as we won't generate a new
3244 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3245 check_added_monitors!(nodes[1], 1);
3246 let events = nodes[1].node.get_and_clear_pending_events();
3247 assert_eq!(events.len(), 1);
3249 Event::PendingHTLCsForwardable { .. } => { },
3250 _ => panic!("Unexpected event"),
3252 // Deliberately don't process the pending fail-back so they all fail back at once after
3253 // block connection just like the !deliver_bs_raa case
3256 let mut failed_htlcs = HashSet::new();
3257 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3259 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3260 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3261 check_added_monitors!(nodes[1], 1);
3262 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3264 let events = nodes[1].node.get_and_clear_pending_events();
3265 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3267 Event::PaymentFailed { ref payment_hash, .. } => {
3268 assert_eq!(*payment_hash, fourth_payment_hash);
3270 _ => panic!("Unexpected event"),
3272 if !deliver_bs_raa {
3274 Event::PendingHTLCsForwardable { .. } => { },
3275 _ => panic!("Unexpected event"),
3278 nodes[1].node.process_pending_htlc_forwards();
3279 check_added_monitors!(nodes[1], 1);
3281 let events = nodes[1].node.get_and_clear_pending_msg_events();
3282 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3283 match events[if deliver_bs_raa { 1 } else { 0 }] {
3284 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3285 _ => panic!("Unexpected event"),
3289 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3290 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3291 assert_eq!(update_add_htlcs.len(), 1);
3292 assert!(update_fulfill_htlcs.is_empty());
3293 assert!(update_fail_htlcs.is_empty());
3294 assert!(update_fail_malformed_htlcs.is_empty());
3296 _ => panic!("Unexpected event"),
3299 match events[if deliver_bs_raa { 2 } else { 1 }] {
3300 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3301 assert!(update_add_htlcs.is_empty());
3302 assert_eq!(update_fail_htlcs.len(), 3);
3303 assert!(update_fulfill_htlcs.is_empty());
3304 assert!(update_fail_malformed_htlcs.is_empty());
3305 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3307 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3308 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3309 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3311 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3313 let events = nodes[0].node.get_and_clear_pending_msg_events();
3314 // If we delivered B's RAA we got an unknown preimage error, not something
3315 // that we should update our routing table for.
3316 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3317 for event in events {
3319 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3320 _ => panic!("Unexpected event"),
3323 let events = nodes[0].node.get_and_clear_pending_events();
3324 assert_eq!(events.len(), 3);
3326 Event::PaymentFailed { ref payment_hash, .. } => {
3327 assert!(failed_htlcs.insert(payment_hash.0));
3329 _ => panic!("Unexpected event"),
3332 Event::PaymentFailed { ref payment_hash, .. } => {
3333 assert!(failed_htlcs.insert(payment_hash.0));
3335 _ => panic!("Unexpected event"),
3338 Event::PaymentFailed { ref payment_hash, .. } => {
3339 assert!(failed_htlcs.insert(payment_hash.0));
3341 _ => panic!("Unexpected event"),
3344 _ => panic!("Unexpected event"),
3347 assert!(failed_htlcs.contains(&first_payment_hash.0));
3348 assert!(failed_htlcs.contains(&second_payment_hash.0));
3349 assert!(failed_htlcs.contains(&third_payment_hash.0));
3353 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3354 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3355 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3356 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3357 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3361 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3362 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3363 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3364 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3365 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3369 fn fail_backward_pending_htlc_upon_channel_failure() {
3370 let chanmon_cfgs = create_chanmon_cfgs(2);
3371 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3372 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3373 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3374 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3375 let logger = test_utils::TestLogger::new();
3377 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3379 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3380 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3381 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3382 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3383 check_added_monitors!(nodes[0], 1);
3385 let payment_event = {
3386 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3387 assert_eq!(events.len(), 1);
3388 SendEvent::from_event(events.remove(0))
3390 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3391 assert_eq!(payment_event.msgs.len(), 1);
3394 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3395 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3397 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3398 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3399 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3400 check_added_monitors!(nodes[0], 0);
3402 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3405 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3407 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3409 let secp_ctx = Secp256k1::new();
3410 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3411 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3412 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3413 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3414 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3415 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3416 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3418 // Send a 0-msat update_add_htlc to fail the channel.
3419 let update_add_htlc = msgs::UpdateAddHTLC {
3425 onion_routing_packet,
3427 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3430 // Check that Alice fails backward the pending HTLC from the second payment.
3431 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3432 check_closed_broadcast!(nodes[0], true);
3433 check_added_monitors!(nodes[0], 1);
3437 fn test_htlc_ignore_latest_remote_commitment() {
3438 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3439 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3440 let chanmon_cfgs = create_chanmon_cfgs(2);
3441 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3442 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3443 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3444 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3446 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3447 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3448 check_closed_broadcast!(nodes[0], false);
3449 check_added_monitors!(nodes[0], 1);
3451 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3452 assert_eq!(node_txn.len(), 2);
3454 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3455 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3456 check_closed_broadcast!(nodes[1], false);
3457 check_added_monitors!(nodes[1], 1);
3459 // Duplicate the connect_block call since this may happen due to other listeners
3460 // registering new transactions
3461 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3465 fn test_force_close_fail_back() {
3466 // Check which HTLCs are failed-backwards on channel force-closure
3467 let chanmon_cfgs = create_chanmon_cfgs(3);
3468 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3469 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3470 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3471 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3472 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3473 let logger = test_utils::TestLogger::new();
3475 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3477 let mut payment_event = {
3478 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3479 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();
3480 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3481 check_added_monitors!(nodes[0], 1);
3483 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3484 assert_eq!(events.len(), 1);
3485 SendEvent::from_event(events.remove(0))
3488 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3489 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3491 expect_pending_htlcs_forwardable!(nodes[1]);
3493 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3494 assert_eq!(events_2.len(), 1);
3495 payment_event = SendEvent::from_event(events_2.remove(0));
3496 assert_eq!(payment_event.msgs.len(), 1);
3498 check_added_monitors!(nodes[1], 1);
3499 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3500 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3501 check_added_monitors!(nodes[2], 1);
3502 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3504 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3505 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3506 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3508 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3509 check_closed_broadcast!(nodes[2], false);
3510 check_added_monitors!(nodes[2], 1);
3512 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3513 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3514 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3515 // back to nodes[1] upon timeout otherwise.
3516 assert_eq!(node_txn.len(), 1);
3521 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3522 txdata: vec![tx.clone()],
3524 connect_block(&nodes[1], &block, 1);
3526 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3527 check_closed_broadcast!(nodes[1], false);
3528 check_added_monitors!(nodes[1], 1);
3530 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3532 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3533 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3534 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3536 connect_block(&nodes[2], &block, 1);
3537 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3538 assert_eq!(node_txn.len(), 1);
3539 assert_eq!(node_txn[0].input.len(), 1);
3540 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3541 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3542 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3544 check_spends!(node_txn[0], tx);
3548 fn test_simple_peer_disconnect() {
3549 // Test that we can reconnect when there are no lost messages
3550 let chanmon_cfgs = create_chanmon_cfgs(3);
3551 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3552 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3553 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3554 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3555 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3557 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3558 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3559 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3561 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3562 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3563 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3564 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3566 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3567 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3568 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3570 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3571 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3572 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3573 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3575 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3576 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3579 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3581 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3583 let events = nodes[0].node.get_and_clear_pending_events();
3584 assert_eq!(events.len(), 2);
3586 Event::PaymentSent { payment_preimage } => {
3587 assert_eq!(payment_preimage, payment_preimage_3);
3589 _ => panic!("Unexpected event"),
3592 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3593 assert_eq!(payment_hash, payment_hash_5);
3594 assert!(rejected_by_dest);
3596 _ => panic!("Unexpected event"),
3600 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3601 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3604 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3605 // Test that we can reconnect when in-flight HTLC updates get dropped
3606 let chanmon_cfgs = create_chanmon_cfgs(2);
3607 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3608 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3609 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3610 if messages_delivered == 0 {
3611 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3612 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3614 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3617 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3619 let logger = test_utils::TestLogger::new();
3620 let payment_event = {
3621 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3622 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3623 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3624 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3625 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3626 check_added_monitors!(nodes[0], 1);
3628 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3629 assert_eq!(events.len(), 1);
3630 SendEvent::from_event(events.remove(0))
3632 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3634 if messages_delivered < 2 {
3635 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3638 if messages_delivered >= 3 {
3639 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3640 check_added_monitors!(nodes[1], 1);
3641 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3643 if messages_delivered >= 4 {
3644 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3645 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3646 check_added_monitors!(nodes[0], 1);
3648 if messages_delivered >= 5 {
3649 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3650 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3651 // No commitment_signed so get_event_msg's assert(len == 1) passes
3652 check_added_monitors!(nodes[0], 1);
3654 if messages_delivered >= 6 {
3655 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3656 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3657 check_added_monitors!(nodes[1], 1);
3664 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3665 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3666 if messages_delivered < 3 {
3667 // Even if the funding_locked messages get exchanged, as long as nothing further was
3668 // received on either side, both sides will need to resend them.
3669 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3670 } else if messages_delivered == 3 {
3671 // nodes[0] still wants its RAA + commitment_signed
3672 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3673 } else if messages_delivered == 4 {
3674 // nodes[0] still wants its commitment_signed
3675 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3676 } else if messages_delivered == 5 {
3677 // nodes[1] still wants its final RAA
3678 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3679 } else if messages_delivered == 6 {
3680 // Everything was delivered...
3681 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3684 let events_1 = nodes[1].node.get_and_clear_pending_events();
3685 assert_eq!(events_1.len(), 1);
3687 Event::PendingHTLCsForwardable { .. } => { },
3688 _ => panic!("Unexpected event"),
3691 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3692 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3693 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695 nodes[1].node.process_pending_htlc_forwards();
3697 let events_2 = nodes[1].node.get_and_clear_pending_events();
3698 assert_eq!(events_2.len(), 1);
3700 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3701 assert_eq!(payment_hash_1, *payment_hash);
3702 assert_eq!(*payment_secret, None);
3703 assert_eq!(amt, 1000000);
3705 _ => panic!("Unexpected event"),
3708 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3709 check_added_monitors!(nodes[1], 1);
3711 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3712 assert_eq!(events_3.len(), 1);
3713 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3714 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3715 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3716 assert!(updates.update_add_htlcs.is_empty());
3717 assert!(updates.update_fail_htlcs.is_empty());
3718 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3719 assert!(updates.update_fail_malformed_htlcs.is_empty());
3720 assert!(updates.update_fee.is_none());
3721 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3723 _ => panic!("Unexpected event"),
3726 if messages_delivered >= 1 {
3727 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
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 if messages_delivered >= 2 {
3739 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3740 check_added_monitors!(nodes[0], 1);
3741 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3743 if messages_delivered >= 3 {
3744 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3745 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3746 check_added_monitors!(nodes[1], 1);
3748 if messages_delivered >= 4 {
3749 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3750 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3751 // No commitment_signed so get_event_msg's assert(len == 1) passes
3752 check_added_monitors!(nodes[1], 1);
3754 if messages_delivered >= 5 {
3755 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3756 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3757 check_added_monitors!(nodes[0], 1);
3764 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3765 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3766 if messages_delivered < 2 {
3767 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3768 //TODO: Deduplicate PaymentSent events, then enable this if:
3769 //if messages_delivered < 1 {
3770 let events_4 = nodes[0].node.get_and_clear_pending_events();
3771 assert_eq!(events_4.len(), 1);
3773 Event::PaymentSent { ref payment_preimage } => {
3774 assert_eq!(payment_preimage_1, *payment_preimage);
3776 _ => panic!("Unexpected event"),
3779 } else if messages_delivered == 2 {
3780 // nodes[0] still wants its RAA + commitment_signed
3781 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3782 } else if messages_delivered == 3 {
3783 // nodes[0] still wants its commitment_signed
3784 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3785 } else if messages_delivered == 4 {
3786 // nodes[1] still wants its final RAA
3787 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3788 } else if messages_delivered == 5 {
3789 // Everything was delivered...
3790 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3793 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3794 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3795 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3797 // Channel should still work fine...
3798 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3799 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3800 &nodes[1].node.get_our_node_id(), None, Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3801 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3802 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3803 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3807 fn test_drop_messages_peer_disconnect_a() {
3808 do_test_drop_messages_peer_disconnect(0);
3809 do_test_drop_messages_peer_disconnect(1);
3810 do_test_drop_messages_peer_disconnect(2);
3811 do_test_drop_messages_peer_disconnect(3);
3815 fn test_drop_messages_peer_disconnect_b() {
3816 do_test_drop_messages_peer_disconnect(4);
3817 do_test_drop_messages_peer_disconnect(5);
3818 do_test_drop_messages_peer_disconnect(6);
3822 fn test_funding_peer_disconnect() {
3823 // Test that we can lock in our funding tx while disconnected
3824 let chanmon_cfgs = create_chanmon_cfgs(2);
3825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3827 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3828 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3830 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3831 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3833 confirm_transaction(&nodes[0], &tx);
3834 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3835 assert_eq!(events_1.len(), 1);
3837 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3838 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3840 _ => panic!("Unexpected event"),
3843 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3845 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3846 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3848 confirm_transaction(&nodes[1], &tx);
3849 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3850 assert_eq!(events_2.len(), 2);
3851 let funding_locked = match events_2[0] {
3852 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3853 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3856 _ => panic!("Unexpected event"),
3858 let bs_announcement_sigs = match events_2[1] {
3859 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3860 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3863 _ => panic!("Unexpected event"),
3866 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3868 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3869 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3870 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3871 assert_eq!(events_3.len(), 2);
3872 let as_announcement_sigs = match events_3[0] {
3873 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3874 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3877 _ => panic!("Unexpected event"),
3879 let (as_announcement, as_update) = match events_3[1] {
3880 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3881 (msg.clone(), update_msg.clone())
3883 _ => panic!("Unexpected event"),
3886 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3887 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3888 assert_eq!(events_4.len(), 1);
3889 let (_, bs_update) = match events_4[0] {
3890 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3891 (msg.clone(), update_msg.clone())
3893 _ => panic!("Unexpected event"),
3896 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3897 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3898 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3900 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3901 let logger = test_utils::TestLogger::new();
3902 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();
3903 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3904 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3908 fn test_drop_messages_peer_disconnect_dual_htlc() {
3909 // Test that we can handle reconnecting when both sides of a channel have pending
3910 // commitment_updates when we disconnect.
3911 let chanmon_cfgs = create_chanmon_cfgs(2);
3912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3914 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3915 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3916 let logger = test_utils::TestLogger::new();
3918 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3920 // Now try to send a second payment which will fail to send
3921 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3922 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3923 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();
3924 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3925 check_added_monitors!(nodes[0], 1);
3927 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3928 assert_eq!(events_1.len(), 1);
3930 MessageSendEvent::UpdateHTLCs { .. } => {},
3931 _ => panic!("Unexpected event"),
3934 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3935 check_added_monitors!(nodes[1], 1);
3937 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3938 assert_eq!(events_2.len(), 1);
3940 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 } } => {
3941 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3942 assert!(update_add_htlcs.is_empty());
3943 assert_eq!(update_fulfill_htlcs.len(), 1);
3944 assert!(update_fail_htlcs.is_empty());
3945 assert!(update_fail_malformed_htlcs.is_empty());
3946 assert!(update_fee.is_none());
3948 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3949 let events_3 = nodes[0].node.get_and_clear_pending_events();
3950 assert_eq!(events_3.len(), 1);
3952 Event::PaymentSent { ref payment_preimage } => {
3953 assert_eq!(*payment_preimage, payment_preimage_1);
3955 _ => panic!("Unexpected event"),
3958 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3959 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3960 // No commitment_signed so get_event_msg's assert(len == 1) passes
3961 check_added_monitors!(nodes[0], 1);
3963 _ => panic!("Unexpected event"),
3966 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3967 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3969 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3970 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3971 assert_eq!(reestablish_1.len(), 1);
3972 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3973 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3974 assert_eq!(reestablish_2.len(), 1);
3976 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3977 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3978 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3979 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3981 assert!(as_resp.0.is_none());
3982 assert!(bs_resp.0.is_none());
3984 assert!(bs_resp.1.is_none());
3985 assert!(bs_resp.2.is_none());
3987 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3989 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3990 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3991 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3992 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3993 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3994 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3995 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3996 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3997 // No commitment_signed so get_event_msg's assert(len == 1) passes
3998 check_added_monitors!(nodes[1], 1);
4000 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4001 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4002 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4003 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4004 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4005 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4006 assert!(bs_second_commitment_signed.update_fee.is_none());
4007 check_added_monitors!(nodes[1], 1);
4009 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4010 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4011 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4012 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4013 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4014 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4015 assert!(as_commitment_signed.update_fee.is_none());
4016 check_added_monitors!(nodes[0], 1);
4018 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4019 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4020 // No commitment_signed so get_event_msg's assert(len == 1) passes
4021 check_added_monitors!(nodes[0], 1);
4023 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4024 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4025 // No commitment_signed so get_event_msg's assert(len == 1) passes
4026 check_added_monitors!(nodes[1], 1);
4028 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4029 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4030 check_added_monitors!(nodes[1], 1);
4032 expect_pending_htlcs_forwardable!(nodes[1]);
4034 let events_5 = nodes[1].node.get_and_clear_pending_events();
4035 assert_eq!(events_5.len(), 1);
4037 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4038 assert_eq!(payment_hash_2, *payment_hash);
4039 assert_eq!(*payment_secret, None);
4041 _ => panic!("Unexpected event"),
4044 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4045 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4046 check_added_monitors!(nodes[0], 1);
4048 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4051 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4052 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4053 // to avoid our counterparty failing the channel.
4054 let chanmon_cfgs = create_chanmon_cfgs(2);
4055 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4056 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4057 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4059 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4060 let logger = test_utils::TestLogger::new();
4062 let our_payment_hash = if send_partial_mpp {
4063 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4064 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();
4065 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4066 let payment_secret = PaymentSecret([0xdb; 32]);
4067 // Use the utility function send_payment_along_path to send the payment with MPP data which
4068 // indicates there are more HTLCs coming.
4069 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.
4070 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, cur_height).unwrap();
4071 check_added_monitors!(nodes[0], 1);
4072 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4073 assert_eq!(events.len(), 1);
4074 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4075 // hop should *not* yet generate any PaymentReceived event(s).
4076 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4079 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4082 let mut block = Block {
4083 header: BlockHeader { version: 0x20000000, prev_blockhash: nodes[0].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4086 connect_block(&nodes[0], &block, CHAN_CONFIRM_DEPTH + 1);
4087 connect_block(&nodes[1], &block, CHAN_CONFIRM_DEPTH + 1);
4088 for i in CHAN_CONFIRM_DEPTH + 2 ..TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4089 block.header.prev_blockhash = block.block_hash();
4090 connect_block(&nodes[0], &block, i);
4091 connect_block(&nodes[1], &block, i);
4094 expect_pending_htlcs_forwardable!(nodes[1]);
4096 check_added_monitors!(nodes[1], 1);
4097 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4098 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4099 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4100 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4101 assert!(htlc_timeout_updates.update_fee.is_none());
4103 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4104 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4105 // 100_000 msat as u64, followed by a height of TEST_FINAL_CLTV + 2 as u32
4106 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4107 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(TEST_FINAL_CLTV + 2));
4108 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4112 fn test_htlc_timeout() {
4113 do_test_htlc_timeout(true);
4114 do_test_htlc_timeout(false);
4117 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4118 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4119 let chanmon_cfgs = create_chanmon_cfgs(3);
4120 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4121 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4122 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4123 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4124 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4126 // Make sure all nodes are at the same starting height
4127 connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1, nodes[0].best_block_info().1, false, Default::default());
4128 connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1, nodes[1].best_block_info().1, false, Default::default());
4129 connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1, nodes[2].best_block_info().1, false, Default::default());
4131 let logger = test_utils::TestLogger::new();
4133 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4134 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4136 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4137 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();
4138 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4140 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4141 check_added_monitors!(nodes[1], 1);
4143 // Now attempt to route a second payment, which should be placed in the holding cell
4144 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4146 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4147 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4148 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4149 check_added_monitors!(nodes[0], 1);
4150 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4151 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4152 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4153 expect_pending_htlcs_forwardable!(nodes[1]);
4154 check_added_monitors!(nodes[1], 0);
4156 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4157 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();
4158 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4159 check_added_monitors!(nodes[1], 0);
4162 connect_blocks(&nodes[1], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, nodes[1].best_block_info().1, false, Default::default());
4163 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4164 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4165 connect_blocks(&nodes[1], 1, nodes[1].best_block_info().1, false, Default::default());
4168 expect_pending_htlcs_forwardable!(nodes[1]);
4169 check_added_monitors!(nodes[1], 1);
4170 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4171 assert_eq!(fail_commit.len(), 1);
4172 match fail_commit[0] {
4173 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4174 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4175 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4177 _ => unreachable!(),
4179 expect_payment_failed!(nodes[0], second_payment_hash, false);
4180 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4182 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4183 _ => panic!("Unexpected event"),
4186 panic!("Unexpected event");
4189 expect_payment_failed!(nodes[1], second_payment_hash, true);
4194 fn test_holding_cell_htlc_add_timeouts() {
4195 do_test_holding_cell_htlc_add_timeouts(false);
4196 do_test_holding_cell_htlc_add_timeouts(true);
4200 fn test_invalid_channel_announcement() {
4201 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4202 let secp_ctx = Secp256k1::new();
4203 let chanmon_cfgs = create_chanmon_cfgs(2);
4204 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4205 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4206 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4208 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4210 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4211 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4212 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4213 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4215 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 } );
4217 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4218 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4220 let as_network_key = nodes[0].node.get_our_node_id();
4221 let bs_network_key = nodes[1].node.get_our_node_id();
4223 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4225 let mut chan_announcement;
4227 macro_rules! dummy_unsigned_msg {
4229 msgs::UnsignedChannelAnnouncement {
4230 features: ChannelFeatures::known(),
4231 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4232 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4233 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4234 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4235 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4236 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4237 excess_data: Vec::new(),
4242 macro_rules! sign_msg {
4243 ($unsigned_msg: expr) => {
4244 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4245 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4246 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4247 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4248 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4249 chan_announcement = msgs::ChannelAnnouncement {
4250 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4251 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4252 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4253 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4254 contents: $unsigned_msg
4259 let unsigned_msg = dummy_unsigned_msg!();
4260 sign_msg!(unsigned_msg);
4261 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4262 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 } );
4264 // Configured with Network::Testnet
4265 let mut unsigned_msg = dummy_unsigned_msg!();
4266 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4267 sign_msg!(unsigned_msg);
4268 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4270 let mut unsigned_msg = dummy_unsigned_msg!();
4271 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4272 sign_msg!(unsigned_msg);
4273 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4277 fn test_no_txn_manager_serialize_deserialize() {
4278 let chanmon_cfgs = create_chanmon_cfgs(2);
4279 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4280 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4281 let logger: test_utils::TestLogger;
4282 let fee_estimator: test_utils::TestFeeEstimator;
4283 let persister: test_utils::TestPersister;
4284 let new_chain_monitor: test_utils::TestChainMonitor;
4285 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4286 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4288 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4290 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4292 let nodes_0_serialized = nodes[0].node.encode();
4293 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4294 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4296 logger = test_utils::TestLogger::new();
4297 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4298 persister = test_utils::TestPersister::new();
4299 let keys_manager = &chanmon_cfgs[0].keys_manager;
4300 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4301 nodes[0].chain_monitor = &new_chain_monitor;
4302 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4303 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4304 &mut chan_0_monitor_read, keys_manager).unwrap();
4305 assert!(chan_0_monitor_read.is_empty());
4307 let mut nodes_0_read = &nodes_0_serialized[..];
4308 let config = UserConfig::default();
4309 let (_, nodes_0_deserialized_tmp) = {
4310 let mut channel_monitors = HashMap::new();
4311 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4312 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4313 default_config: config,
4315 fee_estimator: &fee_estimator,
4316 chain_monitor: nodes[0].chain_monitor,
4317 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4322 nodes_0_deserialized = nodes_0_deserialized_tmp;
4323 assert!(nodes_0_read.is_empty());
4325 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4326 nodes[0].node = &nodes_0_deserialized;
4327 assert_eq!(nodes[0].node.list_channels().len(), 1);
4328 check_added_monitors!(nodes[0], 1);
4330 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4331 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4332 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4333 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4335 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4336 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4337 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4338 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4340 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4341 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4342 for node in nodes.iter() {
4343 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4344 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4345 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4348 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4352 fn test_manager_serialize_deserialize_events() {
4353 // This test makes sure the events field in ChannelManager survives de/serialization
4354 let chanmon_cfgs = create_chanmon_cfgs(2);
4355 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4356 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4357 let fee_estimator: test_utils::TestFeeEstimator;
4358 let persister: test_utils::TestPersister;
4359 let logger: test_utils::TestLogger;
4360 let new_chain_monitor: test_utils::TestChainMonitor;
4361 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4364 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4365 let channel_value = 100000;
4366 let push_msat = 10001;
4367 let a_flags = InitFeatures::known();
4368 let b_flags = InitFeatures::known();
4369 let node_a = nodes.remove(0);
4370 let node_b = nodes.remove(0);
4371 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4372 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()));
4373 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()));
4375 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4377 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4378 check_added_monitors!(node_a, 0);
4380 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()));
4382 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4383 assert_eq!(added_monitors.len(), 1);
4384 assert_eq!(added_monitors[0].0, funding_output);
4385 added_monitors.clear();
4388 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()));
4390 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4391 assert_eq!(added_monitors.len(), 1);
4392 assert_eq!(added_monitors[0].0, funding_output);
4393 added_monitors.clear();
4395 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4400 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4401 let nodes_0_serialized = nodes[0].node.encode();
4402 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4403 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4405 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4406 logger = test_utils::TestLogger::new();
4407 persister = test_utils::TestPersister::new();
4408 let keys_manager = &chanmon_cfgs[0].keys_manager;
4409 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4410 nodes[0].chain_monitor = &new_chain_monitor;
4411 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4412 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4413 &mut chan_0_monitor_read, keys_manager).unwrap();
4414 assert!(chan_0_monitor_read.is_empty());
4416 let mut nodes_0_read = &nodes_0_serialized[..];
4417 let config = UserConfig::default();
4418 let (_, nodes_0_deserialized_tmp) = {
4419 let mut channel_monitors = HashMap::new();
4420 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4421 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4422 default_config: config,
4424 fee_estimator: &fee_estimator,
4425 chain_monitor: nodes[0].chain_monitor,
4426 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4431 nodes_0_deserialized = nodes_0_deserialized_tmp;
4432 assert!(nodes_0_read.is_empty());
4434 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4436 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4437 nodes[0].node = &nodes_0_deserialized;
4439 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4440 let events_4 = nodes[0].node.get_and_clear_pending_events();
4441 assert_eq!(events_4.len(), 1);
4443 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4444 assert_eq!(user_channel_id, 42);
4445 assert_eq!(*funding_txo, funding_output);
4447 _ => panic!("Unexpected event"),
4450 // Make sure the channel is functioning as though the de/serialization never happened
4451 assert_eq!(nodes[0].node.list_channels().len(), 1);
4452 check_added_monitors!(nodes[0], 1);
4454 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4455 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4456 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4457 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4459 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4460 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4461 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4462 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4464 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4465 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4466 for node in nodes.iter() {
4467 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4468 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4469 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4472 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4476 fn test_simple_manager_serialize_deserialize() {
4477 let chanmon_cfgs = create_chanmon_cfgs(2);
4478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4480 let logger: test_utils::TestLogger;
4481 let fee_estimator: test_utils::TestFeeEstimator;
4482 let persister: test_utils::TestPersister;
4483 let new_chain_monitor: test_utils::TestChainMonitor;
4484 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4485 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4486 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4488 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4489 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4491 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4493 let nodes_0_serialized = nodes[0].node.encode();
4494 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4495 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4497 logger = test_utils::TestLogger::new();
4498 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4499 persister = test_utils::TestPersister::new();
4500 let keys_manager = &chanmon_cfgs[0].keys_manager;
4501 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4502 nodes[0].chain_monitor = &new_chain_monitor;
4503 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4504 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4505 &mut chan_0_monitor_read, keys_manager).unwrap();
4506 assert!(chan_0_monitor_read.is_empty());
4508 let mut nodes_0_read = &nodes_0_serialized[..];
4509 let (_, nodes_0_deserialized_tmp) = {
4510 let mut channel_monitors = HashMap::new();
4511 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4512 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4513 default_config: UserConfig::default(),
4515 fee_estimator: &fee_estimator,
4516 chain_monitor: nodes[0].chain_monitor,
4517 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4522 nodes_0_deserialized = nodes_0_deserialized_tmp;
4523 assert!(nodes_0_read.is_empty());
4525 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4526 nodes[0].node = &nodes_0_deserialized;
4527 check_added_monitors!(nodes[0], 1);
4529 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4531 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4532 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4536 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4537 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4538 let chanmon_cfgs = create_chanmon_cfgs(4);
4539 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4540 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4541 let logger: test_utils::TestLogger;
4542 let fee_estimator: test_utils::TestFeeEstimator;
4543 let persister: test_utils::TestPersister;
4544 let new_chain_monitor: test_utils::TestChainMonitor;
4545 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4546 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4547 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4548 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4549 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4551 let mut node_0_stale_monitors_serialized = Vec::new();
4552 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4553 let mut writer = test_utils::TestVecWriter(Vec::new());
4554 monitor.1.write(&mut writer).unwrap();
4555 node_0_stale_monitors_serialized.push(writer.0);
4558 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4560 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4561 let nodes_0_serialized = nodes[0].node.encode();
4563 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4564 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4565 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4566 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4568 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4570 let mut node_0_monitors_serialized = Vec::new();
4571 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4572 let mut writer = test_utils::TestVecWriter(Vec::new());
4573 monitor.1.write(&mut writer).unwrap();
4574 node_0_monitors_serialized.push(writer.0);
4577 logger = test_utils::TestLogger::new();
4578 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4579 persister = test_utils::TestPersister::new();
4580 let keys_manager = &chanmon_cfgs[0].keys_manager;
4581 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4582 nodes[0].chain_monitor = &new_chain_monitor;
4585 let mut node_0_stale_monitors = Vec::new();
4586 for serialized in node_0_stale_monitors_serialized.iter() {
4587 let mut read = &serialized[..];
4588 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4589 assert!(read.is_empty());
4590 node_0_stale_monitors.push(monitor);
4593 let mut node_0_monitors = Vec::new();
4594 for serialized in node_0_monitors_serialized.iter() {
4595 let mut read = &serialized[..];
4596 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4597 assert!(read.is_empty());
4598 node_0_monitors.push(monitor);
4601 let mut nodes_0_read = &nodes_0_serialized[..];
4602 if let Err(msgs::DecodeError::InvalidValue) =
4603 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4604 default_config: UserConfig::default(),
4606 fee_estimator: &fee_estimator,
4607 chain_monitor: nodes[0].chain_monitor,
4608 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4610 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4612 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4615 let mut nodes_0_read = &nodes_0_serialized[..];
4616 let (_, nodes_0_deserialized_tmp) =
4617 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4618 default_config: UserConfig::default(),
4620 fee_estimator: &fee_estimator,
4621 chain_monitor: nodes[0].chain_monitor,
4622 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4624 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4626 nodes_0_deserialized = nodes_0_deserialized_tmp;
4627 assert!(nodes_0_read.is_empty());
4629 { // Channel close should result in a commitment tx and an HTLC tx
4630 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4631 assert_eq!(txn.len(), 2);
4632 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4633 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4636 for monitor in node_0_monitors.drain(..) {
4637 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4638 check_added_monitors!(nodes[0], 1);
4640 nodes[0].node = &nodes_0_deserialized;
4642 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4643 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4644 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4645 //... and we can even still claim the payment!
4646 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4648 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4649 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4650 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4651 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4652 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4653 assert_eq!(msg_events.len(), 1);
4654 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4656 &ErrorAction::SendErrorMessage { ref msg } => {
4657 assert_eq!(msg.channel_id, channel_id);
4659 _ => panic!("Unexpected event!"),
4664 macro_rules! check_spendable_outputs {
4665 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4667 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4668 let mut txn = Vec::new();
4669 let mut all_outputs = Vec::new();
4670 let secp_ctx = Secp256k1::new();
4671 for event in events.drain(..) {
4673 Event::SpendableOutputs { mut outputs } => {
4674 for outp in outputs.drain(..) {
4675 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4676 all_outputs.push(outp);
4679 _ => panic!("Unexpected event"),
4682 if all_outputs.len() > 1 {
4683 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) {
4693 fn test_claim_sizeable_push_msat() {
4694 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4695 let chanmon_cfgs = create_chanmon_cfgs(2);
4696 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4697 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4698 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4700 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4701 nodes[1].node.force_close_channel(&chan.2).unwrap();
4702 check_closed_broadcast!(nodes[1], false);
4703 check_added_monitors!(nodes[1], 1);
4704 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4705 assert_eq!(node_txn.len(), 1);
4706 check_spends!(node_txn[0], chan.3);
4707 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
4709 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4710 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4711 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4713 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4714 assert_eq!(spend_txn.len(), 1);
4715 check_spends!(spend_txn[0], node_txn[0]);
4719 fn test_claim_on_remote_sizeable_push_msat() {
4720 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4721 // to_remote output is encumbered by a P2WPKH
4722 let chanmon_cfgs = create_chanmon_cfgs(2);
4723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4725 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4727 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4728 nodes[0].node.force_close_channel(&chan.2).unwrap();
4729 check_closed_broadcast!(nodes[0], false);
4730 check_added_monitors!(nodes[0], 1);
4732 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4733 assert_eq!(node_txn.len(), 1);
4734 check_spends!(node_txn[0], chan.3);
4735 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
4737 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4738 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4739 check_closed_broadcast!(nodes[1], false);
4740 check_added_monitors!(nodes[1], 1);
4741 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4743 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4744 assert_eq!(spend_txn.len(), 1);
4745 check_spends!(spend_txn[0], node_txn[0]);
4749 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4750 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4751 // to_remote output is encumbered by a P2WPKH
4753 let chanmon_cfgs = create_chanmon_cfgs(2);
4754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4756 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4758 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4759 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4760 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4761 assert_eq!(revoked_local_txn[0].input.len(), 1);
4762 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4764 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4765 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4766 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4767 check_closed_broadcast!(nodes[1], false);
4768 check_added_monitors!(nodes[1], 1);
4770 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4771 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4772 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4773 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4775 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4776 assert_eq!(spend_txn.len(), 3);
4777 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4778 check_spends!(spend_txn[1], node_txn[0]);
4779 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4783 fn test_static_spendable_outputs_preimage_tx() {
4784 let chanmon_cfgs = create_chanmon_cfgs(2);
4785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4789 // Create some initial channels
4790 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4792 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4794 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4795 assert_eq!(commitment_tx[0].input.len(), 1);
4796 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4798 // Settle A's commitment tx on B's chain
4799 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4800 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4801 check_added_monitors!(nodes[1], 1);
4802 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4803 check_added_monitors!(nodes[1], 1);
4804 let events = nodes[1].node.get_and_clear_pending_msg_events();
4806 MessageSendEvent::UpdateHTLCs { .. } => {},
4807 _ => panic!("Unexpected event"),
4810 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4811 _ => panic!("Unexepected event"),
4814 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4815 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4816 assert_eq!(node_txn.len(), 3);
4817 check_spends!(node_txn[0], commitment_tx[0]);
4818 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4819 check_spends!(node_txn[1], chan_1.3);
4820 check_spends!(node_txn[2], node_txn[1]);
4822 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4823 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4824 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4826 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4827 assert_eq!(spend_txn.len(), 1);
4828 check_spends!(spend_txn[0], node_txn[0]);
4832 fn test_static_spendable_outputs_timeout_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 // Rebalance the network a bit by relaying one payment through all the channels ...
4842 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4844 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4846 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4847 assert_eq!(commitment_tx[0].input.len(), 1);
4848 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4850 // Settle A's commitment tx on B' chain
4851 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4852 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4853 check_added_monitors!(nodes[1], 1);
4854 let events = nodes[1].node.get_and_clear_pending_msg_events();
4856 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4857 _ => panic!("Unexpected event"),
4860 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4861 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4862 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4863 check_spends!(node_txn[0], commitment_tx[0].clone());
4864 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4865 check_spends!(node_txn[1], chan_1.3.clone());
4866 check_spends!(node_txn[2], node_txn[1]);
4868 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4869 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4870 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4871 expect_payment_failed!(nodes[1], our_payment_hash, true);
4873 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4874 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4875 check_spends!(spend_txn[0], commitment_tx[0]);
4876 check_spends!(spend_txn[1], node_txn[0]);
4877 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4881 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4882 let chanmon_cfgs = create_chanmon_cfgs(2);
4883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4885 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4887 // Create some initial channels
4888 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4890 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4891 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4892 assert_eq!(revoked_local_txn[0].input.len(), 1);
4893 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4895 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4897 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4898 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4899 check_closed_broadcast!(nodes[1], false);
4900 check_added_monitors!(nodes[1], 1);
4902 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4903 assert_eq!(node_txn.len(), 2);
4904 assert_eq!(node_txn[0].input.len(), 2);
4905 check_spends!(node_txn[0], revoked_local_txn[0]);
4907 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4908 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4909 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4911 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4912 assert_eq!(spend_txn.len(), 1);
4913 check_spends!(spend_txn[0], node_txn[0]);
4917 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4918 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4919 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4924 // Create some initial channels
4925 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4927 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4928 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4929 assert_eq!(revoked_local_txn[0].input.len(), 1);
4930 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4932 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4934 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4935 // A will generate HTLC-Timeout from revoked commitment tx
4936 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4937 check_closed_broadcast!(nodes[0], false);
4938 check_added_monitors!(nodes[0], 1);
4940 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4941 assert_eq!(revoked_htlc_txn.len(), 2);
4942 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4943 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4944 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4945 check_spends!(revoked_htlc_txn[1], chan_1.3);
4947 // B will generate justice tx from A's revoked commitment/HTLC tx
4948 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4949 check_closed_broadcast!(nodes[1], false);
4950 check_added_monitors!(nodes[1], 1);
4952 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4953 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4954 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4955 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4956 // transactions next...
4957 assert_eq!(node_txn[0].input.len(), 3);
4958 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4960 assert_eq!(node_txn[1].input.len(), 2);
4961 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4962 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4963 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4965 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4966 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4969 assert_eq!(node_txn[2].input.len(), 1);
4970 check_spends!(node_txn[2], chan_1.3);
4972 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4973 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
4974 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4976 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4977 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4978 assert_eq!(spend_txn.len(), 1);
4979 assert_eq!(spend_txn[0].input.len(), 1);
4980 check_spends!(spend_txn[0], node_txn[1]);
4984 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4985 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4986 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4987 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4988 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4989 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4991 // Create some initial channels
4992 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4994 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4995 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4996 assert_eq!(revoked_local_txn[0].input.len(), 1);
4997 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4999 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5000 assert_eq!(revoked_local_txn[0].output.len(), 2);
5002 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5004 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5005 // B will generate HTLC-Success from revoked commitment tx
5006 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5007 check_closed_broadcast!(nodes[1], false);
5008 check_added_monitors!(nodes[1], 1);
5009 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5011 assert_eq!(revoked_htlc_txn.len(), 2);
5012 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5013 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5014 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5016 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5017 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5018 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5020 // A will generate justice tx from B's revoked commitment/HTLC tx
5021 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5022 check_closed_broadcast!(nodes[0], false);
5023 check_added_monitors!(nodes[0], 1);
5025 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5026 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5028 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5029 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5030 // transactions next...
5031 assert_eq!(node_txn[0].input.len(), 2);
5032 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5033 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5034 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5036 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5037 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5040 assert_eq!(node_txn[1].input.len(), 1);
5041 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5043 check_spends!(node_txn[2], chan_1.3);
5045 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5046 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5047 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5049 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5050 // didn't try to generate any new transactions.
5052 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5053 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5054 assert_eq!(spend_txn.len(), 3);
5055 assert_eq!(spend_txn[0].input.len(), 1);
5056 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5057 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5058 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5059 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5063 fn test_onchain_to_onchain_claim() {
5064 // Test that in case of channel closure, we detect the state of output and claim HTLC
5065 // on downstream peer's remote commitment tx.
5066 // First, have C claim an HTLC against its own latest commitment transaction.
5067 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5069 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5072 let chanmon_cfgs = create_chanmon_cfgs(3);
5073 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5074 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5075 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5077 // Create some initial channels
5078 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5079 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5081 // Rebalance the network a bit by relaying one payment through all the channels ...
5082 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5083 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5085 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5086 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5087 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5088 check_spends!(commitment_tx[0], chan_2.3);
5089 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5090 check_added_monitors!(nodes[2], 1);
5091 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5092 assert!(updates.update_add_htlcs.is_empty());
5093 assert!(updates.update_fail_htlcs.is_empty());
5094 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5095 assert!(updates.update_fail_malformed_htlcs.is_empty());
5097 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5098 check_closed_broadcast!(nodes[2], false);
5099 check_added_monitors!(nodes[2], 1);
5101 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5102 assert_eq!(c_txn.len(), 3);
5103 assert_eq!(c_txn[0], c_txn[2]);
5104 assert_eq!(commitment_tx[0], c_txn[1]);
5105 check_spends!(c_txn[1], chan_2.3);
5106 check_spends!(c_txn[2], c_txn[1]);
5107 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5108 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5109 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5110 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5112 // 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
5113 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5115 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5116 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5117 assert_eq!(b_txn.len(), 3);
5118 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5119 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5120 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5121 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5122 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5123 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5124 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5125 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5126 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5129 check_added_monitors!(nodes[1], 1);
5130 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5131 check_added_monitors!(nodes[1], 1);
5132 match msg_events[0] {
5133 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5134 _ => panic!("Unexpected event"),
5136 match msg_events[1] {
5137 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, .. } } => {
5138 assert!(update_add_htlcs.is_empty());
5139 assert!(update_fail_htlcs.is_empty());
5140 assert_eq!(update_fulfill_htlcs.len(), 1);
5141 assert!(update_fail_malformed_htlcs.is_empty());
5142 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5144 _ => panic!("Unexpected event"),
5146 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5147 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5148 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5149 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5150 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5151 assert_eq!(b_txn.len(), 3);
5152 check_spends!(b_txn[1], chan_1.3);
5153 check_spends!(b_txn[2], b_txn[1]);
5154 check_spends!(b_txn[0], commitment_tx[0]);
5155 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5156 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5157 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5159 check_closed_broadcast!(nodes[1], false);
5160 check_added_monitors!(nodes[1], 1);
5164 fn test_duplicate_payment_hash_one_failure_one_success() {
5165 // Topology : A --> B --> C
5166 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5167 let chanmon_cfgs = create_chanmon_cfgs(3);
5168 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5169 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5170 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5172 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5173 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5175 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5176 *nodes[0].network_payment_count.borrow_mut() -= 1;
5177 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5179 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5180 assert_eq!(commitment_txn[0].input.len(), 1);
5181 check_spends!(commitment_txn[0], chan_2.3);
5183 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5184 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5185 check_closed_broadcast!(nodes[1], false);
5186 check_added_monitors!(nodes[1], 1);
5188 let htlc_timeout_tx;
5189 { // Extract one of the two HTLC-Timeout transaction
5190 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5191 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5192 assert_eq!(node_txn.len(), 5);
5193 check_spends!(node_txn[0], commitment_txn[0]);
5194 assert_eq!(node_txn[0].input.len(), 1);
5195 check_spends!(node_txn[1], commitment_txn[0]);
5196 assert_eq!(node_txn[1].input.len(), 1);
5197 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5198 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5199 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5200 check_spends!(node_txn[2], chan_2.3);
5201 check_spends!(node_txn[3], node_txn[2]);
5202 check_spends!(node_txn[4], node_txn[2]);
5203 htlc_timeout_tx = node_txn[1].clone();
5206 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5207 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5208 check_added_monitors!(nodes[2], 3);
5209 let events = nodes[2].node.get_and_clear_pending_msg_events();
5211 MessageSendEvent::UpdateHTLCs { .. } => {},
5212 _ => panic!("Unexpected event"),
5215 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5216 _ => panic!("Unexepected event"),
5218 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5219 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)
5220 check_spends!(htlc_success_txn[2], chan_2.3);
5221 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5222 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5223 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5224 assert_eq!(htlc_success_txn[0].input.len(), 1);
5225 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5226 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5227 assert_eq!(htlc_success_txn[1].input.len(), 1);
5228 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5229 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5230 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5231 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5233 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5234 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5235 expect_pending_htlcs_forwardable!(nodes[1]);
5236 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5237 assert!(htlc_updates.update_add_htlcs.is_empty());
5238 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5239 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5240 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5241 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5242 check_added_monitors!(nodes[1], 1);
5244 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5245 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5247 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5248 let events = nodes[0].node.get_and_clear_pending_msg_events();
5249 assert_eq!(events.len(), 1);
5251 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5253 _ => { panic!("Unexpected event"); }
5256 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5258 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5259 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5260 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5261 assert!(updates.update_add_htlcs.is_empty());
5262 assert!(updates.update_fail_htlcs.is_empty());
5263 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5264 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5265 assert!(updates.update_fail_malformed_htlcs.is_empty());
5266 check_added_monitors!(nodes[1], 1);
5268 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5269 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5271 let events = nodes[0].node.get_and_clear_pending_events();
5273 Event::PaymentSent { ref payment_preimage } => {
5274 assert_eq!(*payment_preimage, our_payment_preimage);
5276 _ => panic!("Unexpected event"),
5281 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5282 let chanmon_cfgs = create_chanmon_cfgs(2);
5283 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5284 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5285 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5287 // Create some initial channels
5288 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5290 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5291 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5292 assert_eq!(local_txn.len(), 1);
5293 assert_eq!(local_txn[0].input.len(), 1);
5294 check_spends!(local_txn[0], chan_1.3);
5296 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5297 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5298 check_added_monitors!(nodes[1], 1);
5299 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5300 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5301 check_added_monitors!(nodes[1], 1);
5302 let events = nodes[1].node.get_and_clear_pending_msg_events();
5304 MessageSendEvent::UpdateHTLCs { .. } => {},
5305 _ => panic!("Unexpected event"),
5308 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5309 _ => panic!("Unexepected event"),
5312 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5313 assert_eq!(node_txn.len(), 3);
5314 assert_eq!(node_txn[0], node_txn[2]);
5315 assert_eq!(node_txn[1], local_txn[0]);
5316 assert_eq!(node_txn[0].input.len(), 1);
5317 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5318 check_spends!(node_txn[0], local_txn[0]);
5319 vec![node_txn[0].clone()]
5322 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5323 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5324 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5326 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5327 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5328 assert_eq!(spend_txn.len(), 1);
5329 check_spends!(spend_txn[0], node_txn[0]);
5332 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5333 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5334 // unrevoked commitment transaction.
5335 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5336 // a remote RAA before they could be failed backwards (and combinations thereof).
5337 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5338 // use the same payment hashes.
5339 // Thus, we use a six-node network:
5344 // And test where C fails back to A/B when D announces its latest commitment transaction
5345 let chanmon_cfgs = create_chanmon_cfgs(6);
5346 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5347 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5348 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5349 let logger = test_utils::TestLogger::new();
5351 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5352 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5353 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5354 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5355 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5357 // Rebalance and check output sanity...
5358 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5359 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5360 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5362 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5364 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
5366 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
5367 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5368 let our_node_id = &nodes[1].node.get_our_node_id();
5369 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5371 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
5373 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
5375 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5377 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5378 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();
5380 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5382 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5385 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5387 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();
5388 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
5391 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
5393 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();
5394 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5396 // Double-check that six of the new HTLC were added
5397 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5398 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5399 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5400 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5402 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5403 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5404 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5405 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5406 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5407 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5408 check_added_monitors!(nodes[4], 0);
5409 expect_pending_htlcs_forwardable!(nodes[4]);
5410 check_added_monitors!(nodes[4], 1);
5412 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5413 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5414 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5415 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5416 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5417 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5419 // Fail 3rd below-dust and 7th above-dust HTLCs
5420 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5421 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5422 check_added_monitors!(nodes[5], 0);
5423 expect_pending_htlcs_forwardable!(nodes[5]);
5424 check_added_monitors!(nodes[5], 1);
5426 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5427 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5428 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5429 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5431 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5433 expect_pending_htlcs_forwardable!(nodes[3]);
5434 check_added_monitors!(nodes[3], 1);
5435 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5436 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5437 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5438 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5439 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5440 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5441 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5442 if deliver_last_raa {
5443 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5445 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5448 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5449 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5450 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5451 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5453 // We now broadcast the latest commitment transaction, which *should* result in failures for
5454 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5455 // the non-broadcast above-dust HTLCs.
5457 // Alternatively, we may broadcast the previous commitment transaction, which should only
5458 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5459 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5461 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5462 if announce_latest {
5463 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5465 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5467 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5468 check_closed_broadcast!(nodes[2], false);
5469 expect_pending_htlcs_forwardable!(nodes[2]);
5470 check_added_monitors!(nodes[2], 3);
5472 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5473 assert_eq!(cs_msgs.len(), 2);
5474 let mut a_done = false;
5475 for msg in cs_msgs {
5477 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5478 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5479 // should be failed-backwards here.
5480 let target = if *node_id == nodes[0].node.get_our_node_id() {
5481 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5482 for htlc in &updates.update_fail_htlcs {
5483 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 });
5485 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5490 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5491 for htlc in &updates.update_fail_htlcs {
5492 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5494 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5495 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5498 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5499 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5500 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5501 if announce_latest {
5502 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5503 if *node_id == nodes[0].node.get_our_node_id() {
5504 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5507 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5509 _ => panic!("Unexpected event"),
5513 let as_events = nodes[0].node.get_and_clear_pending_events();
5514 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5515 let mut as_failds = HashSet::new();
5516 for event in as_events.iter() {
5517 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5518 assert!(as_failds.insert(*payment_hash));
5519 if *payment_hash != payment_hash_2 {
5520 assert_eq!(*rejected_by_dest, deliver_last_raa);
5522 assert!(!rejected_by_dest);
5524 } else { panic!("Unexpected event"); }
5526 assert!(as_failds.contains(&payment_hash_1));
5527 assert!(as_failds.contains(&payment_hash_2));
5528 if announce_latest {
5529 assert!(as_failds.contains(&payment_hash_3));
5530 assert!(as_failds.contains(&payment_hash_5));
5532 assert!(as_failds.contains(&payment_hash_6));
5534 let bs_events = nodes[1].node.get_and_clear_pending_events();
5535 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5536 let mut bs_failds = HashSet::new();
5537 for event in bs_events.iter() {
5538 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5539 assert!(bs_failds.insert(*payment_hash));
5540 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5541 assert_eq!(*rejected_by_dest, deliver_last_raa);
5543 assert!(!rejected_by_dest);
5545 } else { panic!("Unexpected event"); }
5547 assert!(bs_failds.contains(&payment_hash_1));
5548 assert!(bs_failds.contains(&payment_hash_2));
5549 if announce_latest {
5550 assert!(bs_failds.contains(&payment_hash_4));
5552 assert!(bs_failds.contains(&payment_hash_5));
5554 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5555 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5556 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5557 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5558 // PaymentFailureNetworkUpdates.
5559 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5560 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5561 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5562 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5563 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5565 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5566 _ => panic!("Unexpected event"),
5572 fn test_fail_backwards_latest_remote_announce_a() {
5573 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5577 fn test_fail_backwards_latest_remote_announce_b() {
5578 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5582 fn test_fail_backwards_previous_remote_announce() {
5583 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5584 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5585 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5589 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5590 let chanmon_cfgs = create_chanmon_cfgs(2);
5591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5593 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5595 // Create some initial channels
5596 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5598 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5599 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5600 assert_eq!(local_txn[0].input.len(), 1);
5601 check_spends!(local_txn[0], chan_1.3);
5603 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5604 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5605 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5606 check_closed_broadcast!(nodes[0], false);
5607 check_added_monitors!(nodes[0], 1);
5609 let htlc_timeout = {
5610 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5611 assert_eq!(node_txn[0].input.len(), 1);
5612 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5613 check_spends!(node_txn[0], local_txn[0]);
5617 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5618 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5619 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5620 expect_payment_failed!(nodes[0], our_payment_hash, true);
5622 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5623 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5624 assert_eq!(spend_txn.len(), 3);
5625 check_spends!(spend_txn[0], local_txn[0]);
5626 check_spends!(spend_txn[1], htlc_timeout);
5627 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5631 fn test_key_derivation_params() {
5632 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5633 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5634 // let us re-derive the channel key set to then derive a delayed_payment_key.
5636 let chanmon_cfgs = create_chanmon_cfgs(3);
5638 // We manually create the node configuration to backup the seed.
5639 let seed = [42; 32];
5640 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5641 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);
5642 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 };
5643 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5644 node_cfgs.remove(0);
5645 node_cfgs.insert(0, node);
5647 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5648 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5650 // Create some initial channels
5651 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5653 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5654 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5655 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5657 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5658 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5659 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5660 assert_eq!(local_txn_1[0].input.len(), 1);
5661 check_spends!(local_txn_1[0], chan_1.3);
5663 // We check funding pubkey are unique
5664 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]));
5665 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]));
5666 if from_0_funding_key_0 == from_1_funding_key_0
5667 || from_0_funding_key_0 == from_1_funding_key_1
5668 || from_0_funding_key_1 == from_1_funding_key_0
5669 || from_0_funding_key_1 == from_1_funding_key_1 {
5670 panic!("Funding pubkeys aren't unique");
5673 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5674 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5675 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5676 check_closed_broadcast!(nodes[0], false);
5677 check_added_monitors!(nodes[0], 1);
5679 let htlc_timeout = {
5680 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5681 assert_eq!(node_txn[0].input.len(), 1);
5682 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5683 check_spends!(node_txn[0], local_txn_1[0]);
5687 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5688 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5689 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5690 expect_payment_failed!(nodes[0], our_payment_hash, true);
5692 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5693 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5694 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5695 assert_eq!(spend_txn.len(), 3);
5696 check_spends!(spend_txn[0], local_txn_1[0]);
5697 check_spends!(spend_txn[1], htlc_timeout);
5698 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5702 fn test_static_output_closing_tx() {
5703 let chanmon_cfgs = create_chanmon_cfgs(2);
5704 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5705 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5706 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5708 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5710 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5711 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5713 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5714 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5715 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5717 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5718 assert_eq!(spend_txn.len(), 1);
5719 check_spends!(spend_txn[0], closing_tx);
5721 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5722 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5724 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5725 assert_eq!(spend_txn.len(), 1);
5726 check_spends!(spend_txn[0], closing_tx);
5729 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5730 let chanmon_cfgs = create_chanmon_cfgs(2);
5731 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5732 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5733 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5734 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5736 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5738 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5739 // present in B's local commitment transaction, but none of A's commitment transactions.
5740 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5741 check_added_monitors!(nodes[1], 1);
5743 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5744 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5745 let events = nodes[0].node.get_and_clear_pending_events();
5746 assert_eq!(events.len(), 1);
5748 Event::PaymentSent { payment_preimage } => {
5749 assert_eq!(payment_preimage, our_payment_preimage);
5751 _ => panic!("Unexpected event"),
5754 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5755 check_added_monitors!(nodes[0], 1);
5756 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5757 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5758 check_added_monitors!(nodes[1], 1);
5760 let starting_block = nodes[1].best_block_info();
5761 let mut block = Block {
5762 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5765 for i in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5766 connect_block(&nodes[1], &block, i);
5767 block.header.prev_blockhash = block.block_hash();
5769 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5770 check_closed_broadcast!(nodes[1], false);
5771 check_added_monitors!(nodes[1], 1);
5774 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5775 let chanmon_cfgs = create_chanmon_cfgs(2);
5776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5778 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5779 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5780 let logger = test_utils::TestLogger::new();
5782 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5783 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5784 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();
5785 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5786 check_added_monitors!(nodes[0], 1);
5788 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5790 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5791 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5792 // to "time out" the HTLC.
5794 let starting_block = nodes[1].best_block_info();
5795 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5797 for i in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5798 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5799 header.prev_blockhash = header.block_hash();
5801 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5802 check_closed_broadcast!(nodes[0], false);
5803 check_added_monitors!(nodes[0], 1);
5806 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5807 let chanmon_cfgs = create_chanmon_cfgs(3);
5808 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5809 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5810 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5811 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5813 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5814 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5815 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5816 // actually revoked.
5817 let htlc_value = if use_dust { 50000 } else { 3000000 };
5818 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5819 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5820 expect_pending_htlcs_forwardable!(nodes[1]);
5821 check_added_monitors!(nodes[1], 1);
5823 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5824 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5825 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5826 check_added_monitors!(nodes[0], 1);
5827 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5828 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5829 check_added_monitors!(nodes[1], 1);
5830 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5831 check_added_monitors!(nodes[1], 1);
5832 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5834 if check_revoke_no_close {
5835 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5836 check_added_monitors!(nodes[0], 1);
5839 let starting_block = nodes[1].best_block_info();
5840 let mut block = Block {
5841 header: BlockHeader { version: 0x20000000, prev_blockhash: starting_block.0, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5844 for i in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5845 connect_block(&nodes[0], &block, i);
5846 block.header.prev_blockhash = block.block_hash();
5848 if !check_revoke_no_close {
5849 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5850 check_closed_broadcast!(nodes[0], false);
5851 check_added_monitors!(nodes[0], 1);
5853 expect_payment_failed!(nodes[0], our_payment_hash, true);
5857 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5858 // There are only a few cases to test here:
5859 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5860 // broadcastable commitment transactions result in channel closure,
5861 // * its included in an unrevoked-but-previous remote commitment transaction,
5862 // * its included in the latest remote or local commitment transactions.
5863 // We test each of the three possible commitment transactions individually and use both dust and
5865 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5866 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5867 // tested for at least one of the cases in other tests.
5869 fn htlc_claim_single_commitment_only_a() {
5870 do_htlc_claim_local_commitment_only(true);
5871 do_htlc_claim_local_commitment_only(false);
5873 do_htlc_claim_current_remote_commitment_only(true);
5874 do_htlc_claim_current_remote_commitment_only(false);
5878 fn htlc_claim_single_commitment_only_b() {
5879 do_htlc_claim_previous_remote_commitment_only(true, false);
5880 do_htlc_claim_previous_remote_commitment_only(false, false);
5881 do_htlc_claim_previous_remote_commitment_only(true, true);
5882 do_htlc_claim_previous_remote_commitment_only(false, true);
5887 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5888 let chanmon_cfgs = create_chanmon_cfgs(2);
5889 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5890 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5891 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5892 //Force duplicate channel ids
5893 for node in nodes.iter() {
5894 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5897 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5898 let channel_value_satoshis=10000;
5899 let push_msat=10001;
5900 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5901 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5902 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5904 //Create a second channel with a channel_id collision
5905 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5909 fn bolt2_open_channel_sending_node_checks_part2() {
5910 let chanmon_cfgs = create_chanmon_cfgs(2);
5911 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5912 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5913 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5915 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5916 let channel_value_satoshis=2^24;
5917 let push_msat=10001;
5918 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5920 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5921 let channel_value_satoshis=10000;
5922 // Test when push_msat is equal to 1000 * funding_satoshis.
5923 let push_msat=1000*channel_value_satoshis+1;
5924 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5926 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5927 let channel_value_satoshis=10000;
5928 let push_msat=10001;
5929 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
5930 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5931 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5933 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5934 // 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
5935 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5937 // 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.
5938 assert!(BREAKDOWN_TIMEOUT>0);
5939 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5941 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5942 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5943 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5945 // 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.
5946 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5947 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5948 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5949 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5950 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5953 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5954 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5955 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5956 // is no longer affordable once it's freed.
5958 fn test_fail_holding_cell_htlc_upon_free() {
5959 let chanmon_cfgs = create_chanmon_cfgs(2);
5960 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5961 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5962 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5963 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5964 let logger = test_utils::TestLogger::new();
5966 // First nodes[0] generates an update_fee, setting the channel's
5967 // pending_update_fee.
5968 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5969 check_added_monitors!(nodes[0], 1);
5971 let events = nodes[0].node.get_and_clear_pending_msg_events();
5972 assert_eq!(events.len(), 1);
5973 let (update_msg, commitment_signed) = match events[0] {
5974 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5975 (update_fee.as_ref(), commitment_signed)
5977 _ => panic!("Unexpected event"),
5980 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5982 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5983 let channel_reserve = chan_stat.channel_reserve_msat;
5984 let feerate = get_feerate!(nodes[0], chan.2);
5986 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5987 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5988 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
5989 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5990 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();
5992 // Send a payment which passes reserve checks but gets stuck in the holding cell.
5993 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5994 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
5995 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5997 // Flush the pending fee update.
5998 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5999 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6000 check_added_monitors!(nodes[1], 1);
6001 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6002 check_added_monitors!(nodes[0], 1);
6004 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6005 // HTLC, but now that the fee has been raised the payment will now fail, causing
6006 // us to surface its failure to the user.
6007 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6008 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6009 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6010 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);
6011 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6013 // Check that the payment failed to be sent out.
6014 let events = nodes[0].node.get_and_clear_pending_events();
6015 assert_eq!(events.len(), 1);
6017 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6018 assert_eq!(our_payment_hash.clone(), *payment_hash);
6019 assert_eq!(*rejected_by_dest, false);
6020 assert_eq!(*error_code, None);
6021 assert_eq!(*error_data, None);
6023 _ => panic!("Unexpected event"),
6027 // Test that if multiple HTLCs are released from the holding cell and one is
6028 // valid but the other is no longer valid upon release, the valid HTLC can be
6029 // successfully completed while the other one fails as expected.
6031 fn test_free_and_fail_holding_cell_htlcs() {
6032 let chanmon_cfgs = create_chanmon_cfgs(2);
6033 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6034 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6035 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6036 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6037 let logger = test_utils::TestLogger::new();
6039 // First nodes[0] generates an update_fee, setting the channel's
6040 // pending_update_fee.
6041 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6042 check_added_monitors!(nodes[0], 1);
6044 let events = nodes[0].node.get_and_clear_pending_msg_events();
6045 assert_eq!(events.len(), 1);
6046 let (update_msg, commitment_signed) = match events[0] {
6047 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6048 (update_fee.as_ref(), commitment_signed)
6050 _ => panic!("Unexpected event"),
6053 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6055 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6056 let channel_reserve = chan_stat.channel_reserve_msat;
6057 let feerate = get_feerate!(nodes[0], chan.2);
6059 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6060 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6062 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6063 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6064 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6065 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();
6066 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();
6068 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6069 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6070 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6071 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6072 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6073 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6074 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6076 // Flush the pending fee update.
6077 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6078 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6079 check_added_monitors!(nodes[1], 1);
6080 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6081 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6082 check_added_monitors!(nodes[0], 2);
6084 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6085 // but now that the fee has been raised the second payment will now fail, causing us
6086 // to surface its failure to the user. The first payment should succeed.
6087 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6088 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6089 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6090 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);
6091 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6093 // Check that the second payment failed to be sent out.
6094 let events = nodes[0].node.get_and_clear_pending_events();
6095 assert_eq!(events.len(), 1);
6097 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6098 assert_eq!(payment_hash_2.clone(), *payment_hash);
6099 assert_eq!(*rejected_by_dest, false);
6100 assert_eq!(*error_code, None);
6101 assert_eq!(*error_data, None);
6103 _ => panic!("Unexpected event"),
6106 // Complete the first payment and the RAA from the fee update.
6107 let (payment_event, send_raa_event) = {
6108 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6109 assert_eq!(msgs.len(), 2);
6110 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6112 let raa = match send_raa_event {
6113 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6114 _ => panic!("Unexpected event"),
6116 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6117 check_added_monitors!(nodes[1], 1);
6118 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6119 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6120 let events = nodes[1].node.get_and_clear_pending_events();
6121 assert_eq!(events.len(), 1);
6123 Event::PendingHTLCsForwardable { .. } => {},
6124 _ => panic!("Unexpected event"),
6126 nodes[1].node.process_pending_htlc_forwards();
6127 let events = nodes[1].node.get_and_clear_pending_events();
6128 assert_eq!(events.len(), 1);
6130 Event::PaymentReceived { .. } => {},
6131 _ => panic!("Unexpected event"),
6133 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6134 check_added_monitors!(nodes[1], 1);
6135 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6136 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6137 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6138 let events = nodes[0].node.get_and_clear_pending_events();
6139 assert_eq!(events.len(), 1);
6141 Event::PaymentSent { ref payment_preimage } => {
6142 assert_eq!(*payment_preimage, payment_preimage_1);
6144 _ => panic!("Unexpected event"),
6148 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6149 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6150 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6153 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6154 let chanmon_cfgs = create_chanmon_cfgs(3);
6155 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6156 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6157 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6158 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6159 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6160 let logger = test_utils::TestLogger::new();
6162 // First nodes[1] generates an update_fee, setting the channel's
6163 // pending_update_fee.
6164 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6165 check_added_monitors!(nodes[1], 1);
6167 let events = nodes[1].node.get_and_clear_pending_msg_events();
6168 assert_eq!(events.len(), 1);
6169 let (update_msg, commitment_signed) = match events[0] {
6170 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6171 (update_fee.as_ref(), commitment_signed)
6173 _ => panic!("Unexpected event"),
6176 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6178 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6179 let channel_reserve = chan_stat.channel_reserve_msat;
6180 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6182 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6184 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6185 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6186 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6187 let payment_event = {
6188 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6189 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();
6190 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6191 check_added_monitors!(nodes[0], 1);
6193 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6194 assert_eq!(events.len(), 1);
6196 SendEvent::from_event(events.remove(0))
6198 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6199 check_added_monitors!(nodes[1], 0);
6200 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6201 expect_pending_htlcs_forwardable!(nodes[1]);
6203 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6204 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6206 // Flush the pending fee update.
6207 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6208 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6209 check_added_monitors!(nodes[2], 1);
6210 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6211 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6212 check_added_monitors!(nodes[1], 2);
6214 // A final RAA message is generated to finalize the fee update.
6215 let events = nodes[1].node.get_and_clear_pending_msg_events();
6216 assert_eq!(events.len(), 1);
6218 let raa_msg = match &events[0] {
6219 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6222 _ => panic!("Unexpected event"),
6225 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6226 check_added_monitors!(nodes[2], 1);
6227 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6229 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6230 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6231 assert_eq!(process_htlc_forwards_event.len(), 1);
6232 match &process_htlc_forwards_event[0] {
6233 &Event::PendingHTLCsForwardable { .. } => {},
6234 _ => panic!("Unexpected event"),
6237 // In response, we call ChannelManager's process_pending_htlc_forwards
6238 nodes[1].node.process_pending_htlc_forwards();
6239 check_added_monitors!(nodes[1], 1);
6241 // This causes the HTLC to be failed backwards.
6242 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6243 assert_eq!(fail_event.len(), 1);
6244 let (fail_msg, commitment_signed) = match &fail_event[0] {
6245 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6246 assert_eq!(updates.update_add_htlcs.len(), 0);
6247 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6248 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6249 assert_eq!(updates.update_fail_htlcs.len(), 1);
6250 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6252 _ => panic!("Unexpected event"),
6255 // Pass the failure messages back to nodes[0].
6256 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6257 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6259 // Complete the HTLC failure+removal process.
6260 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6261 check_added_monitors!(nodes[0], 1);
6262 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6263 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6264 check_added_monitors!(nodes[1], 2);
6265 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6266 assert_eq!(final_raa_event.len(), 1);
6267 let raa = match &final_raa_event[0] {
6268 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6269 _ => panic!("Unexpected event"),
6271 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6272 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6273 assert_eq!(fail_msg_event.len(), 1);
6274 match &fail_msg_event[0] {
6275 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6276 _ => panic!("Unexpected event"),
6278 let failure_event = nodes[0].node.get_and_clear_pending_events();
6279 assert_eq!(failure_event.len(), 1);
6280 match &failure_event[0] {
6281 &Event::PaymentFailed { rejected_by_dest, .. } => {
6282 assert!(!rejected_by_dest);
6284 _ => panic!("Unexpected event"),
6286 check_added_monitors!(nodes[0], 1);
6289 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6290 // 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.
6291 //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.
6294 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6295 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6296 let chanmon_cfgs = create_chanmon_cfgs(2);
6297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6299 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6300 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6302 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6303 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6304 let logger = test_utils::TestLogger::new();
6305 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();
6306 route.paths[0][0].fee_msat = 100;
6308 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6309 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6310 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6311 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6315 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6316 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6317 let chanmon_cfgs = create_chanmon_cfgs(2);
6318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6320 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6321 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6322 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6324 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6325 let logger = test_utils::TestLogger::new();
6326 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();
6327 route.paths[0][0].fee_msat = 0;
6328 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6329 assert_eq!(err, "Cannot send 0-msat HTLC"));
6331 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6332 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6336 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6337 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6338 let chanmon_cfgs = create_chanmon_cfgs(2);
6339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6342 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6344 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6345 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6346 let logger = test_utils::TestLogger::new();
6347 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();
6348 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6349 check_added_monitors!(nodes[0], 1);
6350 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6351 updates.update_add_htlcs[0].amount_msat = 0;
6353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6354 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6355 check_closed_broadcast!(nodes[1], true).unwrap();
6356 check_added_monitors!(nodes[1], 1);
6360 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6361 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6362 //It is enforced when constructing a route.
6363 let chanmon_cfgs = create_chanmon_cfgs(2);
6364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6368 let logger = test_utils::TestLogger::new();
6370 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6372 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6373 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();
6374 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6375 assert_eq!(err, &"Channel CLTV overflowed?"));
6379 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6380 //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.
6381 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6382 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6383 let chanmon_cfgs = create_chanmon_cfgs(2);
6384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6386 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6387 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6388 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6390 let logger = test_utils::TestLogger::new();
6391 for i in 0..max_accepted_htlcs {
6392 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6393 let payment_event = {
6394 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6395 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();
6396 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6397 check_added_monitors!(nodes[0], 1);
6399 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6400 assert_eq!(events.len(), 1);
6401 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6402 assert_eq!(htlcs[0].htlc_id, i);
6406 SendEvent::from_event(events.remove(0))
6408 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6409 check_added_monitors!(nodes[1], 0);
6410 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6412 expect_pending_htlcs_forwardable!(nodes[1]);
6413 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6415 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6416 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6417 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();
6418 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6419 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6421 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6422 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6426 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6427 //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.
6428 let chanmon_cfgs = create_chanmon_cfgs(2);
6429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6431 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6432 let channel_value = 100000;
6433 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6434 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6436 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6438 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6439 // Manually create a route over our max in flight (which our router normally automatically
6441 let route = Route { paths: vec![vec![RouteHop {
6442 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6443 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6444 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6446 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6447 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)));
6449 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6450 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);
6452 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6455 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6457 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6458 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6459 let chanmon_cfgs = create_chanmon_cfgs(2);
6460 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6461 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6462 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6463 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6464 let htlc_minimum_msat: u64;
6466 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6467 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6468 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6471 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6472 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6473 let logger = test_utils::TestLogger::new();
6474 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();
6475 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6476 check_added_monitors!(nodes[0], 1);
6477 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6478 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6479 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6480 assert!(nodes[1].node.list_channels().is_empty());
6481 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6482 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()));
6483 check_added_monitors!(nodes[1], 1);
6487 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6488 //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
6489 let chanmon_cfgs = create_chanmon_cfgs(2);
6490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6492 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6493 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6494 let logger = test_utils::TestLogger::new();
6496 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6497 let channel_reserve = chan_stat.channel_reserve_msat;
6498 let feerate = get_feerate!(nodes[0], chan.2);
6499 // The 2* and +1 are for the fee spike reserve.
6500 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6502 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6503 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6504 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6505 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();
6506 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6507 check_added_monitors!(nodes[0], 1);
6508 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6510 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6511 // at this time channel-initiatee receivers are not required to enforce that senders
6512 // respect the fee_spike_reserve.
6513 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6514 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6516 assert!(nodes[1].node.list_channels().is_empty());
6517 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6518 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6519 check_added_monitors!(nodes[1], 1);
6523 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6524 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6525 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6526 let chanmon_cfgs = create_chanmon_cfgs(2);
6527 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6528 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6529 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6530 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6531 let logger = test_utils::TestLogger::new();
6533 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6534 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6536 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6537 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();
6539 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6540 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6541 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6542 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6544 let mut msg = msgs::UpdateAddHTLC {
6548 payment_hash: our_payment_hash,
6549 cltv_expiry: htlc_cltv,
6550 onion_routing_packet: onion_packet.clone(),
6553 for i in 0..super::channel::OUR_MAX_HTLCS {
6554 msg.htlc_id = i as u64;
6555 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6557 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6558 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6560 assert!(nodes[1].node.list_channels().is_empty());
6561 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6562 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6563 check_added_monitors!(nodes[1], 1);
6567 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6568 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6569 let chanmon_cfgs = create_chanmon_cfgs(2);
6570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6574 let logger = test_utils::TestLogger::new();
6576 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6577 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6578 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();
6579 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6580 check_added_monitors!(nodes[0], 1);
6581 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6582 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6583 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6585 assert!(nodes[1].node.list_channels().is_empty());
6586 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6587 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6588 check_added_monitors!(nodes[1], 1);
6592 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6593 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6594 let chanmon_cfgs = create_chanmon_cfgs(2);
6595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6597 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6598 let logger = test_utils::TestLogger::new();
6600 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6601 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6602 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6603 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();
6604 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6605 check_added_monitors!(nodes[0], 1);
6606 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6607 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6608 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6610 assert!(nodes[1].node.list_channels().is_empty());
6611 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6612 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6613 check_added_monitors!(nodes[1], 1);
6617 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6618 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6619 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6620 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6621 let chanmon_cfgs = create_chanmon_cfgs(2);
6622 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6623 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6624 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6625 let logger = test_utils::TestLogger::new();
6627 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6628 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6629 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6630 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();
6631 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6632 check_added_monitors!(nodes[0], 1);
6633 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6634 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6636 //Disconnect and Reconnect
6637 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6638 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6639 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6640 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6641 assert_eq!(reestablish_1.len(), 1);
6642 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6643 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6644 assert_eq!(reestablish_2.len(), 1);
6645 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6646 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6647 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6648 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6651 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6652 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6653 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6654 check_added_monitors!(nodes[1], 1);
6655 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6657 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6659 assert!(nodes[1].node.list_channels().is_empty());
6660 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6661 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6662 check_added_monitors!(nodes[1], 1);
6666 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6667 //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.
6669 let chanmon_cfgs = create_chanmon_cfgs(2);
6670 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6671 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6672 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6673 let logger = test_utils::TestLogger::new();
6674 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6675 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6676 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6677 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();
6678 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6680 check_added_monitors!(nodes[0], 1);
6681 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6682 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6684 let update_msg = msgs::UpdateFulfillHTLC{
6687 payment_preimage: our_payment_preimage,
6690 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6692 assert!(nodes[0].node.list_channels().is_empty());
6693 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6694 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()));
6695 check_added_monitors!(nodes[0], 1);
6699 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6700 //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.
6702 let chanmon_cfgs = create_chanmon_cfgs(2);
6703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6705 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6706 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6707 let logger = test_utils::TestLogger::new();
6709 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6710 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6711 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();
6712 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6713 check_added_monitors!(nodes[0], 1);
6714 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6715 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6717 let update_msg = msgs::UpdateFailHTLC{
6720 reason: msgs::OnionErrorPacket { data: Vec::new()},
6723 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6725 assert!(nodes[0].node.list_channels().is_empty());
6726 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6727 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6728 check_added_monitors!(nodes[0], 1);
6732 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6733 //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.
6735 let chanmon_cfgs = create_chanmon_cfgs(2);
6736 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6737 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6738 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6739 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6740 let logger = test_utils::TestLogger::new();
6742 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6743 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6744 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();
6745 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6746 check_added_monitors!(nodes[0], 1);
6747 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6748 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6749 let update_msg = msgs::UpdateFailMalformedHTLC{
6752 sha256_of_onion: [1; 32],
6753 failure_code: 0x8000,
6756 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6758 assert!(nodes[0].node.list_channels().is_empty());
6759 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6760 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()));
6761 check_added_monitors!(nodes[0], 1);
6765 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6766 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6768 let chanmon_cfgs = create_chanmon_cfgs(2);
6769 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6770 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6771 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6772 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6774 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6776 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6777 check_added_monitors!(nodes[1], 1);
6779 let events = nodes[1].node.get_and_clear_pending_msg_events();
6780 assert_eq!(events.len(), 1);
6781 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6783 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, .. } } => {
6784 assert!(update_add_htlcs.is_empty());
6785 assert_eq!(update_fulfill_htlcs.len(), 1);
6786 assert!(update_fail_htlcs.is_empty());
6787 assert!(update_fail_malformed_htlcs.is_empty());
6788 assert!(update_fee.is_none());
6789 update_fulfill_htlcs[0].clone()
6791 _ => panic!("Unexpected event"),
6795 update_fulfill_msg.htlc_id = 1;
6797 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6799 assert!(nodes[0].node.list_channels().is_empty());
6800 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6801 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6802 check_added_monitors!(nodes[0], 1);
6806 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6807 //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.
6809 let chanmon_cfgs = create_chanmon_cfgs(2);
6810 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6811 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6812 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6813 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6815 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6817 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6818 check_added_monitors!(nodes[1], 1);
6820 let events = nodes[1].node.get_and_clear_pending_msg_events();
6821 assert_eq!(events.len(), 1);
6822 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6824 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, .. } } => {
6825 assert!(update_add_htlcs.is_empty());
6826 assert_eq!(update_fulfill_htlcs.len(), 1);
6827 assert!(update_fail_htlcs.is_empty());
6828 assert!(update_fail_malformed_htlcs.is_empty());
6829 assert!(update_fee.is_none());
6830 update_fulfill_htlcs[0].clone()
6832 _ => panic!("Unexpected event"),
6836 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6838 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6840 assert!(nodes[0].node.list_channels().is_empty());
6841 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6842 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6843 check_added_monitors!(nodes[0], 1);
6847 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6848 //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.
6850 let chanmon_cfgs = create_chanmon_cfgs(2);
6851 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6852 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6853 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6854 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6855 let logger = test_utils::TestLogger::new();
6857 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6858 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6859 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();
6860 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6861 check_added_monitors!(nodes[0], 1);
6863 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6864 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6866 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6867 check_added_monitors!(nodes[1], 0);
6868 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6870 let events = nodes[1].node.get_and_clear_pending_msg_events();
6872 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6874 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, .. } } => {
6875 assert!(update_add_htlcs.is_empty());
6876 assert!(update_fulfill_htlcs.is_empty());
6877 assert!(update_fail_htlcs.is_empty());
6878 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6879 assert!(update_fee.is_none());
6880 update_fail_malformed_htlcs[0].clone()
6882 _ => panic!("Unexpected event"),
6885 update_msg.failure_code &= !0x8000;
6886 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6888 assert!(nodes[0].node.list_channels().is_empty());
6889 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6890 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6891 check_added_monitors!(nodes[0], 1);
6895 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6896 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6897 // * 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.
6899 let chanmon_cfgs = create_chanmon_cfgs(3);
6900 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6901 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6902 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6903 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6904 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6905 let logger = test_utils::TestLogger::new();
6907 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6910 let mut payment_event = {
6911 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6912 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();
6913 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6914 check_added_monitors!(nodes[0], 1);
6915 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6916 assert_eq!(events.len(), 1);
6917 SendEvent::from_event(events.remove(0))
6919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6920 check_added_monitors!(nodes[1], 0);
6921 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6922 expect_pending_htlcs_forwardable!(nodes[1]);
6923 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6924 assert_eq!(events_2.len(), 1);
6925 check_added_monitors!(nodes[1], 1);
6926 payment_event = SendEvent::from_event(events_2.remove(0));
6927 assert_eq!(payment_event.msgs.len(), 1);
6930 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6931 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6932 check_added_monitors!(nodes[2], 0);
6933 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6935 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6936 assert_eq!(events_3.len(), 1);
6937 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6939 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 } } => {
6940 assert!(update_add_htlcs.is_empty());
6941 assert!(update_fulfill_htlcs.is_empty());
6942 assert!(update_fail_htlcs.is_empty());
6943 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6944 assert!(update_fee.is_none());
6945 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6947 _ => panic!("Unexpected event"),
6951 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6953 check_added_monitors!(nodes[1], 0);
6954 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6955 expect_pending_htlcs_forwardable!(nodes[1]);
6956 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6957 assert_eq!(events_4.len(), 1);
6959 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6961 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, .. } } => {
6962 assert!(update_add_htlcs.is_empty());
6963 assert!(update_fulfill_htlcs.is_empty());
6964 assert_eq!(update_fail_htlcs.len(), 1);
6965 assert!(update_fail_malformed_htlcs.is_empty());
6966 assert!(update_fee.is_none());
6968 _ => panic!("Unexpected event"),
6971 check_added_monitors!(nodes[1], 1);
6974 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6975 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6976 // 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
6977 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6979 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6980 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6981 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6982 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6983 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6984 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6986 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
6988 // We route 2 dust-HTLCs between A and B
6989 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6990 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6991 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6993 // Cache one local commitment tx as previous
6994 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6996 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6997 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6998 check_added_monitors!(nodes[1], 0);
6999 expect_pending_htlcs_forwardable!(nodes[1]);
7000 check_added_monitors!(nodes[1], 1);
7002 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7003 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7004 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7005 check_added_monitors!(nodes[0], 1);
7007 // Cache one local commitment tx as lastest
7008 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7010 let events = nodes[0].node.get_and_clear_pending_msg_events();
7012 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7013 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7015 _ => panic!("Unexpected event"),
7018 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7019 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7021 _ => panic!("Unexpected event"),
7024 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7025 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7026 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7028 if announce_latest {
7029 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7031 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7034 check_closed_broadcast!(nodes[0], false);
7035 check_added_monitors!(nodes[0], 1);
7037 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7038 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7039 let events = nodes[0].node.get_and_clear_pending_events();
7040 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7041 assert_eq!(events.len(), 2);
7042 let mut first_failed = false;
7043 for event in events {
7045 Event::PaymentFailed { payment_hash, .. } => {
7046 if payment_hash == payment_hash_1 {
7047 assert!(!first_failed);
7048 first_failed = true;
7050 assert_eq!(payment_hash, payment_hash_2);
7053 _ => panic!("Unexpected event"),
7059 fn test_failure_delay_dust_htlc_local_commitment() {
7060 do_test_failure_delay_dust_htlc_local_commitment(true);
7061 do_test_failure_delay_dust_htlc_local_commitment(false);
7064 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7065 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7066 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7067 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7068 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7069 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7070 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7072 let chanmon_cfgs = create_chanmon_cfgs(3);
7073 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7074 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7075 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7076 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7078 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7080 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7081 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7083 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7084 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7086 // We revoked bs_commitment_tx
7088 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7089 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7092 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7093 let mut timeout_tx = Vec::new();
7095 // We fail dust-HTLC 1 by broadcast of local commitment tx
7096 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7097 check_closed_broadcast!(nodes[0], false);
7098 check_added_monitors!(nodes[0], 1);
7099 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7100 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7101 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7102 expect_payment_failed!(nodes[0], dust_hash, true);
7103 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7104 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7105 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7106 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7107 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7108 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7109 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7110 expect_payment_failed!(nodes[0], non_dust_hash, true);
7112 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7113 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7114 check_closed_broadcast!(nodes[0], false);
7115 check_added_monitors!(nodes[0], 1);
7116 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7117 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7118 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7119 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7121 expect_payment_failed!(nodes[0], dust_hash, true);
7122 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7123 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7124 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7125 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7126 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7127 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7128 expect_payment_failed!(nodes[0], non_dust_hash, true);
7130 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7132 let events = nodes[0].node.get_and_clear_pending_events();
7133 assert_eq!(events.len(), 2);
7136 Event::PaymentFailed { payment_hash, .. } => {
7137 if payment_hash == dust_hash { first = true; }
7138 else { first = false; }
7140 _ => panic!("Unexpected event"),
7143 Event::PaymentFailed { payment_hash, .. } => {
7144 if first { assert_eq!(payment_hash, non_dust_hash); }
7145 else { assert_eq!(payment_hash, dust_hash); }
7147 _ => panic!("Unexpected event"),
7154 fn test_sweep_outbound_htlc_failure_update() {
7155 do_test_sweep_outbound_htlc_failure_update(false, true);
7156 do_test_sweep_outbound_htlc_failure_update(false, false);
7157 do_test_sweep_outbound_htlc_failure_update(true, false);
7161 fn test_upfront_shutdown_script() {
7162 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7163 // enforce it at shutdown message
7165 let mut config = UserConfig::default();
7166 config.channel_options.announced_channel = true;
7167 config.peer_channel_config_limits.force_announced_channel_preference = false;
7168 config.channel_options.commit_upfront_shutdown_pubkey = false;
7169 let user_cfgs = [None, Some(config), None];
7170 let chanmon_cfgs = create_chanmon_cfgs(3);
7171 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7172 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7173 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7175 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7176 let flags = InitFeatures::known();
7177 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7178 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7179 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7180 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7181 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7182 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7183 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()));
7184 check_added_monitors!(nodes[2], 1);
7186 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7187 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7188 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7189 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7190 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7191 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7192 let events = nodes[2].node.get_and_clear_pending_msg_events();
7193 assert_eq!(events.len(), 1);
7195 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7196 _ => panic!("Unexpected event"),
7199 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7200 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7201 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7202 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7203 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7204 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7205 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7206 let events = nodes[1].node.get_and_clear_pending_msg_events();
7207 assert_eq!(events.len(), 1);
7209 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7210 _ => panic!("Unexpected event"),
7213 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7214 // channel smoothly, opt-out is from channel initiator here
7215 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7216 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7217 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7218 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7219 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7220 let events = nodes[0].node.get_and_clear_pending_msg_events();
7221 assert_eq!(events.len(), 1);
7223 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7224 _ => panic!("Unexpected event"),
7227 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7228 //// channel smoothly
7229 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7230 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7231 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7232 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7233 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7234 let events = nodes[0].node.get_and_clear_pending_msg_events();
7235 assert_eq!(events.len(), 2);
7237 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7238 _ => panic!("Unexpected event"),
7241 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7242 _ => panic!("Unexpected event"),
7247 fn test_upfront_shutdown_script_unsupport_segwit() {
7248 // We test that channel is closed early
7249 // if a segwit program is passed as upfront shutdown script,
7250 // but the peer does not support segwit.
7251 let chanmon_cfgs = create_chanmon_cfgs(2);
7252 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7253 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7254 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7256 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7258 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7259 open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7260 .push_slice(&[0, 0])
7263 let features = InitFeatures::known().clear_shutdown_anysegwit();
7264 nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7266 let events = nodes[0].node.get_and_clear_pending_msg_events();
7267 assert_eq!(events.len(), 1);
7269 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7270 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7271 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));
7273 _ => panic!("Unexpected event"),
7278 fn test_shutdown_script_any_segwit_allowed() {
7279 let mut config = UserConfig::default();
7280 config.channel_options.announced_channel = true;
7281 config.peer_channel_config_limits.force_announced_channel_preference = false;
7282 config.channel_options.commit_upfront_shutdown_pubkey = false;
7283 let user_cfgs = [None, Some(config), None];
7284 let chanmon_cfgs = create_chanmon_cfgs(3);
7285 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7286 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7287 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7289 //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7290 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7291 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7292 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7293 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7294 .push_slice(&[0, 0])
7296 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7297 let events = nodes[0].node.get_and_clear_pending_msg_events();
7298 assert_eq!(events.len(), 2);
7300 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7301 _ => panic!("Unexpected event"),
7304 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7305 _ => panic!("Unexpected event"),
7310 fn test_shutdown_script_any_segwit_not_allowed() {
7311 let mut config = UserConfig::default();
7312 config.channel_options.announced_channel = true;
7313 config.peer_channel_config_limits.force_announced_channel_preference = false;
7314 config.channel_options.commit_upfront_shutdown_pubkey = false;
7315 let user_cfgs = [None, Some(config), None];
7316 let chanmon_cfgs = create_chanmon_cfgs(3);
7317 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7318 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7319 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7321 //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7322 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7323 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7324 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7325 // Make an any segwit version script
7326 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7327 .push_slice(&[0, 0])
7329 let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7330 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7331 let events = nodes[0].node.get_and_clear_pending_msg_events();
7332 assert_eq!(events.len(), 2);
7334 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7335 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7336 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7338 _ => panic!("Unexpected event"),
7340 check_added_monitors!(nodes[0], 1);
7344 fn test_shutdown_script_segwit_but_not_anysegwit() {
7345 let mut config = UserConfig::default();
7346 config.channel_options.announced_channel = true;
7347 config.peer_channel_config_limits.force_announced_channel_preference = false;
7348 config.channel_options.commit_upfront_shutdown_pubkey = false;
7349 let user_cfgs = [None, Some(config), None];
7350 let chanmon_cfgs = create_chanmon_cfgs(3);
7351 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7352 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7353 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7355 //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7356 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7357 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7358 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7359 // Make a segwit script that is not a valid as any segwit
7360 node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7361 .push_slice(&[0, 0])
7363 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7364 let events = nodes[0].node.get_and_clear_pending_msg_events();
7365 assert_eq!(events.len(), 2);
7367 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7368 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7369 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7371 _ => panic!("Unexpected event"),
7373 check_added_monitors!(nodes[0], 1);
7377 fn test_user_configurable_csv_delay() {
7378 // We test our channel constructors yield errors when we pass them absurd csv delay
7380 let mut low_our_to_self_config = UserConfig::default();
7381 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7382 let mut high_their_to_self_config = UserConfig::default();
7383 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7384 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7385 let chanmon_cfgs = create_chanmon_cfgs(2);
7386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7388 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7390 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7391 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) {
7393 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())); },
7394 _ => panic!("Unexpected event"),
7396 } else { assert!(false) }
7398 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7399 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7400 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7401 open_channel.to_self_delay = 200;
7402 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) {
7404 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())); },
7405 _ => panic!("Unexpected event"),
7407 } else { assert!(false); }
7409 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7410 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7411 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()));
7412 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7413 accept_channel.to_self_delay = 200;
7414 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7415 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7417 &ErrorAction::SendErrorMessage { ref msg } => {
7418 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()));
7420 _ => { assert!(false); }
7422 } else { assert!(false); }
7424 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7425 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7426 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7427 open_channel.to_self_delay = 200;
7428 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) {
7430 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())); },
7431 _ => panic!("Unexpected event"),
7433 } else { assert!(false); }
7437 fn test_data_loss_protect() {
7438 // We want to be sure that :
7439 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7440 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7441 // * we close channel in case of detecting other being fallen behind
7442 // * we are able to claim our own outputs thanks to to_remote being static
7443 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7449 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7450 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7451 // during signing due to revoked tx
7452 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7453 let keys_manager = &chanmon_cfgs[0].keys_manager;
7456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7458 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7460 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7462 // Cache node A state before any channel update
7463 let previous_node_state = nodes[0].node.encode();
7464 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7465 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7467 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7468 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7470 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7471 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7473 // Restore node A from previous state
7474 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7475 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7476 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7477 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7478 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7479 persister = test_utils::TestPersister::new();
7480 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7482 let mut channel_monitors = HashMap::new();
7483 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7484 <(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 {
7485 keys_manager: keys_manager,
7486 fee_estimator: &fee_estimator,
7487 chain_monitor: &monitor,
7489 tx_broadcaster: &tx_broadcaster,
7490 default_config: UserConfig::default(),
7494 nodes[0].node = &node_state_0;
7495 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7496 nodes[0].chain_monitor = &monitor;
7497 nodes[0].chain_source = &chain_source;
7499 check_added_monitors!(nodes[0], 1);
7501 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7502 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7504 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7506 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7507 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7508 check_added_monitors!(nodes[0], 1);
7511 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7512 assert_eq!(node_txn.len(), 0);
7515 let mut reestablish_1 = Vec::with_capacity(1);
7516 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7517 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7518 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7519 reestablish_1.push(msg.clone());
7520 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7521 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7523 &ErrorAction::SendErrorMessage { ref msg } => {
7524 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");
7526 _ => panic!("Unexpected event!"),
7529 panic!("Unexpected event")
7533 // Check we close channel detecting A is fallen-behind
7534 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7535 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7536 check_added_monitors!(nodes[1], 1);
7539 // Check A is able to claim to_remote output
7540 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7541 assert_eq!(node_txn.len(), 1);
7542 check_spends!(node_txn[0], chan.3);
7543 assert_eq!(node_txn[0].output.len(), 2);
7544 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7545 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7546 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7547 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7548 assert_eq!(spend_txn.len(), 1);
7549 check_spends!(spend_txn[0], node_txn[0]);
7553 fn test_check_htlc_underpaying() {
7554 // Send payment through A -> B but A is maliciously
7555 // sending a probe payment (i.e less than expected value0
7556 // to B, B should refuse payment.
7558 let chanmon_cfgs = create_chanmon_cfgs(2);
7559 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7560 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7561 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7563 // Create some initial channels
7564 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7566 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7568 // Node 3 is expecting payment of 100_000 but receive 10_000,
7569 // fail htlc like we didn't know the preimage.
7570 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7571 nodes[1].node.process_pending_htlc_forwards();
7573 let events = nodes[1].node.get_and_clear_pending_msg_events();
7574 assert_eq!(events.len(), 1);
7575 let (update_fail_htlc, commitment_signed) = match events[0] {
7576 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 } } => {
7577 assert!(update_add_htlcs.is_empty());
7578 assert!(update_fulfill_htlcs.is_empty());
7579 assert_eq!(update_fail_htlcs.len(), 1);
7580 assert!(update_fail_malformed_htlcs.is_empty());
7581 assert!(update_fee.is_none());
7582 (update_fail_htlcs[0].clone(), commitment_signed)
7584 _ => panic!("Unexpected event"),
7586 check_added_monitors!(nodes[1], 1);
7588 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7589 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7591 // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7592 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7593 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(CHAN_CONFIRM_DEPTH));
7594 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7595 nodes[1].node.get_and_clear_pending_events();
7599 fn test_announce_disable_channels() {
7600 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7601 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7603 let chanmon_cfgs = create_chanmon_cfgs(2);
7604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7606 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7608 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7609 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7610 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7613 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7614 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7616 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7617 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7618 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7619 assert_eq!(msg_events.len(), 3);
7620 for e in msg_events {
7622 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7623 let short_id = msg.contents.short_channel_id;
7624 // Check generated channel_update match list in PendingChannelUpdate
7625 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7626 panic!("Generated ChannelUpdate for wrong chan!");
7629 _ => panic!("Unexpected event"),
7633 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7634 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7635 assert_eq!(reestablish_1.len(), 3);
7636 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7637 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7638 assert_eq!(reestablish_2.len(), 3);
7640 // Reestablish chan_1
7641 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7642 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7643 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7644 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7645 // Reestablish chan_2
7646 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7647 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7648 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7649 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7650 // Reestablish chan_3
7651 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7652 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7653 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7654 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7656 nodes[0].node.timer_chan_freshness_every_min();
7657 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7661 fn test_bump_penalty_txn_on_revoked_commitment() {
7662 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7663 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7665 let chanmon_cfgs = create_chanmon_cfgs(2);
7666 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7667 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7668 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7670 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7671 let logger = test_utils::TestLogger::new();
7673 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7674 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7675 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();
7676 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7678 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7679 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7680 assert_eq!(revoked_txn[0].output.len(), 4);
7681 assert_eq!(revoked_txn[0].input.len(), 1);
7682 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7683 let revoked_txid = revoked_txn[0].txid();
7685 let mut penalty_sum = 0;
7686 for outp in revoked_txn[0].output.iter() {
7687 if outp.script_pubkey.is_v0_p2wsh() {
7688 penalty_sum += outp.value;
7692 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7693 let starting_height = nodes[1].best_block_info().1;
7694 let header_114 = connect_blocks(&nodes[1], 14, starting_height, false, Default::default());
7696 // Actually revoke tx by claiming a HTLC
7697 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7698 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7699 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 15 + starting_height);
7700 check_added_monitors!(nodes[1], 1);
7702 // One or more justice tx should have been broadcast, check it
7706 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7707 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7708 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7709 assert_eq!(node_txn[0].output.len(), 1);
7710 check_spends!(node_txn[0], revoked_txn[0]);
7711 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7712 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7713 penalty_1 = node_txn[0].txid();
7717 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7718 let header = connect_blocks(&nodes[1], 15, 15 + starting_height, true, header.block_hash());
7719 let mut penalty_2 = penalty_1;
7720 let mut feerate_2 = 0;
7722 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7723 assert_eq!(node_txn.len(), 1);
7724 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7725 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7726 assert_eq!(node_txn[0].output.len(), 1);
7727 check_spends!(node_txn[0], revoked_txn[0]);
7728 penalty_2 = node_txn[0].txid();
7729 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7730 assert_ne!(penalty_2, penalty_1);
7731 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7732 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7733 // Verify 25% bump heuristic
7734 assert!(feerate_2 * 100 >= feerate_1 * 125);
7738 assert_ne!(feerate_2, 0);
7740 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7741 connect_blocks(&nodes[1], 1, 30 + starting_height, true, header);
7743 let mut feerate_3 = 0;
7745 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7746 assert_eq!(node_txn.len(), 1);
7747 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7748 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7749 assert_eq!(node_txn[0].output.len(), 1);
7750 check_spends!(node_txn[0], revoked_txn[0]);
7751 penalty_3 = node_txn[0].txid();
7752 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7753 assert_ne!(penalty_3, penalty_2);
7754 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7755 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7756 // Verify 25% bump heuristic
7757 assert!(feerate_3 * 100 >= feerate_2 * 125);
7761 assert_ne!(feerate_3, 0);
7763 nodes[1].node.get_and_clear_pending_events();
7764 nodes[1].node.get_and_clear_pending_msg_events();
7768 fn test_bump_penalty_txn_on_revoked_htlcs() {
7769 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7770 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7772 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7773 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7776 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7778 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7779 // Lock HTLC in both directions
7780 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7781 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7783 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7784 assert_eq!(revoked_local_txn[0].input.len(), 1);
7785 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7787 // Revoke local commitment tx
7788 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7790 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7791 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7792 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, CHAN_CONFIRM_DEPTH + 1);
7793 check_closed_broadcast!(nodes[1], false);
7794 check_added_monitors!(nodes[1], 1);
7796 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7797 assert_eq!(revoked_htlc_txn.len(), 4);
7798 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7799 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7800 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7801 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7802 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7803 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7804 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7805 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7806 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7807 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7808 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7809 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7810 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7811 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7814 // Broadcast set of revoked txn on A
7815 let hash_128 = connect_blocks(&nodes[0], 40, CHAN_CONFIRM_DEPTH, false, Default::default());
7816 let header_11 = BlockHeader { version: 0x20000000, prev_blockhash: hash_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7817 connect_block(&nodes[0], &Block { header: header_11, txdata: vec![revoked_local_txn[0].clone()] }, CHAN_CONFIRM_DEPTH + 40 + 1);
7818 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_11.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7819 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);
7820 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7825 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7826 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7827 // Verify claim tx are spending revoked HTLC txn
7829 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7830 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7831 // which are included in the same block (they are broadcasted because we scan the
7832 // transactions linearly and generate claims as we go, they likely should be removed in the
7834 assert_eq!(node_txn[0].input.len(), 1);
7835 check_spends!(node_txn[0], revoked_local_txn[0]);
7836 assert_eq!(node_txn[1].input.len(), 1);
7837 check_spends!(node_txn[1], revoked_local_txn[0]);
7838 assert_eq!(node_txn[2].input.len(), 1);
7839 check_spends!(node_txn[2], revoked_local_txn[0]);
7841 // Each of the three justice transactions claim a separate (single) output of the three
7842 // available, which we check here:
7843 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7844 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7845 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7847 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7848 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7850 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7851 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7852 // a remote commitment tx has already been confirmed).
7853 check_spends!(node_txn[3], chan.3);
7855 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7856 // output, checked above).
7857 assert_eq!(node_txn[4].input.len(), 2);
7858 assert_eq!(node_txn[4].output.len(), 1);
7859 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7861 first = node_txn[4].txid();
7862 // Store both feerates for later comparison
7863 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7864 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7865 penalty_txn = vec![node_txn[2].clone()];
7869 // Connect one more block to see if bumped penalty are issued for HTLC txn
7870 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7871 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, CHAN_CONFIRM_DEPTH + 40 + 3);
7872 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7873 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, CHAN_CONFIRM_DEPTH + 40 + 4);
7875 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7876 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7878 check_spends!(node_txn[0], revoked_local_txn[0]);
7879 check_spends!(node_txn[1], revoked_local_txn[0]);
7880 // Note that these are both bogus - they spend outputs already claimed in block 129:
7881 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7882 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7884 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7885 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7891 // Few more blocks to confirm penalty txn
7892 let header_135 = connect_blocks(&nodes[0], 4, CHAN_CONFIRM_DEPTH + 40 + 4, true, header_131.block_hash());
7893 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7894 let header_144 = connect_blocks(&nodes[0], 9, CHAN_CONFIRM_DEPTH + 40 + 8, true, header_135);
7896 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7897 assert_eq!(node_txn.len(), 1);
7899 assert_eq!(node_txn[0].input.len(), 2);
7900 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7901 // Verify bumped tx is different and 25% bump heuristic
7902 assert_ne!(first, node_txn[0].txid());
7903 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7904 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7905 assert!(feerate_2 * 100 > feerate_1 * 125);
7906 let txn = vec![node_txn[0].clone()];
7910 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7911 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7912 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, CHAN_CONFIRM_DEPTH + 40 + 8 + 10);
7913 connect_blocks(&nodes[0], 20, CHAN_CONFIRM_DEPTH + 40 + 8 + 10, true, header_145.block_hash());
7915 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7916 // We verify than no new transaction has been broadcast because previously
7917 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7918 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7919 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7920 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7921 // up bumped justice generation.
7922 assert_eq!(node_txn.len(), 0);
7925 check_closed_broadcast!(nodes[0], false);
7926 check_added_monitors!(nodes[0], 1);
7930 fn test_bump_penalty_txn_on_remote_commitment() {
7931 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7932 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7935 // Provide preimage for one
7936 // Check aggregation
7938 let chanmon_cfgs = create_chanmon_cfgs(2);
7939 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7940 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7941 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7943 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7944 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7945 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7947 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7948 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7949 assert_eq!(remote_txn[0].output.len(), 4);
7950 assert_eq!(remote_txn[0].input.len(), 1);
7951 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7953 // Claim a HTLC without revocation (provide B monitor with preimage)
7954 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7955 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7956 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7957 check_added_monitors!(nodes[1], 2);
7959 // One or more claim tx should have been broadcast, check it
7962 let feerate_timeout;
7963 let feerate_preimage;
7965 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7966 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7967 assert_eq!(node_txn[0].input.len(), 1);
7968 assert_eq!(node_txn[1].input.len(), 1);
7969 check_spends!(node_txn[0], remote_txn[0]);
7970 check_spends!(node_txn[1], remote_txn[0]);
7971 check_spends!(node_txn[2], chan.3);
7972 check_spends!(node_txn[3], node_txn[2]);
7973 check_spends!(node_txn[4], node_txn[2]);
7974 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7975 timeout = node_txn[0].txid();
7976 let index = node_txn[0].input[0].previous_output.vout;
7977 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7978 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7980 preimage = node_txn[1].txid();
7981 let index = node_txn[1].input[0].previous_output.vout;
7982 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7983 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7985 timeout = node_txn[1].txid();
7986 let index = node_txn[1].input[0].previous_output.vout;
7987 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7988 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7990 preimage = node_txn[0].txid();
7991 let index = node_txn[0].input[0].previous_output.vout;
7992 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7993 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7997 assert_ne!(feerate_timeout, 0);
7998 assert_ne!(feerate_preimage, 0);
8000 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8001 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
8003 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8004 assert_eq!(node_txn.len(), 2);
8005 assert_eq!(node_txn[0].input.len(), 1);
8006 assert_eq!(node_txn[1].input.len(), 1);
8007 check_spends!(node_txn[0], remote_txn[0]);
8008 check_spends!(node_txn[1], remote_txn[0]);
8009 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8010 let index = node_txn[0].input[0].previous_output.vout;
8011 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8012 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8013 assert!(new_feerate * 100 > feerate_timeout * 125);
8014 assert_ne!(timeout, node_txn[0].txid());
8016 let index = node_txn[1].input[0].previous_output.vout;
8017 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8018 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8019 assert!(new_feerate * 100 > feerate_preimage * 125);
8020 assert_ne!(preimage, node_txn[1].txid());
8022 let index = node_txn[1].input[0].previous_output.vout;
8023 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8024 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8025 assert!(new_feerate * 100 > feerate_timeout * 125);
8026 assert_ne!(timeout, node_txn[1].txid());
8028 let index = node_txn[0].input[0].previous_output.vout;
8029 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8030 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8031 assert!(new_feerate * 100 > feerate_preimage * 125);
8032 assert_ne!(preimage, node_txn[0].txid());
8037 nodes[1].node.get_and_clear_pending_events();
8038 nodes[1].node.get_and_clear_pending_msg_events();
8042 fn test_counterparty_raa_skip_no_crash() {
8043 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8044 // commitment transaction, we would have happily carried on and provided them the next
8045 // commitment transaction based on one RAA forward. This would probably eventually have led to
8046 // channel closure, but it would not have resulted in funds loss. Still, our
8047 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8048 // check simply that the channel is closed in response to such an RAA, but don't check whether
8049 // we decide to punish our counterparty for revoking their funds (as we don't currently
8051 let chanmon_cfgs = create_chanmon_cfgs(2);
8052 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8053 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8054 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8055 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8057 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8058 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8059 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8060 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8061 // Must revoke without gaps
8062 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8063 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8064 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8066 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8067 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8068 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8069 check_added_monitors!(nodes[1], 1);
8073 fn test_bump_txn_sanitize_tracking_maps() {
8074 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8075 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8077 let chanmon_cfgs = create_chanmon_cfgs(2);
8078 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8079 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8080 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8082 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8083 // Lock HTLC in both directions
8084 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8085 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8087 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8088 assert_eq!(revoked_local_txn[0].input.len(), 1);
8089 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8091 // Revoke local commitment tx
8092 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8094 // Broadcast set of revoked txn on A
8095 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8096 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8098 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8099 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8100 check_closed_broadcast!(nodes[0], false);
8101 check_added_monitors!(nodes[0], 1);
8103 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8104 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8105 check_spends!(node_txn[0], revoked_local_txn[0]);
8106 check_spends!(node_txn[1], revoked_local_txn[0]);
8107 check_spends!(node_txn[2], revoked_local_txn[0]);
8108 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8112 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8113 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8114 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8116 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8117 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8118 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8119 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8125 fn test_override_channel_config() {
8126 let chanmon_cfgs = create_chanmon_cfgs(2);
8127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8129 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8131 // Node0 initiates a channel to node1 using the override config.
8132 let mut override_config = UserConfig::default();
8133 override_config.own_channel_config.our_to_self_delay = 200;
8135 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8137 // Assert the channel created by node0 is using the override config.
8138 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8139 assert_eq!(res.channel_flags, 0);
8140 assert_eq!(res.to_self_delay, 200);
8144 fn test_override_0msat_htlc_minimum() {
8145 let mut zero_config = UserConfig::default();
8146 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8147 let chanmon_cfgs = create_chanmon_cfgs(2);
8148 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8149 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8150 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8152 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8153 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8154 assert_eq!(res.htlc_minimum_msat, 1);
8156 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8157 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8158 assert_eq!(res.htlc_minimum_msat, 1);
8162 fn test_simple_payment_secret() {
8163 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8164 // features, however.
8165 let chanmon_cfgs = create_chanmon_cfgs(3);
8166 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8167 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8168 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8170 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8171 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8172 let logger = test_utils::TestLogger::new();
8174 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8175 let payment_secret = PaymentSecret([0xdb; 32]);
8176 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8177 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();
8178 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8179 // Claiming with all the correct values but the wrong secret should result in nothing...
8180 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8181 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8182 // ...but with the right secret we should be able to claim all the way back
8183 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8187 fn test_simple_mpp() {
8188 // Simple test of sending a multi-path payment.
8189 let chanmon_cfgs = create_chanmon_cfgs(4);
8190 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8191 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8192 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8194 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8195 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8196 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8197 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8198 let logger = test_utils::TestLogger::new();
8200 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8201 let payment_secret = PaymentSecret([0xdb; 32]);
8202 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8203 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();
8204 let path = route.paths[0].clone();
8205 route.paths.push(path);
8206 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8207 route.paths[0][0].short_channel_id = chan_1_id;
8208 route.paths[0][1].short_channel_id = chan_3_id;
8209 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8210 route.paths[1][0].short_channel_id = chan_2_id;
8211 route.paths[1][1].short_channel_id = chan_4_id;
8212 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8213 // Claiming with all the correct values but the wrong secret should result in nothing...
8214 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8215 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8216 // ...but with the right secret we should be able to claim all the way back
8217 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8221 fn test_update_err_monitor_lockdown() {
8222 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8223 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8224 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8226 // This scenario may happen in a watchtower setup, where watchtower process a block height
8227 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8228 // commitment at same time.
8230 let chanmon_cfgs = create_chanmon_cfgs(2);
8231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8233 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8235 // Create some initial channel
8236 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8237 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8239 // Rebalance the network to generate htlc in the two directions
8240 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8242 // Route a HTLC from node 0 to node 1 (but don't settle)
8243 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8245 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8246 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8247 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8248 let persister = test_utils::TestPersister::new();
8250 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8251 let monitor = monitors.get(&outpoint).unwrap();
8252 let mut w = test_utils::TestVecWriter(Vec::new());
8253 monitor.write(&mut w).unwrap();
8254 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8255 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8256 assert!(new_monitor == *monitor);
8257 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);
8258 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8261 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8262 watchtower.chain_monitor.block_connected(&header, &[], 200);
8264 // Try to update ChannelMonitor
8265 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8266 check_added_monitors!(nodes[1], 1);
8267 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8268 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8269 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8270 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8271 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8272 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8273 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8274 } else { assert!(false); }
8275 } else { assert!(false); };
8276 // Our local monitor is in-sync and hasn't processed yet timeout
8277 check_added_monitors!(nodes[0], 1);
8278 let events = nodes[0].node.get_and_clear_pending_events();
8279 assert_eq!(events.len(), 1);
8283 fn test_concurrent_monitor_claim() {
8284 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8285 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8286 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8287 // state N+1 confirms. Alice claims output from state N+1.
8289 let chanmon_cfgs = create_chanmon_cfgs(2);
8290 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8291 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8292 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8294 // Create some initial channel
8295 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8296 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8298 // Rebalance the network to generate htlc in the two directions
8299 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8301 // Route a HTLC from node 0 to node 1 (but don't settle)
8302 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8304 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8305 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8306 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8307 let persister = test_utils::TestPersister::new();
8308 let watchtower_alice = {
8309 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8310 let monitor = monitors.get(&outpoint).unwrap();
8311 let mut w = test_utils::TestVecWriter(Vec::new());
8312 monitor.write(&mut w).unwrap();
8313 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8314 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8315 assert!(new_monitor == *monitor);
8316 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);
8317 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8320 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8321 watchtower_alice.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8323 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8325 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8326 assert_eq!(txn.len(), 2);
8330 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8331 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8332 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8333 let persister = test_utils::TestPersister::new();
8334 let watchtower_bob = {
8335 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8336 let monitor = monitors.get(&outpoint).unwrap();
8337 let mut w = test_utils::TestVecWriter(Vec::new());
8338 monitor.write(&mut w).unwrap();
8339 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8340 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8341 assert!(new_monitor == *monitor);
8342 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8343 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8346 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8347 watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8349 // Route another payment to generate another update with still previous HTLC pending
8350 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8352 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8353 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();
8354 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8356 check_added_monitors!(nodes[1], 1);
8358 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8359 assert_eq!(updates.update_add_htlcs.len(), 1);
8360 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8361 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8362 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8363 // Watchtower Alice should already have seen the block and reject the update
8364 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8365 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8366 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8367 } else { assert!(false); }
8368 } else { assert!(false); };
8369 // Our local monitor is in-sync and hasn't processed yet timeout
8370 check_added_monitors!(nodes[0], 1);
8372 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8373 watchtower_bob.chain_monitor.block_connected(&header, &vec![], CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8375 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8378 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8379 assert_eq!(txn.len(), 2);
8380 bob_state_y = txn[0].clone();
8384 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8385 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], CHAN_CONFIRM_DEPTH + 2 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS);
8387 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8388 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8389 // the onchain detection of the HTLC output
8390 assert_eq!(htlc_txn.len(), 2);
8391 check_spends!(htlc_txn[0], bob_state_y);
8392 check_spends!(htlc_txn[1], bob_state_y);
8397 fn test_pre_lockin_no_chan_closed_update() {
8398 // Test that if a peer closes a channel in response to a funding_created message we don't
8399 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8402 // Doing so would imply a channel monitor update before the initial channel monitor
8403 // registration, violating our API guarantees.
8405 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8406 // then opening a second channel with the same funding output as the first (which is not
8407 // rejected because the first channel does not exist in the ChannelManager) and closing it
8408 // before receiving funding_signed.
8409 let chanmon_cfgs = create_chanmon_cfgs(2);
8410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8414 // Create an initial channel
8415 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8416 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8417 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8418 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8419 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8421 // Move the first channel through the funding flow...
8422 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8424 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8425 check_added_monitors!(nodes[0], 0);
8427 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8428 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8429 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8430 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8434 fn test_htlc_no_detection() {
8435 // This test is a mutation to underscore the detection logic bug we had
8436 // before #653. HTLC value routed is above the remaining balance, thus
8437 // inverting HTLC and `to_remote` output. HTLC will come second and
8438 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8439 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8440 // outputs order detection for correct spending children filtring.
8442 let chanmon_cfgs = create_chanmon_cfgs(2);
8443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8445 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8447 // Create some initial channels
8448 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8450 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8451 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8452 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8453 assert_eq!(local_txn[0].input.len(), 1);
8454 assert_eq!(local_txn[0].output.len(), 3);
8455 check_spends!(local_txn[0], chan_1.3);
8457 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8458 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8459 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8460 // We deliberately connect the local tx twice as this should provoke a failure calling
8461 // this test before #653 fix.
8462 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8463 check_closed_broadcast!(nodes[0], false);
8464 check_added_monitors!(nodes[0], 1);
8466 let htlc_timeout = {
8467 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8468 assert_eq!(node_txn[0].input.len(), 1);
8469 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8470 check_spends!(node_txn[0], local_txn[0]);
8474 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8475 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8476 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8477 expect_payment_failed!(nodes[0], our_payment_hash, true);
8480 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8481 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8482 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8483 // Carol, Alice would be the upstream node, and Carol the downstream.)
8485 // Steps of the test:
8486 // 1) Alice sends a HTLC to Carol through Bob.
8487 // 2) Carol doesn't settle the HTLC.
8488 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8489 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8490 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8491 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8492 // 5) Carol release the preimage to Bob off-chain.
8493 // 6) Bob claims the offered output on the broadcasted commitment.
8494 let chanmon_cfgs = create_chanmon_cfgs(3);
8495 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8496 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8497 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8499 // Create some initial channels
8500 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8501 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8503 // Steps (1) and (2):
8504 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8505 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8507 // Check that Alice's commitment transaction now contains an output for this HTLC.
8508 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8509 check_spends!(alice_txn[0], chan_ab.3);
8510 assert_eq!(alice_txn[0].output.len(), 2);
8511 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8512 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8513 assert_eq!(alice_txn.len(), 2);
8515 // Steps (3) and (4):
8516 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8517 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8518 let mut force_closing_node = 0; // Alice force-closes
8519 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8520 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8521 check_closed_broadcast!(nodes[force_closing_node], false);
8522 check_added_monitors!(nodes[force_closing_node], 1);
8523 if go_onchain_before_fulfill {
8524 let txn_to_broadcast = match broadcast_alice {
8525 true => alice_txn.clone(),
8526 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8528 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8529 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, CHAN_CONFIRM_DEPTH * 2 + 1);
8530 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8531 if broadcast_alice {
8532 check_closed_broadcast!(nodes[1], false);
8533 check_added_monitors!(nodes[1], 1);
8535 assert_eq!(bob_txn.len(), 1);
8536 check_spends!(bob_txn[0], chan_ab.3);
8540 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8541 // process of removing the HTLC from their commitment transactions.
8542 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8543 check_added_monitors!(nodes[2], 1);
8544 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8545 assert!(carol_updates.update_add_htlcs.is_empty());
8546 assert!(carol_updates.update_fail_htlcs.is_empty());
8547 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8548 assert!(carol_updates.update_fee.is_none());
8549 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8551 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8552 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8553 if !go_onchain_before_fulfill && broadcast_alice {
8554 let events = nodes[1].node.get_and_clear_pending_msg_events();
8555 assert_eq!(events.len(), 1);
8557 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8558 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8560 _ => panic!("Unexpected event"),
8563 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8564 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8565 // Carol<->Bob's updated commitment transaction info.
8566 check_added_monitors!(nodes[1], 2);
8568 let events = nodes[1].node.get_and_clear_pending_msg_events();
8569 assert_eq!(events.len(), 2);
8570 let bob_revocation = match events[0] {
8571 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8572 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8575 _ => panic!("Unexpected event"),
8577 let bob_updates = match events[1] {
8578 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8579 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8582 _ => panic!("Unexpected event"),
8585 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8586 check_added_monitors!(nodes[2], 1);
8587 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8588 check_added_monitors!(nodes[2], 1);
8590 let events = nodes[2].node.get_and_clear_pending_msg_events();
8591 assert_eq!(events.len(), 1);
8592 let carol_revocation = match events[0] {
8593 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8594 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8597 _ => panic!("Unexpected event"),
8599 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8600 check_added_monitors!(nodes[1], 1);
8602 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8603 // here's where we put said channel's commitment tx on-chain.
8604 let mut txn_to_broadcast = alice_txn.clone();
8605 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8606 if !go_onchain_before_fulfill {
8607 let header = BlockHeader { version: 0x20000000, prev_blockhash: nodes[1].best_block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8608 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, CHAN_CONFIRM_DEPTH * 2 + 1);
8609 // If Bob was the one to force-close, he will have already passed these checks earlier.
8610 if broadcast_alice {
8611 check_closed_broadcast!(nodes[1], false);
8612 check_added_monitors!(nodes[1], 1);
8614 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8615 if broadcast_alice {
8616 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8617 // new block being connected. The ChannelManager being notified triggers a monitor update,
8618 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8619 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8621 assert_eq!(bob_txn.len(), 3);
8622 check_spends!(bob_txn[1], chan_ab.3);
8624 assert_eq!(bob_txn.len(), 2);
8625 check_spends!(bob_txn[0], chan_ab.3);
8630 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8631 // broadcasted commitment transaction.
8633 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8634 if go_onchain_before_fulfill {
8635 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8636 assert_eq!(bob_txn.len(), 2);
8638 let script_weight = match broadcast_alice {
8639 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8640 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8642 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8643 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8644 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8645 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8646 if broadcast_alice && !go_onchain_before_fulfill {
8647 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8648 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8650 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8651 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8657 fn test_onchain_htlc_settlement_after_close() {
8658 do_test_onchain_htlc_settlement_after_close(true, true);
8659 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8660 do_test_onchain_htlc_settlement_after_close(true, false);
8661 do_test_onchain_htlc_settlement_after_close(false, false);
8665 fn test_duplicate_chan_id() {
8666 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8667 // already open we reject it and keep the old channel.
8669 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8670 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8671 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8672 // updating logic for the existing channel.
8673 let chanmon_cfgs = create_chanmon_cfgs(2);
8674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8676 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8678 // Create an initial channel
8679 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8680 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8681 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8682 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()));
8684 // Try to create a second channel with the same temporary_channel_id as the first and check
8685 // that it is rejected.
8686 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8688 let events = nodes[1].node.get_and_clear_pending_msg_events();
8689 assert_eq!(events.len(), 1);
8691 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8692 // Technically, at this point, nodes[1] would be justified in thinking both the
8693 // first (valid) and second (invalid) channels are closed, given they both have
8694 // the same non-temporary channel_id. However, currently we do not, so we just
8695 // move forward with it.
8696 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8697 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8699 _ => panic!("Unexpected event"),
8703 // Move the first channel through the funding flow...
8704 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8706 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8707 check_added_monitors!(nodes[0], 0);
8709 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8710 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8712 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8713 assert_eq!(added_monitors.len(), 1);
8714 assert_eq!(added_monitors[0].0, funding_output);
8715 added_monitors.clear();
8717 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8719 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8720 let channel_id = funding_outpoint.to_channel_id();
8722 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8725 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8726 // Technically this is allowed by the spec, but we don't support it and there's little reason
8727 // to. Still, it shouldn't cause any other issues.
8728 open_chan_msg.temporary_channel_id = channel_id;
8729 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8731 let events = nodes[1].node.get_and_clear_pending_msg_events();
8732 assert_eq!(events.len(), 1);
8734 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8735 // Technically, at this point, nodes[1] would be justified in thinking both
8736 // channels are closed, but currently we do not, so we just move forward with it.
8737 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8738 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8740 _ => panic!("Unexpected event"),
8744 // Now try to create a second channel which has a duplicate funding output.
8745 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8746 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8747 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8748 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()));
8749 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8751 let funding_created = {
8752 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8753 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8754 let logger = test_utils::TestLogger::new();
8755 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8757 check_added_monitors!(nodes[0], 0);
8758 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8759 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8760 // still needs to be cleared here.
8761 check_added_monitors!(nodes[1], 1);
8763 // ...still, nodes[1] will reject the duplicate channel.
8765 let events = nodes[1].node.get_and_clear_pending_msg_events();
8766 assert_eq!(events.len(), 1);
8768 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8769 // Technically, at this point, nodes[1] would be justified in thinking both
8770 // channels are closed, but currently we do not, so we just move forward with it.
8771 assert_eq!(msg.channel_id, channel_id);
8772 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8774 _ => panic!("Unexpected event"),
8778 // finally, finish creating the original channel and send a payment over it to make sure
8779 // everything is functional.
8780 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8782 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8783 assert_eq!(added_monitors.len(), 1);
8784 assert_eq!(added_monitors[0].0, funding_output);
8785 added_monitors.clear();
8788 let events_4 = nodes[0].node.get_and_clear_pending_events();
8789 assert_eq!(events_4.len(), 1);
8791 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8792 assert_eq!(user_channel_id, 42);
8793 assert_eq!(*funding_txo, funding_output);
8795 _ => panic!("Unexpected event"),
8798 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8799 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8800 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8801 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8805 fn test_error_chans_closed() {
8806 // Test that we properly handle error messages, closing appropriate channels.
8808 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8809 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8810 // we can test various edge cases around it to ensure we don't regress.
8811 let chanmon_cfgs = create_chanmon_cfgs(3);
8812 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8813 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8814 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8816 // Create some initial channels
8817 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8818 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8819 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8821 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8822 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8823 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8825 // Closing a channel from a different peer has no effect
8826 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8827 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8829 // Closing one channel doesn't impact others
8830 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8831 check_added_monitors!(nodes[0], 1);
8832 check_closed_broadcast!(nodes[0], false);
8833 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8834 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);
8835 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);
8837 // A null channel ID should close all channels
8838 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8839 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8840 check_added_monitors!(nodes[0], 2);
8841 let events = nodes[0].node.get_and_clear_pending_msg_events();
8842 assert_eq!(events.len(), 2);
8844 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8845 assert_eq!(msg.contents.flags & 2, 2);
8847 _ => panic!("Unexpected event"),
8850 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8851 assert_eq!(msg.contents.flags & 2, 2);
8853 _ => panic!("Unexpected event"),
8855 // Note that at this point users of a standard PeerHandler will end up calling
8856 // peer_disconnected with no_connection_possible set to false, duplicating the
8857 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8858 // users with their own peer handling logic. We duplicate the call here, however.
8859 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8860 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8862 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8863 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8864 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);