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;
56 use ln::functional_test_utils::*;
57 use ln::chan_utils::CommitmentTransaction;
58 use ln::msgs::OptionalField::Present;
61 fn test_insane_channel_opens() {
62 // Stand up a network of 2 nodes
63 let chanmon_cfgs = create_chanmon_cfgs(2);
64 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
65 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
66 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
68 // Instantiate channel parameters where we push the maximum msats given our
70 let channel_value_sat = 31337; // same as funding satoshis
71 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
72 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
74 // Have node0 initiate a channel to node1 with aforementioned parameters
75 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
77 // Extract the channel open message from node0 to node1
78 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
80 // Test helper that asserts we get the correct error string given a mutator
81 // that supposedly makes the channel open message insane
82 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
83 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
84 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
85 assert_eq!(msg_events.len(), 1);
86 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
87 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
89 &ErrorAction::SendErrorMessage { .. } => {
90 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
92 _ => panic!("unexpected event!"),
94 } else { assert!(false); }
97 use ln::channel::MAX_FUNDING_SATOSHIS;
98 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
100 // Test all mutations that would make the channel open message insane
101 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
103 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
105 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
107 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
109 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
111 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
113 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
115 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
117 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
121 fn test_async_inbound_update_fee() {
122 let chanmon_cfgs = create_chanmon_cfgs(2);
123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
125 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
126 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
127 let logger = test_utils::TestLogger::new();
128 let channel_id = chan.2;
131 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
135 // send (1) commitment_signed -.
136 // <- update_add_htlc/commitment_signed
137 // send (2) RAA (awaiting remote revoke) -.
138 // (1) commitment_signed is delivered ->
139 // .- send (3) RAA (awaiting remote revoke)
140 // (2) RAA is delivered ->
141 // .- send (4) commitment_signed
142 // <- (3) RAA is delivered
143 // send (5) commitment_signed -.
144 // <- (4) commitment_signed is delivered
146 // (5) commitment_signed is delivered ->
148 // (6) RAA is delivered ->
150 // First nodes[0] generates an update_fee
151 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
152 check_added_monitors!(nodes[0], 1);
154 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
155 assert_eq!(events_0.len(), 1);
156 let (update_msg, commitment_signed) = match events_0[0] { // (1)
157 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
158 (update_fee.as_ref(), commitment_signed)
160 _ => panic!("Unexpected event"),
163 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
165 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
166 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
167 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
168 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
169 check_added_monitors!(nodes[1], 1);
171 let payment_event = {
172 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
173 assert_eq!(events_1.len(), 1);
174 SendEvent::from_event(events_1.remove(0))
176 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
177 assert_eq!(payment_event.msgs.len(), 1);
179 // ...now when the messages get delivered everyone should be happy
180 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
181 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
182 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
183 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
184 check_added_monitors!(nodes[0], 1);
186 // deliver(1), generate (3):
187 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
188 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
189 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
190 check_added_monitors!(nodes[1], 1);
192 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
193 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
194 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
195 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
196 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
197 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
198 assert!(bs_update.update_fee.is_none()); // (4)
199 check_added_monitors!(nodes[1], 1);
201 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
202 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
203 assert!(as_update.update_add_htlcs.is_empty()); // (5)
204 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
205 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
206 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
207 assert!(as_update.update_fee.is_none()); // (5)
208 check_added_monitors!(nodes[0], 1);
210 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
211 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
212 // only (6) so get_event_msg's assert(len == 1) passes
213 check_added_monitors!(nodes[0], 1);
215 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
216 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
217 check_added_monitors!(nodes[1], 1);
219 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
220 check_added_monitors!(nodes[0], 1);
222 let events_2 = nodes[0].node.get_and_clear_pending_events();
223 assert_eq!(events_2.len(), 1);
225 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
226 _ => panic!("Unexpected event"),
229 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
230 check_added_monitors!(nodes[1], 1);
234 fn test_update_fee_unordered_raa() {
235 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
236 // crash in an earlier version of the update_fee patch)
237 let chanmon_cfgs = create_chanmon_cfgs(2);
238 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
239 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
240 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
241 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
242 let channel_id = chan.2;
243 let logger = test_utils::TestLogger::new();
246 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
248 // First nodes[0] generates an update_fee
249 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
250 check_added_monitors!(nodes[0], 1);
252 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
253 assert_eq!(events_0.len(), 1);
254 let update_msg = match events_0[0] { // (1)
255 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
258 _ => panic!("Unexpected event"),
261 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
263 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
264 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
265 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
266 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
267 check_added_monitors!(nodes[1], 1);
269 let payment_event = {
270 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
271 assert_eq!(events_1.len(), 1);
272 SendEvent::from_event(events_1.remove(0))
274 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
275 assert_eq!(payment_event.msgs.len(), 1);
277 // ...now when the messages get delivered everyone should be happy
278 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
279 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
280 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
281 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
282 check_added_monitors!(nodes[0], 1);
284 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
285 check_added_monitors!(nodes[1], 1);
287 // We can't continue, sadly, because our (1) now has a bogus signature
291 fn test_multi_flight_update_fee() {
292 let chanmon_cfgs = create_chanmon_cfgs(2);
293 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
294 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
295 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
296 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
297 let channel_id = chan.2;
300 // update_fee/commitment_signed ->
301 // .- send (1) RAA and (2) commitment_signed
302 // update_fee (never committed) ->
304 // We have to manually generate the above update_fee, it is allowed by the protocol but we
305 // don't track which updates correspond to which revoke_and_ack responses so we're in
306 // AwaitingRAA mode and will not generate the update_fee yet.
307 // <- (1) RAA delivered
308 // (3) is generated and send (4) CS -.
309 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
310 // know the per_commitment_point to use for it.
311 // <- (2) commitment_signed delivered
313 // B should send no response here
314 // (4) commitment_signed delivered ->
315 // <- RAA/commitment_signed delivered
318 // First nodes[0] generates an update_fee
319 let initial_feerate = get_feerate!(nodes[0], channel_id);
320 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
321 check_added_monitors!(nodes[0], 1);
323 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
324 assert_eq!(events_0.len(), 1);
325 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
326 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
327 (update_fee.as_ref().unwrap(), commitment_signed)
329 _ => panic!("Unexpected event"),
332 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
333 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
334 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
335 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
336 check_added_monitors!(nodes[1], 1);
338 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
340 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
341 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
342 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
344 // Create the (3) update_fee message that nodes[0] will generate before it does...
345 let mut update_msg_2 = msgs::UpdateFee {
346 channel_id: update_msg_1.channel_id.clone(),
347 feerate_per_kw: (initial_feerate + 30) as u32,
350 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
352 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
354 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
356 // Deliver (1), generating (3) and (4)
357 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
358 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
359 check_added_monitors!(nodes[0], 1);
360 assert!(as_second_update.update_add_htlcs.is_empty());
361 assert!(as_second_update.update_fulfill_htlcs.is_empty());
362 assert!(as_second_update.update_fail_htlcs.is_empty());
363 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
364 // Check that the update_fee newly generated matches what we delivered:
365 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
366 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
368 // Deliver (2) commitment_signed
369 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
370 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
371 check_added_monitors!(nodes[0], 1);
372 // No commitment_signed so get_event_msg's assert(len == 1) passes
374 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
375 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
376 check_added_monitors!(nodes[1], 1);
379 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
380 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
381 check_added_monitors!(nodes[1], 1);
383 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
384 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
385 check_added_monitors!(nodes[0], 1);
387 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
388 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
389 // No commitment_signed so get_event_msg's assert(len == 1) passes
390 check_added_monitors!(nodes[0], 1);
392 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
393 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
394 check_added_monitors!(nodes[1], 1);
398 fn test_1_conf_open() {
399 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
400 // tests that we properly send one in that case.
401 let mut alice_config = UserConfig::default();
402 alice_config.own_channel_config.minimum_depth = 1;
403 alice_config.channel_options.announced_channel = true;
404 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
405 let mut bob_config = UserConfig::default();
406 bob_config.own_channel_config.minimum_depth = 1;
407 bob_config.channel_options.announced_channel = true;
408 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
409 let chanmon_cfgs = create_chanmon_cfgs(2);
410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
412 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
414 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
416 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
419 connect_block(&nodes[1], &block, 1);
420 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()));
422 connect_block(&nodes[0], &block, 1);
423 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
424 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
427 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
428 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
429 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
433 fn do_test_sanity_on_in_flight_opens(steps: u8) {
434 // Previously, we had issues deserializing channels when we hadn't connected the first block
435 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
436 // serialization round-trips and simply do steps towards opening a channel and then drop the
439 let chanmon_cfgs = create_chanmon_cfgs(2);
440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
444 if steps & 0b1000_0000 != 0{
446 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
449 connect_block(&nodes[0], &block, 1);
450 connect_block(&nodes[1], &block, 1);
453 if steps & 0x0f == 0 { return; }
454 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
455 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
457 if steps & 0x0f == 1 { return; }
458 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
459 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
461 if steps & 0x0f == 2 { return; }
462 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
464 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
466 if steps & 0x0f == 3 { return; }
467 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
468 check_added_monitors!(nodes[0], 0);
469 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
471 if steps & 0x0f == 4 { return; }
472 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
474 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
475 assert_eq!(added_monitors.len(), 1);
476 assert_eq!(added_monitors[0].0, funding_output);
477 added_monitors.clear();
479 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
481 if steps & 0x0f == 5 { return; }
482 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
484 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
485 assert_eq!(added_monitors.len(), 1);
486 assert_eq!(added_monitors[0].0, funding_output);
487 added_monitors.clear();
490 let events_4 = nodes[0].node.get_and_clear_pending_events();
491 assert_eq!(events_4.len(), 1);
493 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
494 assert_eq!(user_channel_id, 42);
495 assert_eq!(*funding_txo, funding_output);
497 _ => panic!("Unexpected event"),
500 if steps & 0x0f == 6 { return; }
501 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
503 if steps & 0x0f == 7 { return; }
504 confirm_transaction(&nodes[0], &tx);
505 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
509 fn test_sanity_on_in_flight_opens() {
510 do_test_sanity_on_in_flight_opens(0);
511 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
512 do_test_sanity_on_in_flight_opens(1);
513 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
514 do_test_sanity_on_in_flight_opens(2);
515 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(3);
517 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
518 do_test_sanity_on_in_flight_opens(4);
519 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(5);
521 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(6);
523 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(7);
525 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(8);
527 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
531 fn test_update_fee_vanilla() {
532 let chanmon_cfgs = create_chanmon_cfgs(2);
533 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
534 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
535 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
536 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
537 let channel_id = chan.2;
539 let feerate = get_feerate!(nodes[0], channel_id);
540 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
541 check_added_monitors!(nodes[0], 1);
543 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
544 assert_eq!(events_0.len(), 1);
545 let (update_msg, commitment_signed) = match events_0[0] {
546 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 } } => {
547 (update_fee.as_ref(), commitment_signed)
549 _ => panic!("Unexpected event"),
551 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
553 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
554 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
555 check_added_monitors!(nodes[1], 1);
557 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
558 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
559 check_added_monitors!(nodes[0], 1);
561 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
562 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
563 // No commitment_signed so get_event_msg's assert(len == 1) passes
564 check_added_monitors!(nodes[0], 1);
566 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
567 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
568 check_added_monitors!(nodes[1], 1);
572 fn test_update_fee_that_funder_cannot_afford() {
573 let chanmon_cfgs = create_chanmon_cfgs(2);
574 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
575 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
576 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
577 let channel_value = 1888;
578 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
579 let channel_id = chan.2;
582 nodes[0].node.update_fee(channel_id, feerate).unwrap();
583 check_added_monitors!(nodes[0], 1);
584 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
586 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
588 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
590 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
591 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
593 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
595 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
596 let num_htlcs = commitment_tx.output.len() - 2;
597 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
598 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
599 actual_fee = channel_value - actual_fee;
600 assert_eq!(total_fee, actual_fee);
603 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
604 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
605 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
606 check_added_monitors!(nodes[0], 1);
608 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
610 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
612 //While producing the commitment_signed response after handling a received update_fee request the
613 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
614 //Should produce and error.
615 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
616 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
617 check_added_monitors!(nodes[1], 1);
618 check_closed_broadcast!(nodes[1], true);
622 fn test_update_fee_with_fundee_update_add_htlc() {
623 let chanmon_cfgs = create_chanmon_cfgs(2);
624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
626 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
627 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
628 let channel_id = chan.2;
629 let logger = test_utils::TestLogger::new();
632 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
634 let feerate = get_feerate!(nodes[0], channel_id);
635 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
636 check_added_monitors!(nodes[0], 1);
638 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
639 assert_eq!(events_0.len(), 1);
640 let (update_msg, commitment_signed) = match events_0[0] {
641 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 } } => {
642 (update_fee.as_ref(), commitment_signed)
644 _ => panic!("Unexpected event"),
646 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
647 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
648 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
649 check_added_monitors!(nodes[1], 1);
651 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
652 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
653 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, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
655 // nothing happens since node[1] is in AwaitingRemoteRevoke
656 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
658 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
659 assert_eq!(added_monitors.len(), 0);
660 added_monitors.clear();
662 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
663 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
664 // node[1] has nothing to do
666 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
667 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
668 check_added_monitors!(nodes[0], 1);
670 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
671 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
672 // No commitment_signed so get_event_msg's assert(len == 1) passes
673 check_added_monitors!(nodes[0], 1);
674 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
675 check_added_monitors!(nodes[1], 1);
676 // AwaitingRemoteRevoke ends here
678 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
679 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
680 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
681 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
682 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
683 assert_eq!(commitment_update.update_fee.is_none(), true);
685 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
686 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
687 check_added_monitors!(nodes[0], 1);
688 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
690 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
691 check_added_monitors!(nodes[1], 1);
692 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
694 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
695 check_added_monitors!(nodes[1], 1);
696 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
697 // No commitment_signed so get_event_msg's assert(len == 1) passes
699 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
700 check_added_monitors!(nodes[0], 1);
701 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
703 expect_pending_htlcs_forwardable!(nodes[0]);
705 let events = nodes[0].node.get_and_clear_pending_events();
706 assert_eq!(events.len(), 1);
708 Event::PaymentReceived { .. } => { },
709 _ => panic!("Unexpected event"),
712 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
714 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
715 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
716 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
720 fn test_update_fee() {
721 let chanmon_cfgs = create_chanmon_cfgs(2);
722 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
723 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
724 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
725 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
726 let channel_id = chan.2;
729 // (1) update_fee/commitment_signed ->
730 // <- (2) revoke_and_ack
731 // .- send (3) commitment_signed
732 // (4) update_fee/commitment_signed ->
733 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
734 // <- (3) commitment_signed delivered
735 // send (6) revoke_and_ack -.
736 // <- (5) deliver revoke_and_ack
737 // (6) deliver revoke_and_ack ->
738 // .- send (7) commitment_signed in response to (4)
739 // <- (7) deliver commitment_signed
742 // Create and deliver (1)...
743 let feerate = get_feerate!(nodes[0], channel_id);
744 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
745 check_added_monitors!(nodes[0], 1);
747 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
748 assert_eq!(events_0.len(), 1);
749 let (update_msg, commitment_signed) = match events_0[0] {
750 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 } } => {
751 (update_fee.as_ref(), commitment_signed)
753 _ => panic!("Unexpected event"),
755 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
757 // Generate (2) and (3):
758 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
759 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
760 check_added_monitors!(nodes[1], 1);
763 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
764 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
765 check_added_monitors!(nodes[0], 1);
767 // Create and deliver (4)...
768 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
769 check_added_monitors!(nodes[0], 1);
770 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
771 assert_eq!(events_0.len(), 1);
772 let (update_msg, commitment_signed) = match events_0[0] {
773 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 } } => {
774 (update_fee.as_ref(), commitment_signed)
776 _ => panic!("Unexpected event"),
779 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
780 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
781 check_added_monitors!(nodes[1], 1);
783 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
784 // No commitment_signed so get_event_msg's assert(len == 1) passes
786 // Handle (3), creating (6):
787 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
788 check_added_monitors!(nodes[0], 1);
789 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
790 // No commitment_signed so get_event_msg's assert(len == 1) passes
793 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
794 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
795 check_added_monitors!(nodes[0], 1);
797 // Deliver (6), creating (7):
798 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
799 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
800 assert!(commitment_update.update_add_htlcs.is_empty());
801 assert!(commitment_update.update_fulfill_htlcs.is_empty());
802 assert!(commitment_update.update_fail_htlcs.is_empty());
803 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
804 assert!(commitment_update.update_fee.is_none());
805 check_added_monitors!(nodes[1], 1);
808 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
809 check_added_monitors!(nodes[0], 1);
810 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
811 // No commitment_signed so get_event_msg's assert(len == 1) passes
813 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
814 check_added_monitors!(nodes[1], 1);
815 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
818 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
819 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
823 fn pre_funding_lock_shutdown_test() {
824 // Test sending a shutdown prior to funding_locked after funding generation
825 let chanmon_cfgs = create_chanmon_cfgs(2);
826 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
827 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
828 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
829 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
830 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
831 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
832 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
834 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
835 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
836 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
837 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
838 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
840 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
841 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
842 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
843 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
844 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
845 assert!(node_0_none.is_none());
847 assert!(nodes[0].node.list_channels().is_empty());
848 assert!(nodes[1].node.list_channels().is_empty());
852 fn updates_shutdown_wait() {
853 // Test sending a shutdown with outstanding updates pending
854 let chanmon_cfgs = create_chanmon_cfgs(3);
855 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
856 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
857 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
858 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
859 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
860 let logger = test_utils::TestLogger::new();
862 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
864 nodes[0].node.close_channel(&chan_1.2).unwrap();
865 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
866 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
867 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
868 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
870 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
871 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
873 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
875 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
876 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
877 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
878 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
879 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
880 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
882 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
883 check_added_monitors!(nodes[2], 1);
884 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
885 assert!(updates.update_add_htlcs.is_empty());
886 assert!(updates.update_fail_htlcs.is_empty());
887 assert!(updates.update_fail_malformed_htlcs.is_empty());
888 assert!(updates.update_fee.is_none());
889 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
890 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
891 check_added_monitors!(nodes[1], 1);
892 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
893 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
895 assert!(updates_2.update_add_htlcs.is_empty());
896 assert!(updates_2.update_fail_htlcs.is_empty());
897 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
898 assert!(updates_2.update_fee.is_none());
899 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
900 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
901 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
903 let events = nodes[0].node.get_and_clear_pending_events();
904 assert_eq!(events.len(), 1);
906 Event::PaymentSent { ref payment_preimage } => {
907 assert_eq!(our_payment_preimage, *payment_preimage);
909 _ => panic!("Unexpected event"),
912 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
913 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
914 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
915 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
916 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
917 assert!(node_0_none.is_none());
919 assert!(nodes[0].node.list_channels().is_empty());
921 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
922 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
923 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
924 assert!(nodes[1].node.list_channels().is_empty());
925 assert!(nodes[2].node.list_channels().is_empty());
929 fn htlc_fail_async_shutdown() {
930 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
931 let chanmon_cfgs = create_chanmon_cfgs(3);
932 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
933 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
934 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
935 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
936 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
937 let logger = test_utils::TestLogger::new();
939 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
940 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
941 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
942 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
943 check_added_monitors!(nodes[0], 1);
944 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
945 assert_eq!(updates.update_add_htlcs.len(), 1);
946 assert!(updates.update_fulfill_htlcs.is_empty());
947 assert!(updates.update_fail_htlcs.is_empty());
948 assert!(updates.update_fail_malformed_htlcs.is_empty());
949 assert!(updates.update_fee.is_none());
951 nodes[1].node.close_channel(&chan_1.2).unwrap();
952 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
953 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
954 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
956 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
957 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
958 check_added_monitors!(nodes[1], 1);
959 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
960 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
962 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
963 assert!(updates_2.update_add_htlcs.is_empty());
964 assert!(updates_2.update_fulfill_htlcs.is_empty());
965 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
966 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
967 assert!(updates_2.update_fee.is_none());
969 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
970 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
972 expect_payment_failed!(nodes[0], our_payment_hash, false);
974 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
975 assert_eq!(msg_events.len(), 2);
976 let node_0_closing_signed = match msg_events[0] {
977 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
978 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
981 _ => panic!("Unexpected event"),
983 match msg_events[1] {
984 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
985 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
987 _ => panic!("Unexpected event"),
990 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
991 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
992 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
993 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
994 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
995 assert!(node_0_none.is_none());
997 assert!(nodes[0].node.list_channels().is_empty());
999 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1000 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1001 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1002 assert!(nodes[1].node.list_channels().is_empty());
1003 assert!(nodes[2].node.list_channels().is_empty());
1006 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1007 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1008 // messages delivered prior to disconnect
1009 let chanmon_cfgs = create_chanmon_cfgs(3);
1010 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1011 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1012 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1013 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1014 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1016 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1018 nodes[1].node.close_channel(&chan_1.2).unwrap();
1019 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1021 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
1022 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1024 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
1028 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1029 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1031 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1032 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1033 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1034 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1036 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1037 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1038 assert!(node_1_shutdown == node_1_2nd_shutdown);
1040 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1041 let node_0_2nd_shutdown = if recv_count > 0 {
1042 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1043 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1046 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1047 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_2nd_shutdown);
1048 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1050 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_2nd_shutdown);
1052 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1053 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1055 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1056 check_added_monitors!(nodes[2], 1);
1057 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1058 assert!(updates.update_add_htlcs.is_empty());
1059 assert!(updates.update_fail_htlcs.is_empty());
1060 assert!(updates.update_fail_malformed_htlcs.is_empty());
1061 assert!(updates.update_fee.is_none());
1062 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1063 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1064 check_added_monitors!(nodes[1], 1);
1065 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1066 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1068 assert!(updates_2.update_add_htlcs.is_empty());
1069 assert!(updates_2.update_fail_htlcs.is_empty());
1070 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1071 assert!(updates_2.update_fee.is_none());
1072 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1073 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1074 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1076 let events = nodes[0].node.get_and_clear_pending_events();
1077 assert_eq!(events.len(), 1);
1079 Event::PaymentSent { ref payment_preimage } => {
1080 assert_eq!(our_payment_preimage, *payment_preimage);
1082 _ => panic!("Unexpected event"),
1085 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1087 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1088 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1089 assert!(node_1_closing_signed.is_some());
1092 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1093 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1095 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1096 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1097 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1098 if recv_count == 0 {
1099 // If all closing_signeds weren't delivered we can just resume where we left off...
1100 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1102 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1103 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1104 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1106 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1107 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1108 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1110 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_3rd_shutdown);
1111 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1113 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_1_3rd_shutdown);
1114 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1115 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1117 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1118 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1119 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1120 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1121 assert!(node_0_none.is_none());
1123 // If one node, however, received + responded with an identical closing_signed we end
1124 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1125 // There isn't really anything better we can do simply, but in the future we might
1126 // explore storing a set of recently-closed channels that got disconnected during
1127 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1128 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1130 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1132 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1133 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1134 assert_eq!(msg_events.len(), 1);
1135 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1137 &ErrorAction::SendErrorMessage { ref msg } => {
1138 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1139 assert_eq!(msg.channel_id, chan_1.2);
1141 _ => panic!("Unexpected event!"),
1143 } else { panic!("Needed SendErrorMessage close"); }
1145 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1146 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1147 // closing_signed so we do it ourselves
1148 check_closed_broadcast!(nodes[0], false);
1149 check_added_monitors!(nodes[0], 1);
1152 assert!(nodes[0].node.list_channels().is_empty());
1154 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1155 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1156 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1157 assert!(nodes[1].node.list_channels().is_empty());
1158 assert!(nodes[2].node.list_channels().is_empty());
1162 fn test_shutdown_rebroadcast() {
1163 do_test_shutdown_rebroadcast(0);
1164 do_test_shutdown_rebroadcast(1);
1165 do_test_shutdown_rebroadcast(2);
1169 fn fake_network_test() {
1170 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1171 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1172 let chanmon_cfgs = create_chanmon_cfgs(4);
1173 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1174 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1175 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1177 // Create some initial channels
1178 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1179 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1180 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1182 // Rebalance the network a bit by relaying one payment through all the channels...
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);
1186 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188 // Send some more payments
1189 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1190 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1191 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1193 // Test failure packets
1194 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1195 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1197 // Add a new channel that skips 3
1198 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1201 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_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);
1206 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208 // Do some rebalance loop payments, simultaneously
1209 let mut hops = Vec::with_capacity(3);
1210 hops.push(RouteHop {
1211 pubkey: nodes[2].node.get_our_node_id(),
1212 node_features: NodeFeatures::empty(),
1213 short_channel_id: chan_2.0.contents.short_channel_id,
1214 channel_features: ChannelFeatures::empty(),
1216 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1218 hops.push(RouteHop {
1219 pubkey: nodes[3].node.get_our_node_id(),
1220 node_features: NodeFeatures::empty(),
1221 short_channel_id: chan_3.0.contents.short_channel_id,
1222 channel_features: ChannelFeatures::empty(),
1224 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1226 hops.push(RouteHop {
1227 pubkey: nodes[1].node.get_our_node_id(),
1228 node_features: NodeFeatures::empty(),
1229 short_channel_id: chan_4.0.contents.short_channel_id,
1230 channel_features: ChannelFeatures::empty(),
1232 cltv_expiry_delta: TEST_FINAL_CLTV,
1234 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;
1235 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;
1236 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1238 let mut hops = Vec::with_capacity(3);
1239 hops.push(RouteHop {
1240 pubkey: nodes[3].node.get_our_node_id(),
1241 node_features: NodeFeatures::empty(),
1242 short_channel_id: chan_4.0.contents.short_channel_id,
1243 channel_features: ChannelFeatures::empty(),
1245 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1247 hops.push(RouteHop {
1248 pubkey: nodes[2].node.get_our_node_id(),
1249 node_features: NodeFeatures::empty(),
1250 short_channel_id: chan_3.0.contents.short_channel_id,
1251 channel_features: ChannelFeatures::empty(),
1253 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1255 hops.push(RouteHop {
1256 pubkey: nodes[1].node.get_our_node_id(),
1257 node_features: NodeFeatures::empty(),
1258 short_channel_id: chan_2.0.contents.short_channel_id,
1259 channel_features: ChannelFeatures::empty(),
1261 cltv_expiry_delta: TEST_FINAL_CLTV,
1263 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;
1264 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;
1265 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1267 // Claim the rebalances...
1268 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1269 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1271 // Add a duplicate new channel from 2 to 4
1272 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1274 // Send some payments across both channels
1275 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1276 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1277 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1281 let events = nodes[0].node.get_and_clear_pending_msg_events();
1282 assert_eq!(events.len(), 0);
1283 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);
1285 //TODO: Test that routes work again here as we've been notified that the channel is full
1287 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1288 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1289 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1291 // Close down the channels...
1292 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1293 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1294 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1295 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1296 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1300 fn holding_cell_htlc_counting() {
1301 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1302 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1303 // commitment dance rounds.
1304 let chanmon_cfgs = create_chanmon_cfgs(3);
1305 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1306 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1307 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1308 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1309 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1310 let logger = test_utils::TestLogger::new();
1312 let mut payments = Vec::new();
1313 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1314 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1315 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1316 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1317 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1318 payments.push((payment_preimage, payment_hash));
1320 check_added_monitors!(nodes[1], 1);
1322 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1323 assert_eq!(events.len(), 1);
1324 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1325 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1327 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1328 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1330 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1332 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1333 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1334 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1335 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1336 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1337 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1340 // This should also be true if we try to forward a payment.
1341 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1343 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1344 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1345 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1346 check_added_monitors!(nodes[0], 1);
1349 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1350 assert_eq!(events.len(), 1);
1351 let payment_event = SendEvent::from_event(events.pop().unwrap());
1352 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1354 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1355 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1356 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1357 // fails), the second will process the resulting failure and fail the HTLC backward.
1358 expect_pending_htlcs_forwardable!(nodes[1]);
1359 expect_pending_htlcs_forwardable!(nodes[1]);
1360 check_added_monitors!(nodes[1], 1);
1362 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1363 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1364 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1366 let events = nodes[0].node.get_and_clear_pending_msg_events();
1367 assert_eq!(events.len(), 1);
1369 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1370 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1372 _ => panic!("Unexpected event"),
1375 expect_payment_failed!(nodes[0], payment_hash_2, false);
1377 // Now forward all the pending HTLCs and claim them back
1378 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1379 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1380 check_added_monitors!(nodes[2], 1);
1382 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1383 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1384 check_added_monitors!(nodes[1], 1);
1385 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1387 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1388 check_added_monitors!(nodes[1], 1);
1389 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1391 for ref update in as_updates.update_add_htlcs.iter() {
1392 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1394 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1395 check_added_monitors!(nodes[2], 1);
1396 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1397 check_added_monitors!(nodes[2], 1);
1398 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1400 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1401 check_added_monitors!(nodes[1], 1);
1402 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1403 check_added_monitors!(nodes[1], 1);
1404 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1406 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1407 check_added_monitors!(nodes[2], 1);
1409 expect_pending_htlcs_forwardable!(nodes[2]);
1411 let events = nodes[2].node.get_and_clear_pending_events();
1412 assert_eq!(events.len(), payments.len());
1413 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1415 &Event::PaymentReceived { ref payment_hash, .. } => {
1416 assert_eq!(*payment_hash, *hash);
1418 _ => panic!("Unexpected event"),
1422 for (preimage, _) in payments.drain(..) {
1423 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1426 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1430 fn duplicate_htlc_test() {
1431 // Test that we accept duplicate payment_hash HTLCs across the network and that
1432 // claiming/failing them are all separate and don't affect each other
1433 let chanmon_cfgs = create_chanmon_cfgs(6);
1434 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1435 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1436 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1438 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1439 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1440 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1441 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1442 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1443 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1445 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1447 *nodes[0].network_payment_count.borrow_mut() -= 1;
1448 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1450 *nodes[0].network_payment_count.borrow_mut() -= 1;
1451 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1453 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1454 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1455 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1459 fn test_duplicate_htlc_different_direction_onchain() {
1460 // Test that ChannelMonitor doesn't generate 2 preimage txn
1461 // when we have 2 HTLCs with same preimage that go across a node
1462 // in opposite directions.
1463 let chanmon_cfgs = create_chanmon_cfgs(2);
1464 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1465 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1466 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1468 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1469 let logger = test_utils::TestLogger::new();
1472 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1474 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1476 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1477 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, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1478 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1480 // Provide preimage to node 0 by claiming payment
1481 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1482 check_added_monitors!(nodes[0], 1);
1484 // Broadcast node 1 commitment txn
1485 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1487 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1488 let mut has_both_htlcs = 0; // check htlcs match ones committed
1489 for outp in remote_txn[0].output.iter() {
1490 if outp.value == 800_000 / 1000 {
1491 has_both_htlcs += 1;
1492 } else if outp.value == 900_000 / 1000 {
1493 has_both_htlcs += 1;
1496 assert_eq!(has_both_htlcs, 2);
1498 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1499 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1500 check_added_monitors!(nodes[0], 1);
1502 // Check we only broadcast 1 timeout tx
1503 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1504 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()) };
1505 assert_eq!(claim_txn.len(), 5);
1506 check_spends!(claim_txn[2], chan_1.3);
1507 check_spends!(claim_txn[3], claim_txn[2]);
1508 assert_eq!(htlc_pair.0.input.len(), 1);
1509 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1510 check_spends!(htlc_pair.0, remote_txn[0]);
1511 assert_eq!(htlc_pair.1.input.len(), 1);
1512 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1513 check_spends!(htlc_pair.1, remote_txn[0]);
1515 let events = nodes[0].node.get_and_clear_pending_msg_events();
1516 assert_eq!(events.len(), 2);
1519 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1520 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, .. } } => {
1521 assert!(update_add_htlcs.is_empty());
1522 assert!(update_fail_htlcs.is_empty());
1523 assert_eq!(update_fulfill_htlcs.len(), 1);
1524 assert!(update_fail_malformed_htlcs.is_empty());
1525 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1527 _ => panic!("Unexpected event"),
1533 fn test_basic_channel_reserve() {
1534 let chanmon_cfgs = create_chanmon_cfgs(2);
1535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1537 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1538 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1539 let logger = test_utils::TestLogger::new();
1541 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1542 let channel_reserve = chan_stat.channel_reserve_msat;
1544 // The 2* and +1 are for the fee spike reserve.
1545 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1546 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1547 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1548 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1549 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, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1550 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1552 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1554 &APIError::ChannelUnavailable{ref err} =>
1555 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1556 _ => panic!("Unexpected error variant"),
1559 _ => panic!("Unexpected error variant"),
1561 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1562 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);
1564 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1568 fn test_fee_spike_violation_fails_htlc() {
1569 let chanmon_cfgs = create_chanmon_cfgs(2);
1570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1572 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1573 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1574 let logger = test_utils::TestLogger::new();
1576 macro_rules! get_route_and_payment_hash {
1577 ($recv_value: expr) => {{
1578 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1579 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1580 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1581 (route, payment_hash, payment_preimage)
1585 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1586 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1587 let secp_ctx = Secp256k1::new();
1588 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1590 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1592 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1593 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1594 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1595 let msg = msgs::UpdateAddHTLC {
1598 amount_msat: htlc_msat,
1599 payment_hash: payment_hash,
1600 cltv_expiry: htlc_cltv,
1601 onion_routing_packet: onion_packet,
1604 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1606 // Now manually create the commitment_signed message corresponding to the update_add
1607 // nodes[0] just sent. In the code for construction of this message, "local" refers
1608 // to the sender of the message, and "remote" refers to the receiver.
1610 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1612 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1614 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1615 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1616 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1617 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1618 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1619 let chan_signer = local_chan.get_signer();
1620 let pubkeys = chan_signer.pubkeys();
1621 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1622 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1623 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1625 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1626 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1627 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1628 let chan_signer = remote_chan.get_signer();
1629 let pubkeys = chan_signer.pubkeys();
1630 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1631 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1634 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1635 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1636 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1638 // Build the remote commitment transaction so we can sign it, and then later use the
1639 // signature for the commitment_signed message.
1640 let local_chan_balance = 1313;
1642 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1644 amount_msat: 3460001,
1645 cltv_expiry: htlc_cltv,
1647 transaction_output_index: Some(1),
1650 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1653 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1654 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1655 let local_chan_signer = local_chan.get_signer();
1656 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1660 commit_tx_keys.clone(),
1662 &mut vec![(accepted_htlc_info, ())],
1663 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1665 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1668 let commit_signed_msg = msgs::CommitmentSigned {
1671 htlc_signatures: res.1
1674 // Send the commitment_signed message to the nodes[1].
1675 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1676 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1678 // Send the RAA to nodes[1].
1679 let raa_msg = msgs::RevokeAndACK {
1681 per_commitment_secret: local_secret,
1682 next_per_commitment_point: next_local_point
1684 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1686 let events = nodes[1].node.get_and_clear_pending_msg_events();
1687 assert_eq!(events.len(), 1);
1688 // Make sure the HTLC failed in the way we expect.
1690 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1691 assert_eq!(update_fail_htlcs.len(), 1);
1692 update_fail_htlcs[0].clone()
1694 _ => panic!("Unexpected event"),
1696 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1698 check_added_monitors!(nodes[1], 2);
1702 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1703 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1704 // Set the fee rate for the channel very high, to the point where the fundee
1705 // sending any above-dust amount would result in a channel reserve violation.
1706 // In this test we check that we would be prevented from sending an HTLC in
1708 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1709 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1712 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1713 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1714 let logger = test_utils::TestLogger::new();
1716 macro_rules! get_route_and_payment_hash {
1717 ($recv_value: expr) => {{
1718 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1719 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1720 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, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1721 (route, payment_hash, payment_preimage)
1725 let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1726 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1727 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1728 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1729 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);
1733 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1734 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1735 // Set the fee rate for the channel very high, to the point where the funder
1736 // receiving 1 update_add_htlc would result in them closing the channel due
1737 // to channel reserve violation. This close could also happen if the fee went
1738 // up a more realistic amount, but many HTLCs were outstanding at the time of
1739 // the update_add_htlc.
1740 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1741 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1742 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1743 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1744 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1745 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1746 let logger = test_utils::TestLogger::new();
1748 macro_rules! get_route_and_payment_hash {
1749 ($recv_value: expr) => {{
1750 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1751 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1752 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, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1753 (route, payment_hash, payment_preimage)
1757 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1758 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1759 let secp_ctx = Secp256k1::new();
1760 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1761 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1762 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1763 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1764 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1765 let msg = msgs::UpdateAddHTLC {
1768 amount_msat: htlc_msat + 1,
1769 payment_hash: payment_hash,
1770 cltv_expiry: htlc_cltv,
1771 onion_routing_packet: onion_packet,
1774 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1775 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1776 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);
1777 assert_eq!(nodes[0].node.list_channels().len(), 0);
1778 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1779 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1780 check_added_monitors!(nodes[0], 1);
1784 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1785 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1786 // calculating our commitment transaction fee (this was previously broken).
1787 let chanmon_cfgs = create_chanmon_cfgs(2);
1788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1790 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1792 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1793 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1794 // transaction fee with 0 HTLCs (183 sats)).
1795 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1797 let dust_amt = 546000; // Dust amount
1798 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1799 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1800 // commitment transaction fee.
1801 let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1805 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1806 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1807 // calculating our counterparty's commitment transaction fee (this was previously broken).
1808 let chanmon_cfgs = create_chanmon_cfgs(2);
1809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1811 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1812 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1814 let payment_amt = 46000; // Dust amount
1815 // In the previous code, these first four payments would succeed.
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);
1819 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1821 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
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);
1826 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1828 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1829 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1830 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1831 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1835 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1836 let chanmon_cfgs = create_chanmon_cfgs(3);
1837 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1838 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1839 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1840 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1841 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1842 let logger = test_utils::TestLogger::new();
1844 macro_rules! get_route_and_payment_hash {
1845 ($recv_value: expr) => {{
1846 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1847 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1848 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, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1849 (route, payment_hash, payment_preimage)
1854 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1855 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1856 let feerate = get_feerate!(nodes[0], chan.2);
1858 // Add a 2* and +1 for the fee spike reserve.
1859 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1860 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;
1861 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1863 // Add a pending HTLC.
1864 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1865 let payment_event_1 = {
1866 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1867 check_added_monitors!(nodes[0], 1);
1869 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1870 assert_eq!(events.len(), 1);
1871 SendEvent::from_event(events.remove(0))
1873 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1875 // Attempt to trigger a channel reserve violation --> payment failure.
1876 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1877 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;
1878 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1879 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1881 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1882 let secp_ctx = Secp256k1::new();
1883 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1884 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1885 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1886 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1887 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1888 let msg = msgs::UpdateAddHTLC {
1891 amount_msat: htlc_msat + 1,
1892 payment_hash: our_payment_hash_1,
1893 cltv_expiry: htlc_cltv,
1894 onion_routing_packet: onion_packet,
1897 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1898 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1899 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1900 assert_eq!(nodes[1].node.list_channels().len(), 1);
1901 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1902 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1903 check_added_monitors!(nodes[1], 1);
1907 fn test_inbound_outbound_capacity_is_not_zero() {
1908 let chanmon_cfgs = create_chanmon_cfgs(2);
1909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1911 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1912 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1913 let channels0 = node_chanmgrs[0].list_channels();
1914 let channels1 = node_chanmgrs[1].list_channels();
1915 assert_eq!(channels0.len(), 1);
1916 assert_eq!(channels1.len(), 1);
1918 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1919 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1921 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1922 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1925 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1926 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1930 fn test_channel_reserve_holding_cell_htlcs() {
1931 let chanmon_cfgs = create_chanmon_cfgs(3);
1932 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1933 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1934 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1935 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1936 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1937 let logger = test_utils::TestLogger::new();
1939 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1940 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1942 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1943 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1945 macro_rules! get_route_and_payment_hash {
1946 ($recv_value: expr) => {{
1947 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1948 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1949 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, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1950 (route, payment_hash, payment_preimage)
1954 macro_rules! expect_forward {
1956 let mut events = $node.node.get_and_clear_pending_msg_events();
1957 assert_eq!(events.len(), 1);
1958 check_added_monitors!($node, 1);
1959 let payment_event = SendEvent::from_event(events.remove(0));
1964 let feemsat = 239; // somehow we know?
1965 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1966 let feerate = get_feerate!(nodes[0], chan_1.2);
1968 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1970 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1972 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 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, &[], 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, &[], 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 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2667 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2668 check_added_monitors!(nodes[0], 1);
2669 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2670 check_added_monitors!(nodes[1], 1);
2671 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2672 expect_payment_failed!(nodes[1], payment_hash_2, true);
2674 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2675 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2677 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2678 check_spends!(node_txn[0], revoked_local_txn[0]);
2680 let mut witness_lens = BTreeSet::new();
2681 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2682 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2683 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2684 assert_eq!(witness_lens.len(), 3);
2685 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2686 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2687 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2689 // Next nodes[1] broadcasts its current local tx state:
2690 assert_eq!(node_txn[1].input.len(), 1);
2691 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2693 assert_eq!(node_txn[2].input.len(), 1);
2694 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2695 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2696 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2697 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2698 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2700 get_announce_close_broadcast_events(&nodes, 0, 1);
2701 assert_eq!(nodes[0].node.list_channels().len(), 0);
2702 assert_eq!(nodes[1].node.list_channels().len(), 0);
2706 fn claim_htlc_outputs_single_tx() {
2707 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2708 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2709 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2710 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2711 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2712 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2714 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2716 // Rebalance the network to generate htlc in the two directions
2717 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2718 // 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
2719 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2720 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2721 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2723 // Get the will-be-revoked local txn from node[0]
2724 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2726 //Revoke the old state
2727 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2730 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2731 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2732 check_added_monitors!(nodes[0], 1);
2733 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2734 check_added_monitors!(nodes[1], 1);
2735 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2737 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2738 expect_payment_failed!(nodes[1], payment_hash_2, true);
2740 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2741 assert_eq!(node_txn.len(), 9);
2742 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2743 // ChannelManager: local commmitment + local HTLC-timeout (2)
2744 // 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)
2745 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2747 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2748 assert_eq!(node_txn[2].input.len(), 1);
2749 check_spends!(node_txn[2], chan_1.3);
2750 assert_eq!(node_txn[3].input.len(), 1);
2751 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2752 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2753 check_spends!(node_txn[3], node_txn[2]);
2755 // Justice transactions are indices 1-2-4
2756 assert_eq!(node_txn[0].input.len(), 1);
2757 assert_eq!(node_txn[1].input.len(), 1);
2758 assert_eq!(node_txn[4].input.len(), 1);
2760 check_spends!(node_txn[0], revoked_local_txn[0]);
2761 check_spends!(node_txn[1], revoked_local_txn[0]);
2762 check_spends!(node_txn[4], revoked_local_txn[0]);
2764 let mut witness_lens = BTreeSet::new();
2765 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2766 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2767 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2768 assert_eq!(witness_lens.len(), 3);
2769 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2770 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2771 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2773 get_announce_close_broadcast_events(&nodes, 0, 1);
2774 assert_eq!(nodes[0].node.list_channels().len(), 0);
2775 assert_eq!(nodes[1].node.list_channels().len(), 0);
2779 fn test_htlc_on_chain_success() {
2780 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2781 // the preimage backward accordingly. So here we test that ChannelManager is
2782 // broadcasting the right event to other nodes in payment path.
2783 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2784 // A --------------------> B ----------------------> C (preimage)
2785 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2786 // commitment transaction was broadcast.
2787 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2789 // B should be able to claim via preimage if A then broadcasts its local tx.
2790 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2791 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2792 // PaymentSent event).
2794 let chanmon_cfgs = create_chanmon_cfgs(3);
2795 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2796 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2797 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2799 // Create some initial channels
2800 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2801 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2803 // Rebalance the network a bit by relaying one payment through all the channels...
2804 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2805 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2807 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2808 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2809 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2811 // Broadcast legit commitment tx from C on B's chain
2812 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2813 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2814 assert_eq!(commitment_tx.len(), 1);
2815 check_spends!(commitment_tx[0], chan_2.3);
2816 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2817 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2818 check_added_monitors!(nodes[2], 2);
2819 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2820 assert!(updates.update_add_htlcs.is_empty());
2821 assert!(updates.update_fail_htlcs.is_empty());
2822 assert!(updates.update_fail_malformed_htlcs.is_empty());
2823 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2825 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2826 check_closed_broadcast!(nodes[2], false);
2827 check_added_monitors!(nodes[2], 1);
2828 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)
2829 assert_eq!(node_txn.len(), 5);
2830 assert_eq!(node_txn[0], node_txn[3]);
2831 assert_eq!(node_txn[1], node_txn[4]);
2832 assert_eq!(node_txn[2], commitment_tx[0]);
2833 check_spends!(node_txn[0], commitment_tx[0]);
2834 check_spends!(node_txn[1], commitment_tx[0]);
2835 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2836 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2837 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2838 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2839 assert_eq!(node_txn[0].lock_time, 0);
2840 assert_eq!(node_txn[1].lock_time, 0);
2842 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2843 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2845 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2846 assert_eq!(added_monitors.len(), 1);
2847 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2848 added_monitors.clear();
2850 let events = nodes[1].node.get_and_clear_pending_msg_events();
2852 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2853 assert_eq!(added_monitors.len(), 2);
2854 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2855 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2856 added_monitors.clear();
2858 assert_eq!(events.len(), 2);
2860 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2861 _ => panic!("Unexpected event"),
2864 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, .. } } => {
2865 assert!(update_add_htlcs.is_empty());
2866 assert!(update_fail_htlcs.is_empty());
2867 assert_eq!(update_fulfill_htlcs.len(), 1);
2868 assert!(update_fail_malformed_htlcs.is_empty());
2869 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2871 _ => panic!("Unexpected event"),
2873 macro_rules! check_tx_local_broadcast {
2874 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2875 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2876 assert_eq!(node_txn.len(), 5);
2877 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2878 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2879 check_spends!(node_txn[0], $commitment_tx);
2880 check_spends!(node_txn[1], $commitment_tx);
2881 assert_ne!(node_txn[0].lock_time, 0);
2882 assert_ne!(node_txn[1].lock_time, 0);
2884 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2887 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2889 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2890 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2891 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2892 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2894 check_spends!(node_txn[2], $chan_tx);
2895 check_spends!(node_txn[3], node_txn[2]);
2896 check_spends!(node_txn[4], node_txn[2]);
2897 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2898 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2899 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2900 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2901 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2902 assert_ne!(node_txn[3].lock_time, 0);
2903 assert_ne!(node_txn[4].lock_time, 0);
2907 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2908 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2909 // timeout-claim of the output that nodes[2] just claimed via success.
2910 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2912 // Broadcast legit commitment tx from A on B's chain
2913 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2914 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2915 check_spends!(commitment_tx[0], chan_1.3);
2916 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2917 check_closed_broadcast!(nodes[1], false);
2918 check_added_monitors!(nodes[1], 1);
2919 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2920 assert_eq!(node_txn.len(), 4);
2921 check_spends!(node_txn[0], commitment_tx[0]);
2922 assert_eq!(node_txn[0].input.len(), 2);
2923 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2924 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2925 assert_eq!(node_txn[0].lock_time, 0);
2926 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2927 check_spends!(node_txn[1], chan_1.3);
2928 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2929 check_spends!(node_txn[2], node_txn[1]);
2930 check_spends!(node_txn[3], node_txn[1]);
2931 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2932 // we already checked the same situation with A.
2934 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2935 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2936 check_closed_broadcast!(nodes[0], false);
2937 check_added_monitors!(nodes[0], 1);
2938 let events = nodes[0].node.get_and_clear_pending_events();
2939 assert_eq!(events.len(), 2);
2940 let mut first_claimed = false;
2941 for event in events {
2943 Event::PaymentSent { payment_preimage } => {
2944 if payment_preimage == our_payment_preimage {
2945 assert!(!first_claimed);
2946 first_claimed = true;
2948 assert_eq!(payment_preimage, our_payment_preimage_2);
2951 _ => panic!("Unexpected event"),
2954 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2958 fn test_htlc_on_chain_timeout() {
2959 // Test that in case of a unilateral close onchain, we detect the state of output and
2960 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2961 // broadcasting the right event to other nodes in payment path.
2962 // A ------------------> B ----------------------> C (timeout)
2963 // B's commitment tx C's commitment tx
2965 // B's HTLC timeout tx B's timeout tx
2967 let chanmon_cfgs = create_chanmon_cfgs(3);
2968 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2969 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2970 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2972 // Create some intial channels
2973 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2974 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2976 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2977 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2978 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2980 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2981 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2983 // Broadcast legit commitment tx from C on B's chain
2984 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2985 check_spends!(commitment_tx[0], chan_2.3);
2986 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2987 check_added_monitors!(nodes[2], 0);
2988 expect_pending_htlcs_forwardable!(nodes[2]);
2989 check_added_monitors!(nodes[2], 1);
2991 let events = nodes[2].node.get_and_clear_pending_msg_events();
2992 assert_eq!(events.len(), 1);
2994 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, .. } } => {
2995 assert!(update_add_htlcs.is_empty());
2996 assert!(!update_fail_htlcs.is_empty());
2997 assert!(update_fulfill_htlcs.is_empty());
2998 assert!(update_fail_malformed_htlcs.is_empty());
2999 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3001 _ => panic!("Unexpected event"),
3003 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3004 check_closed_broadcast!(nodes[2], false);
3005 check_added_monitors!(nodes[2], 1);
3006 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3007 assert_eq!(node_txn.len(), 1);
3008 check_spends!(node_txn[0], chan_2.3);
3009 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3011 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3012 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3013 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
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[1], node_txn[3]);
3019 assert_eq!(node_txn[2], node_txn[4]);
3021 check_spends!(node_txn[0], commitment_tx[0]);
3022 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3024 check_spends!(node_txn[1], chan_2.3);
3025 check_spends!(node_txn[2], node_txn[1]);
3026 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3027 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3029 timeout_tx = node_txn[0].clone();
3033 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3034 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3035 check_added_monitors!(nodes[1], 1);
3036 check_closed_broadcast!(nodes[1], false);
3038 expect_pending_htlcs_forwardable!(nodes[1]);
3039 check_added_monitors!(nodes[1], 1);
3040 let events = nodes[1].node.get_and_clear_pending_msg_events();
3041 assert_eq!(events.len(), 1);
3043 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, .. } } => {
3044 assert!(update_add_htlcs.is_empty());
3045 assert!(!update_fail_htlcs.is_empty());
3046 assert!(update_fulfill_htlcs.is_empty());
3047 assert!(update_fail_malformed_htlcs.is_empty());
3048 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3050 _ => panic!("Unexpected event"),
3052 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
3053 assert_eq!(node_txn.len(), 0);
3055 // Broadcast legit commitment tx from B on A's chain
3056 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3057 check_spends!(commitment_tx[0], chan_1.3);
3059 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3060 check_closed_broadcast!(nodes[0], false);
3061 check_added_monitors!(nodes[0], 1);
3062 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3063 assert_eq!(node_txn.len(), 3);
3064 check_spends!(node_txn[0], commitment_tx[0]);
3065 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3066 check_spends!(node_txn[1], chan_1.3);
3067 check_spends!(node_txn[2], node_txn[1]);
3068 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3069 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3073 fn test_simple_commitment_revoked_fail_backward() {
3074 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3075 // and fail backward accordingly.
3077 let chanmon_cfgs = create_chanmon_cfgs(3);
3078 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3079 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3080 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3082 // Create some initial channels
3083 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3084 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3086 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3087 // Get the will-be-revoked local txn from nodes[2]
3088 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3089 // Revoke the old state
3090 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3092 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3094 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3095 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3096 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3097 check_added_monitors!(nodes[1], 1);
3098 check_closed_broadcast!(nodes[1], false);
3100 expect_pending_htlcs_forwardable!(nodes[1]);
3101 check_added_monitors!(nodes[1], 1);
3102 let events = nodes[1].node.get_and_clear_pending_msg_events();
3103 assert_eq!(events.len(), 1);
3105 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, .. } } => {
3106 assert!(update_add_htlcs.is_empty());
3107 assert_eq!(update_fail_htlcs.len(), 1);
3108 assert!(update_fulfill_htlcs.is_empty());
3109 assert!(update_fail_malformed_htlcs.is_empty());
3110 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3112 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3113 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3115 let events = nodes[0].node.get_and_clear_pending_msg_events();
3116 assert_eq!(events.len(), 1);
3118 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3119 _ => panic!("Unexpected event"),
3121 expect_payment_failed!(nodes[0], payment_hash, false);
3123 _ => panic!("Unexpected event"),
3127 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3128 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3129 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3130 // commitment transaction anymore.
3131 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3132 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3133 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3134 // technically disallowed and we should probably handle it reasonably.
3135 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3136 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3138 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3139 // commitment_signed (implying it will be in the latest remote commitment transaction).
3140 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3141 // and once they revoke the previous commitment transaction (allowing us to send a new
3142 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3143 let chanmon_cfgs = create_chanmon_cfgs(3);
3144 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3145 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3146 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3148 // Create some initial channels
3149 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3150 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3152 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3153 // Get the will-be-revoked local txn from nodes[2]
3154 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3155 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3156 // Revoke the old state
3157 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3159 let value = if use_dust {
3160 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3161 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3162 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3165 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3166 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3167 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3169 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3170 expect_pending_htlcs_forwardable!(nodes[2]);
3171 check_added_monitors!(nodes[2], 1);
3172 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173 assert!(updates.update_add_htlcs.is_empty());
3174 assert!(updates.update_fulfill_htlcs.is_empty());
3175 assert!(updates.update_fail_malformed_htlcs.is_empty());
3176 assert_eq!(updates.update_fail_htlcs.len(), 1);
3177 assert!(updates.update_fee.is_none());
3178 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3179 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3180 // Drop the last RAA from 3 -> 2
3182 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3183 expect_pending_htlcs_forwardable!(nodes[2]);
3184 check_added_monitors!(nodes[2], 1);
3185 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3186 assert!(updates.update_add_htlcs.is_empty());
3187 assert!(updates.update_fulfill_htlcs.is_empty());
3188 assert!(updates.update_fail_malformed_htlcs.is_empty());
3189 assert_eq!(updates.update_fail_htlcs.len(), 1);
3190 assert!(updates.update_fee.is_none());
3191 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3192 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3193 check_added_monitors!(nodes[1], 1);
3194 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3195 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3196 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3197 check_added_monitors!(nodes[2], 1);
3199 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3200 expect_pending_htlcs_forwardable!(nodes[2]);
3201 check_added_monitors!(nodes[2], 1);
3202 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3203 assert!(updates.update_add_htlcs.is_empty());
3204 assert!(updates.update_fulfill_htlcs.is_empty());
3205 assert!(updates.update_fail_malformed_htlcs.is_empty());
3206 assert_eq!(updates.update_fail_htlcs.len(), 1);
3207 assert!(updates.update_fee.is_none());
3208 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3209 // At this point first_payment_hash has dropped out of the latest two commitment
3210 // transactions that nodes[1] is tracking...
3211 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3212 check_added_monitors!(nodes[1], 1);
3213 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3214 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3215 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3216 check_added_monitors!(nodes[2], 1);
3218 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3219 // on nodes[2]'s RAA.
3220 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3221 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3222 let logger = test_utils::TestLogger::new();
3223 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, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3224 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3225 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3226 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3227 check_added_monitors!(nodes[1], 0);
3230 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3231 // One monitor for the new revocation preimage, no second on as we won't generate a new
3232 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3233 check_added_monitors!(nodes[1], 1);
3234 let events = nodes[1].node.get_and_clear_pending_events();
3235 assert_eq!(events.len(), 1);
3237 Event::PendingHTLCsForwardable { .. } => { },
3238 _ => panic!("Unexpected event"),
3240 // Deliberately don't process the pending fail-back so they all fail back at once after
3241 // block connection just like the !deliver_bs_raa case
3244 let mut failed_htlcs = HashSet::new();
3245 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3247 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3248 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3249 check_added_monitors!(nodes[1], 1);
3250 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3252 let events = nodes[1].node.get_and_clear_pending_events();
3253 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3255 Event::PaymentFailed { ref payment_hash, .. } => {
3256 assert_eq!(*payment_hash, fourth_payment_hash);
3258 _ => panic!("Unexpected event"),
3260 if !deliver_bs_raa {
3262 Event::PendingHTLCsForwardable { .. } => { },
3263 _ => panic!("Unexpected event"),
3266 nodes[1].node.process_pending_htlc_forwards();
3267 check_added_monitors!(nodes[1], 1);
3269 let events = nodes[1].node.get_and_clear_pending_msg_events();
3270 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3271 match events[if deliver_bs_raa { 1 } else { 0 }] {
3272 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3273 _ => panic!("Unexpected event"),
3277 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, .. } } => {
3278 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3279 assert_eq!(update_add_htlcs.len(), 1);
3280 assert!(update_fulfill_htlcs.is_empty());
3281 assert!(update_fail_htlcs.is_empty());
3282 assert!(update_fail_malformed_htlcs.is_empty());
3284 _ => panic!("Unexpected event"),
3287 match events[if deliver_bs_raa { 2 } else { 1 }] {
3288 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, .. } } => {
3289 assert!(update_add_htlcs.is_empty());
3290 assert_eq!(update_fail_htlcs.len(), 3);
3291 assert!(update_fulfill_htlcs.is_empty());
3292 assert!(update_fail_malformed_htlcs.is_empty());
3293 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3295 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3296 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3297 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3299 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3301 let events = nodes[0].node.get_and_clear_pending_msg_events();
3302 // If we delivered B's RAA we got an unknown preimage error, not something
3303 // that we should update our routing table for.
3304 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3305 for event in events {
3307 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3308 _ => panic!("Unexpected event"),
3311 let events = nodes[0].node.get_and_clear_pending_events();
3312 assert_eq!(events.len(), 3);
3314 Event::PaymentFailed { ref payment_hash, .. } => {
3315 assert!(failed_htlcs.insert(payment_hash.0));
3317 _ => panic!("Unexpected event"),
3320 Event::PaymentFailed { ref payment_hash, .. } => {
3321 assert!(failed_htlcs.insert(payment_hash.0));
3323 _ => panic!("Unexpected event"),
3326 Event::PaymentFailed { ref payment_hash, .. } => {
3327 assert!(failed_htlcs.insert(payment_hash.0));
3329 _ => panic!("Unexpected event"),
3332 _ => panic!("Unexpected event"),
3335 assert!(failed_htlcs.contains(&first_payment_hash.0));
3336 assert!(failed_htlcs.contains(&second_payment_hash.0));
3337 assert!(failed_htlcs.contains(&third_payment_hash.0));
3341 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3342 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3343 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3344 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3345 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3349 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3350 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3351 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3352 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3353 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3357 fn fail_backward_pending_htlc_upon_channel_failure() {
3358 let chanmon_cfgs = create_chanmon_cfgs(2);
3359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3361 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3362 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3363 let logger = test_utils::TestLogger::new();
3365 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3367 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3368 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3369 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, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3370 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3371 check_added_monitors!(nodes[0], 1);
3373 let payment_event = {
3374 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3375 assert_eq!(events.len(), 1);
3376 SendEvent::from_event(events.remove(0))
3378 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3379 assert_eq!(payment_event.msgs.len(), 1);
3382 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3383 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3385 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3386 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, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3387 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3388 check_added_monitors!(nodes[0], 0);
3390 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3393 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3395 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3397 let secp_ctx = Secp256k1::new();
3398 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3399 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3400 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3401 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, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3402 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3403 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3404 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3406 // Send a 0-msat update_add_htlc to fail the channel.
3407 let update_add_htlc = msgs::UpdateAddHTLC {
3413 onion_routing_packet,
3415 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3418 // Check that Alice fails backward the pending HTLC from the second payment.
3419 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3420 check_closed_broadcast!(nodes[0], true);
3421 check_added_monitors!(nodes[0], 1);
3425 fn test_htlc_ignore_latest_remote_commitment() {
3426 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3427 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3428 let chanmon_cfgs = create_chanmon_cfgs(2);
3429 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3430 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3431 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3432 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3434 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3435 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3436 check_closed_broadcast!(nodes[0], false);
3437 check_added_monitors!(nodes[0], 1);
3439 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3440 assert_eq!(node_txn.len(), 2);
3442 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3443 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3444 check_closed_broadcast!(nodes[1], false);
3445 check_added_monitors!(nodes[1], 1);
3447 // Duplicate the connect_block call since this may happen due to other listeners
3448 // registering new transactions
3449 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3453 fn test_force_close_fail_back() {
3454 // Check which HTLCs are failed-backwards on channel force-closure
3455 let chanmon_cfgs = create_chanmon_cfgs(3);
3456 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3457 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3458 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3459 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3460 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3461 let logger = test_utils::TestLogger::new();
3463 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3465 let mut payment_event = {
3466 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3467 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, &Vec::new(), 1000000, 42, &logger).unwrap();
3468 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3469 check_added_monitors!(nodes[0], 1);
3471 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3472 assert_eq!(events.len(), 1);
3473 SendEvent::from_event(events.remove(0))
3476 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3477 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3479 expect_pending_htlcs_forwardable!(nodes[1]);
3481 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3482 assert_eq!(events_2.len(), 1);
3483 payment_event = SendEvent::from_event(events_2.remove(0));
3484 assert_eq!(payment_event.msgs.len(), 1);
3486 check_added_monitors!(nodes[1], 1);
3487 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3488 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3489 check_added_monitors!(nodes[2], 1);
3490 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3492 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3493 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3494 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3496 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3497 check_closed_broadcast!(nodes[2], false);
3498 check_added_monitors!(nodes[2], 1);
3500 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3501 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3502 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3503 // back to nodes[1] upon timeout otherwise.
3504 assert_eq!(node_txn.len(), 1);
3509 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3510 txdata: vec![tx.clone()],
3512 connect_block(&nodes[1], &block, 1);
3514 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3515 check_closed_broadcast!(nodes[1], false);
3516 check_added_monitors!(nodes[1], 1);
3518 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3520 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3521 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3522 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3524 connect_block(&nodes[2], &block, 1);
3525 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3526 assert_eq!(node_txn.len(), 1);
3527 assert_eq!(node_txn[0].input.len(), 1);
3528 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3529 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3530 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3532 check_spends!(node_txn[0], tx);
3536 fn test_unconf_chan() {
3537 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3538 let chanmon_cfgs = create_chanmon_cfgs(2);
3539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3542 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3544 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3545 assert_eq!(channel_state.by_id.len(), 1);
3546 assert_eq!(channel_state.short_to_id.len(), 1);
3547 mem::drop(channel_state);
3549 let mut headers = Vec::new();
3550 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3551 headers.push(header.clone());
3553 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3554 headers.push(header.clone());
3556 while !headers.is_empty() {
3557 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3559 check_closed_broadcast!(nodes[0], false);
3560 check_added_monitors!(nodes[0], 1);
3561 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3562 assert_eq!(channel_state.by_id.len(), 0);
3563 assert_eq!(channel_state.short_to_id.len(), 0);
3567 fn test_simple_peer_disconnect() {
3568 // Test that we can reconnect when there are no lost messages
3569 let chanmon_cfgs = create_chanmon_cfgs(3);
3570 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3571 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3572 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3573 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3574 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3576 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3580 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3581 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3582 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3583 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3585 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3586 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3587 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3589 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3590 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3591 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3592 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3594 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3595 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3597 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3598 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3600 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3602 let events = nodes[0].node.get_and_clear_pending_events();
3603 assert_eq!(events.len(), 2);
3605 Event::PaymentSent { payment_preimage } => {
3606 assert_eq!(payment_preimage, payment_preimage_3);
3608 _ => panic!("Unexpected event"),
3611 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3612 assert_eq!(payment_hash, payment_hash_5);
3613 assert!(rejected_by_dest);
3615 _ => panic!("Unexpected event"),
3619 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3620 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3623 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3624 // Test that we can reconnect when in-flight HTLC updates get dropped
3625 let chanmon_cfgs = create_chanmon_cfgs(2);
3626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3629 if messages_delivered == 0 {
3630 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3631 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3633 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3636 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3638 let logger = test_utils::TestLogger::new();
3639 let payment_event = {
3640 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3641 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3642 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3643 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3644 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3645 check_added_monitors!(nodes[0], 1);
3647 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3648 assert_eq!(events.len(), 1);
3649 SendEvent::from_event(events.remove(0))
3651 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3653 if messages_delivered < 2 {
3654 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3656 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3657 if messages_delivered >= 3 {
3658 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3659 check_added_monitors!(nodes[1], 1);
3660 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3662 if messages_delivered >= 4 {
3663 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3664 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3665 check_added_monitors!(nodes[0], 1);
3667 if messages_delivered >= 5 {
3668 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3669 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3670 // No commitment_signed so get_event_msg's assert(len == 1) passes
3671 check_added_monitors!(nodes[0], 1);
3673 if messages_delivered >= 6 {
3674 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3675 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3676 check_added_monitors!(nodes[1], 1);
3683 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3684 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3685 if messages_delivered < 3 {
3686 // Even if the funding_locked messages get exchanged, as long as nothing further was
3687 // received on either side, both sides will need to resend them.
3688 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3689 } else if messages_delivered == 3 {
3690 // nodes[0] still wants its RAA + commitment_signed
3691 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3692 } else if messages_delivered == 4 {
3693 // nodes[0] still wants its commitment_signed
3694 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3695 } else if messages_delivered == 5 {
3696 // nodes[1] still wants its final RAA
3697 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3698 } else if messages_delivered == 6 {
3699 // Everything was delivered...
3700 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3703 let events_1 = nodes[1].node.get_and_clear_pending_events();
3704 assert_eq!(events_1.len(), 1);
3706 Event::PendingHTLCsForwardable { .. } => { },
3707 _ => panic!("Unexpected event"),
3710 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3711 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3712 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3714 nodes[1].node.process_pending_htlc_forwards();
3716 let events_2 = nodes[1].node.get_and_clear_pending_events();
3717 assert_eq!(events_2.len(), 1);
3719 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3720 assert_eq!(payment_hash_1, *payment_hash);
3721 assert_eq!(*payment_secret, None);
3722 assert_eq!(amt, 1000000);
3724 _ => panic!("Unexpected event"),
3727 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3728 check_added_monitors!(nodes[1], 1);
3730 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3731 assert_eq!(events_3.len(), 1);
3732 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3733 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3734 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3735 assert!(updates.update_add_htlcs.is_empty());
3736 assert!(updates.update_fail_htlcs.is_empty());
3737 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3738 assert!(updates.update_fail_malformed_htlcs.is_empty());
3739 assert!(updates.update_fee.is_none());
3740 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3742 _ => panic!("Unexpected event"),
3745 if messages_delivered >= 1 {
3746 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3748 let events_4 = nodes[0].node.get_and_clear_pending_events();
3749 assert_eq!(events_4.len(), 1);
3751 Event::PaymentSent { ref payment_preimage } => {
3752 assert_eq!(payment_preimage_1, *payment_preimage);
3754 _ => panic!("Unexpected event"),
3757 if messages_delivered >= 2 {
3758 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3759 check_added_monitors!(nodes[0], 1);
3760 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3762 if messages_delivered >= 3 {
3763 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3764 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3765 check_added_monitors!(nodes[1], 1);
3767 if messages_delivered >= 4 {
3768 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3769 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3770 // No commitment_signed so get_event_msg's assert(len == 1) passes
3771 check_added_monitors!(nodes[1], 1);
3773 if messages_delivered >= 5 {
3774 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3775 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3776 check_added_monitors!(nodes[0], 1);
3783 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3784 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3785 if messages_delivered < 2 {
3786 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3787 //TODO: Deduplicate PaymentSent events, then enable this if:
3788 //if messages_delivered < 1 {
3789 let events_4 = nodes[0].node.get_and_clear_pending_events();
3790 assert_eq!(events_4.len(), 1);
3792 Event::PaymentSent { ref payment_preimage } => {
3793 assert_eq!(payment_preimage_1, *payment_preimage);
3795 _ => panic!("Unexpected event"),
3798 } else if messages_delivered == 2 {
3799 // nodes[0] still wants its RAA + commitment_signed
3800 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3801 } else if messages_delivered == 3 {
3802 // nodes[0] still wants its commitment_signed
3803 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3804 } else if messages_delivered == 4 {
3805 // nodes[1] still wants its final RAA
3806 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3807 } else if messages_delivered == 5 {
3808 // Everything was delivered...
3809 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3812 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3813 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3814 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816 // Channel should still work fine...
3817 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3818 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3819 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3820 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3821 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3822 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3826 fn test_drop_messages_peer_disconnect_a() {
3827 do_test_drop_messages_peer_disconnect(0);
3828 do_test_drop_messages_peer_disconnect(1);
3829 do_test_drop_messages_peer_disconnect(2);
3830 do_test_drop_messages_peer_disconnect(3);
3834 fn test_drop_messages_peer_disconnect_b() {
3835 do_test_drop_messages_peer_disconnect(4);
3836 do_test_drop_messages_peer_disconnect(5);
3837 do_test_drop_messages_peer_disconnect(6);
3841 fn test_funding_peer_disconnect() {
3842 // Test that we can lock in our funding tx while disconnected
3843 let chanmon_cfgs = create_chanmon_cfgs(2);
3844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3847 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3849 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3850 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3852 confirm_transaction(&nodes[0], &tx);
3853 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3854 assert_eq!(events_1.len(), 1);
3856 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3857 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3859 _ => panic!("Unexpected event"),
3862 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3864 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3865 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3867 confirm_transaction(&nodes[1], &tx);
3868 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3869 assert_eq!(events_2.len(), 2);
3870 let funding_locked = match events_2[0] {
3871 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3872 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3875 _ => panic!("Unexpected event"),
3877 let bs_announcement_sigs = match events_2[1] {
3878 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3879 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3882 _ => panic!("Unexpected event"),
3885 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3887 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3888 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3889 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3890 assert_eq!(events_3.len(), 2);
3891 let as_announcement_sigs = match events_3[0] {
3892 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3893 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3896 _ => panic!("Unexpected event"),
3898 let (as_announcement, as_update) = match events_3[1] {
3899 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3900 (msg.clone(), update_msg.clone())
3902 _ => panic!("Unexpected event"),
3905 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3906 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3907 assert_eq!(events_4.len(), 1);
3908 let (_, bs_update) = match events_4[0] {
3909 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3910 (msg.clone(), update_msg.clone())
3912 _ => panic!("Unexpected event"),
3915 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3916 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3917 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3919 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3920 let logger = test_utils::TestLogger::new();
3921 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, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3922 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3923 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3927 fn test_drop_messages_peer_disconnect_dual_htlc() {
3928 // Test that we can handle reconnecting when both sides of a channel have pending
3929 // commitment_updates when we disconnect.
3930 let chanmon_cfgs = create_chanmon_cfgs(2);
3931 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3932 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3933 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3934 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3935 let logger = test_utils::TestLogger::new();
3937 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3939 // Now try to send a second payment which will fail to send
3940 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3941 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3942 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, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3943 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3944 check_added_monitors!(nodes[0], 1);
3946 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3947 assert_eq!(events_1.len(), 1);
3949 MessageSendEvent::UpdateHTLCs { .. } => {},
3950 _ => panic!("Unexpected event"),
3953 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3954 check_added_monitors!(nodes[1], 1);
3956 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3957 assert_eq!(events_2.len(), 1);
3959 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 } } => {
3960 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3961 assert!(update_add_htlcs.is_empty());
3962 assert_eq!(update_fulfill_htlcs.len(), 1);
3963 assert!(update_fail_htlcs.is_empty());
3964 assert!(update_fail_malformed_htlcs.is_empty());
3965 assert!(update_fee.is_none());
3967 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3968 let events_3 = nodes[0].node.get_and_clear_pending_events();
3969 assert_eq!(events_3.len(), 1);
3971 Event::PaymentSent { ref payment_preimage } => {
3972 assert_eq!(*payment_preimage, payment_preimage_1);
3974 _ => panic!("Unexpected event"),
3977 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3978 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3979 // No commitment_signed so get_event_msg's assert(len == 1) passes
3980 check_added_monitors!(nodes[0], 1);
3982 _ => panic!("Unexpected event"),
3985 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3986 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3988 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3989 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3990 assert_eq!(reestablish_1.len(), 1);
3991 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3992 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3993 assert_eq!(reestablish_2.len(), 1);
3995 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3996 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3997 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3998 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4000 assert!(as_resp.0.is_none());
4001 assert!(bs_resp.0.is_none());
4003 assert!(bs_resp.1.is_none());
4004 assert!(bs_resp.2.is_none());
4006 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4008 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4009 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4010 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4011 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4012 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4014 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4015 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4016 // No commitment_signed so get_event_msg's assert(len == 1) passes
4017 check_added_monitors!(nodes[1], 1);
4019 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4020 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4021 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4022 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4023 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4024 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4025 assert!(bs_second_commitment_signed.update_fee.is_none());
4026 check_added_monitors!(nodes[1], 1);
4028 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4029 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4030 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4031 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4032 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4033 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4034 assert!(as_commitment_signed.update_fee.is_none());
4035 check_added_monitors!(nodes[0], 1);
4037 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4038 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4039 // No commitment_signed so get_event_msg's assert(len == 1) passes
4040 check_added_monitors!(nodes[0], 1);
4042 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4043 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4044 // No commitment_signed so get_event_msg's assert(len == 1) passes
4045 check_added_monitors!(nodes[1], 1);
4047 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4048 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4049 check_added_monitors!(nodes[1], 1);
4051 expect_pending_htlcs_forwardable!(nodes[1]);
4053 let events_5 = nodes[1].node.get_and_clear_pending_events();
4054 assert_eq!(events_5.len(), 1);
4056 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4057 assert_eq!(payment_hash_2, *payment_hash);
4058 assert_eq!(*payment_secret, None);
4060 _ => panic!("Unexpected event"),
4063 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4064 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4065 check_added_monitors!(nodes[0], 1);
4067 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4070 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4071 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4072 // to avoid our counterparty failing the channel.
4073 let chanmon_cfgs = create_chanmon_cfgs(2);
4074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4078 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4079 let logger = test_utils::TestLogger::new();
4081 let our_payment_hash = if send_partial_mpp {
4082 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4083 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4084 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4085 let payment_secret = PaymentSecret([0xdb; 32]);
4086 // Use the utility function send_payment_along_path to send the payment with MPP data which
4087 // indicates there are more HTLCs coming.
4088 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4089 check_added_monitors!(nodes[0], 1);
4090 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4091 assert_eq!(events.len(), 1);
4092 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4093 // hop should *not* yet generate any PaymentReceived event(s).
4094 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4097 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4100 let mut block = Block {
4101 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4104 connect_block(&nodes[0], &block, 101);
4105 connect_block(&nodes[1], &block, 101);
4106 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4107 block.header.prev_blockhash = block.block_hash();
4108 connect_block(&nodes[0], &block, i);
4109 connect_block(&nodes[1], &block, i);
4112 expect_pending_htlcs_forwardable!(nodes[1]);
4114 check_added_monitors!(nodes[1], 1);
4115 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4116 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4117 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4118 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4119 assert!(htlc_timeout_updates.update_fee.is_none());
4121 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4122 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4123 // 100_000 msat as u64, followed by a height of 123 as u32
4124 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4125 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4126 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4130 fn test_htlc_timeout() {
4131 do_test_htlc_timeout(true);
4132 do_test_htlc_timeout(false);
4135 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4136 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4137 let chanmon_cfgs = create_chanmon_cfgs(3);
4138 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4139 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4140 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4141 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4142 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4143 let logger = test_utils::TestLogger::new();
4145 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4146 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4148 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4149 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4150 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4152 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4153 check_added_monitors!(nodes[1], 1);
4155 // Now attempt to route a second payment, which should be placed in the holding cell
4156 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4158 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4159 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4160 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4161 check_added_monitors!(nodes[0], 1);
4162 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4163 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4164 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4165 expect_pending_htlcs_forwardable!(nodes[1]);
4166 check_added_monitors!(nodes[1], 0);
4168 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4169 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
4170 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4171 check_added_monitors!(nodes[1], 0);
4174 let mut block = Block {
4175 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4178 connect_block(&nodes[1], &block, 101);
4179 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4180 block.header.prev_blockhash = block.block_hash();
4181 connect_block(&nodes[1], &block, i);
4184 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4185 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4187 block.header.prev_blockhash = block.block_hash();
4188 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4191 expect_pending_htlcs_forwardable!(nodes[1]);
4192 check_added_monitors!(nodes[1], 1);
4193 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4194 assert_eq!(fail_commit.len(), 1);
4195 match fail_commit[0] {
4196 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4197 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4198 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4200 _ => unreachable!(),
4202 expect_payment_failed!(nodes[0], second_payment_hash, false);
4203 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4205 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4206 _ => panic!("Unexpected event"),
4209 panic!("Unexpected event");
4212 expect_payment_failed!(nodes[1], second_payment_hash, true);
4217 fn test_holding_cell_htlc_add_timeouts() {
4218 do_test_holding_cell_htlc_add_timeouts(false);
4219 do_test_holding_cell_htlc_add_timeouts(true);
4223 fn test_invalid_channel_announcement() {
4224 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4225 let secp_ctx = Secp256k1::new();
4226 let chanmon_cfgs = create_chanmon_cfgs(2);
4227 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4228 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4229 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4231 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4233 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4234 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4235 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4236 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4238 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 } );
4240 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4241 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4243 let as_network_key = nodes[0].node.get_our_node_id();
4244 let bs_network_key = nodes[1].node.get_our_node_id();
4246 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4248 let mut chan_announcement;
4250 macro_rules! dummy_unsigned_msg {
4252 msgs::UnsignedChannelAnnouncement {
4253 features: ChannelFeatures::known(),
4254 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4255 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4256 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4257 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4258 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4259 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4260 excess_data: Vec::new(),
4265 macro_rules! sign_msg {
4266 ($unsigned_msg: expr) => {
4267 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4268 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4269 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4270 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4271 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4272 chan_announcement = msgs::ChannelAnnouncement {
4273 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4274 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4275 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4276 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4277 contents: $unsigned_msg
4282 let unsigned_msg = dummy_unsigned_msg!();
4283 sign_msg!(unsigned_msg);
4284 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4285 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 } );
4287 // Configured with Network::Testnet
4288 let mut unsigned_msg = dummy_unsigned_msg!();
4289 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4290 sign_msg!(unsigned_msg);
4291 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4293 let mut unsigned_msg = dummy_unsigned_msg!();
4294 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4295 sign_msg!(unsigned_msg);
4296 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4300 fn test_no_txn_manager_serialize_deserialize() {
4301 let chanmon_cfgs = create_chanmon_cfgs(2);
4302 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4303 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4304 let logger: test_utils::TestLogger;
4305 let fee_estimator: test_utils::TestFeeEstimator;
4306 let persister: test_utils::TestPersister;
4307 let new_chain_monitor: test_utils::TestChainMonitor;
4308 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4309 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4311 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4313 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4315 let nodes_0_serialized = nodes[0].node.encode();
4316 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4317 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4319 logger = test_utils::TestLogger::new();
4320 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4321 persister = test_utils::TestPersister::new();
4322 let keys_manager = &chanmon_cfgs[0].keys_manager;
4323 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4324 nodes[0].chain_monitor = &new_chain_monitor;
4325 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4326 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4327 &mut chan_0_monitor_read, keys_manager).unwrap();
4328 assert!(chan_0_monitor_read.is_empty());
4330 let mut nodes_0_read = &nodes_0_serialized[..];
4331 let config = UserConfig::default();
4332 let (_, nodes_0_deserialized_tmp) = {
4333 let mut channel_monitors = HashMap::new();
4334 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4335 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4336 default_config: config,
4338 fee_estimator: &fee_estimator,
4339 chain_monitor: nodes[0].chain_monitor,
4340 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4345 nodes_0_deserialized = nodes_0_deserialized_tmp;
4346 assert!(nodes_0_read.is_empty());
4348 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4349 nodes[0].node = &nodes_0_deserialized;
4350 assert_eq!(nodes[0].node.list_channels().len(), 1);
4351 check_added_monitors!(nodes[0], 1);
4353 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4354 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4355 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4356 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4358 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4359 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4360 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4361 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4363 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4364 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4365 for node in nodes.iter() {
4366 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4367 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4368 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4371 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4375 fn test_manager_serialize_deserialize_events() {
4376 // This test makes sure the events field in ChannelManager survives de/serialization
4377 let chanmon_cfgs = create_chanmon_cfgs(2);
4378 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4379 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4380 let fee_estimator: test_utils::TestFeeEstimator;
4381 let persister: test_utils::TestPersister;
4382 let logger: test_utils::TestLogger;
4383 let new_chain_monitor: test_utils::TestChainMonitor;
4384 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4385 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4387 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4388 let channel_value = 100000;
4389 let push_msat = 10001;
4390 let a_flags = InitFeatures::known();
4391 let b_flags = InitFeatures::known();
4392 let node_a = nodes.remove(0);
4393 let node_b = nodes.remove(0);
4394 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4395 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()));
4396 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()));
4398 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4400 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4401 check_added_monitors!(node_a, 0);
4403 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()));
4405 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4406 assert_eq!(added_monitors.len(), 1);
4407 assert_eq!(added_monitors[0].0, funding_output);
4408 added_monitors.clear();
4411 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()));
4413 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4414 assert_eq!(added_monitors.len(), 1);
4415 assert_eq!(added_monitors[0].0, funding_output);
4416 added_monitors.clear();
4418 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4423 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4424 let nodes_0_serialized = nodes[0].node.encode();
4425 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4426 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4428 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4429 logger = test_utils::TestLogger::new();
4430 persister = test_utils::TestPersister::new();
4431 let keys_manager = &chanmon_cfgs[0].keys_manager;
4432 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4433 nodes[0].chain_monitor = &new_chain_monitor;
4434 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4435 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4436 &mut chan_0_monitor_read, keys_manager).unwrap();
4437 assert!(chan_0_monitor_read.is_empty());
4439 let mut nodes_0_read = &nodes_0_serialized[..];
4440 let config = UserConfig::default();
4441 let (_, nodes_0_deserialized_tmp) = {
4442 let mut channel_monitors = HashMap::new();
4443 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4444 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4445 default_config: config,
4447 fee_estimator: &fee_estimator,
4448 chain_monitor: nodes[0].chain_monitor,
4449 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4454 nodes_0_deserialized = nodes_0_deserialized_tmp;
4455 assert!(nodes_0_read.is_empty());
4457 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4459 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4460 nodes[0].node = &nodes_0_deserialized;
4462 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4463 let events_4 = nodes[0].node.get_and_clear_pending_events();
4464 assert_eq!(events_4.len(), 1);
4466 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4467 assert_eq!(user_channel_id, 42);
4468 assert_eq!(*funding_txo, funding_output);
4470 _ => panic!("Unexpected event"),
4473 // Make sure the channel is functioning as though the de/serialization never happened
4474 assert_eq!(nodes[0].node.list_channels().len(), 1);
4475 check_added_monitors!(nodes[0], 1);
4477 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4478 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4479 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4480 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4482 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4483 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4484 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4485 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4487 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4488 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4489 for node in nodes.iter() {
4490 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4491 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4492 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4495 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4499 fn test_simple_manager_serialize_deserialize() {
4500 let chanmon_cfgs = create_chanmon_cfgs(2);
4501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4503 let logger: test_utils::TestLogger;
4504 let fee_estimator: test_utils::TestFeeEstimator;
4505 let persister: test_utils::TestPersister;
4506 let new_chain_monitor: test_utils::TestChainMonitor;
4507 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4508 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4509 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4511 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4512 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4514 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4516 let nodes_0_serialized = nodes[0].node.encode();
4517 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4518 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4520 logger = test_utils::TestLogger::new();
4521 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4522 persister = test_utils::TestPersister::new();
4523 let keys_manager = &chanmon_cfgs[0].keys_manager;
4524 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4525 nodes[0].chain_monitor = &new_chain_monitor;
4526 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4527 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4528 &mut chan_0_monitor_read, keys_manager).unwrap();
4529 assert!(chan_0_monitor_read.is_empty());
4531 let mut nodes_0_read = &nodes_0_serialized[..];
4532 let (_, nodes_0_deserialized_tmp) = {
4533 let mut channel_monitors = HashMap::new();
4534 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4535 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4536 default_config: UserConfig::default(),
4538 fee_estimator: &fee_estimator,
4539 chain_monitor: nodes[0].chain_monitor,
4540 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4545 nodes_0_deserialized = nodes_0_deserialized_tmp;
4546 assert!(nodes_0_read.is_empty());
4548 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4549 nodes[0].node = &nodes_0_deserialized;
4550 check_added_monitors!(nodes[0], 1);
4552 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4554 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4555 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4559 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4560 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4561 let chanmon_cfgs = create_chanmon_cfgs(4);
4562 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4563 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4564 let logger: test_utils::TestLogger;
4565 let fee_estimator: test_utils::TestFeeEstimator;
4566 let persister: test_utils::TestPersister;
4567 let new_chain_monitor: test_utils::TestChainMonitor;
4568 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4569 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4570 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4571 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4572 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4574 let mut node_0_stale_monitors_serialized = Vec::new();
4575 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4576 let mut writer = test_utils::TestVecWriter(Vec::new());
4577 monitor.1.write(&mut writer).unwrap();
4578 node_0_stale_monitors_serialized.push(writer.0);
4581 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4583 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4584 let nodes_0_serialized = nodes[0].node.encode();
4586 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4587 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4588 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4589 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4591 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4593 let mut node_0_monitors_serialized = Vec::new();
4594 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4595 let mut writer = test_utils::TestVecWriter(Vec::new());
4596 monitor.1.write(&mut writer).unwrap();
4597 node_0_monitors_serialized.push(writer.0);
4600 logger = test_utils::TestLogger::new();
4601 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4602 persister = test_utils::TestPersister::new();
4603 let keys_manager = &chanmon_cfgs[0].keys_manager;
4604 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4605 nodes[0].chain_monitor = &new_chain_monitor;
4608 let mut node_0_stale_monitors = Vec::new();
4609 for serialized in node_0_stale_monitors_serialized.iter() {
4610 let mut read = &serialized[..];
4611 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4612 assert!(read.is_empty());
4613 node_0_stale_monitors.push(monitor);
4616 let mut node_0_monitors = Vec::new();
4617 for serialized in node_0_monitors_serialized.iter() {
4618 let mut read = &serialized[..];
4619 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4620 assert!(read.is_empty());
4621 node_0_monitors.push(monitor);
4624 let mut nodes_0_read = &nodes_0_serialized[..];
4625 if let Err(msgs::DecodeError::InvalidValue) =
4626 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4627 default_config: UserConfig::default(),
4629 fee_estimator: &fee_estimator,
4630 chain_monitor: nodes[0].chain_monitor,
4631 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4633 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4635 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4638 let mut nodes_0_read = &nodes_0_serialized[..];
4639 let (_, nodes_0_deserialized_tmp) =
4640 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4641 default_config: UserConfig::default(),
4643 fee_estimator: &fee_estimator,
4644 chain_monitor: nodes[0].chain_monitor,
4645 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4647 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4649 nodes_0_deserialized = nodes_0_deserialized_tmp;
4650 assert!(nodes_0_read.is_empty());
4652 { // Channel close should result in a commitment tx and an HTLC tx
4653 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4654 assert_eq!(txn.len(), 2);
4655 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4656 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4659 for monitor in node_0_monitors.drain(..) {
4660 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4661 check_added_monitors!(nodes[0], 1);
4663 nodes[0].node = &nodes_0_deserialized;
4665 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4666 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4667 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4668 //... and we can even still claim the payment!
4669 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4671 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4672 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4673 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4674 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4675 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4676 assert_eq!(msg_events.len(), 1);
4677 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4679 &ErrorAction::SendErrorMessage { ref msg } => {
4680 assert_eq!(msg.channel_id, channel_id);
4682 _ => panic!("Unexpected event!"),
4687 macro_rules! check_spendable_outputs {
4688 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4690 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4691 let mut txn = Vec::new();
4692 let mut all_outputs = Vec::new();
4693 let secp_ctx = Secp256k1::new();
4694 for event in events.drain(..) {
4696 Event::SpendableOutputs { mut outputs } => {
4697 for outp in outputs.drain(..) {
4698 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4699 all_outputs.push(outp);
4702 _ => panic!("Unexpected event"),
4705 if all_outputs.len() > 1 {
4706 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) {
4716 fn test_claim_sizeable_push_msat() {
4717 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4718 let chanmon_cfgs = create_chanmon_cfgs(2);
4719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4721 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4723 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4724 nodes[1].node.force_close_channel(&chan.2).unwrap();
4725 check_closed_broadcast!(nodes[1], false);
4726 check_added_monitors!(nodes[1], 1);
4727 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4728 assert_eq!(node_txn.len(), 1);
4729 check_spends!(node_txn[0], chan.3);
4730 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
4732 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4733 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4734 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4736 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4737 assert_eq!(spend_txn.len(), 1);
4738 check_spends!(spend_txn[0], node_txn[0]);
4742 fn test_claim_on_remote_sizeable_push_msat() {
4743 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4744 // to_remote output is encumbered by a P2WPKH
4745 let chanmon_cfgs = create_chanmon_cfgs(2);
4746 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4747 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4748 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4750 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4751 nodes[0].node.force_close_channel(&chan.2).unwrap();
4752 check_closed_broadcast!(nodes[0], false);
4753 check_added_monitors!(nodes[0], 1);
4755 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4756 assert_eq!(node_txn.len(), 1);
4757 check_spends!(node_txn[0], chan.3);
4758 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
4760 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4761 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4762 check_closed_broadcast!(nodes[1], false);
4763 check_added_monitors!(nodes[1], 1);
4764 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4766 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4767 assert_eq!(spend_txn.len(), 1);
4768 check_spends!(spend_txn[0], node_txn[0]);
4772 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4773 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4774 // to_remote output is encumbered by a P2WPKH
4776 let chanmon_cfgs = create_chanmon_cfgs(2);
4777 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4778 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4779 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4781 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4782 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4783 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4784 assert_eq!(revoked_local_txn[0].input.len(), 1);
4785 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4787 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4788 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4789 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4790 check_closed_broadcast!(nodes[1], false);
4791 check_added_monitors!(nodes[1], 1);
4793 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4794 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4795 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4796 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4798 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4799 assert_eq!(spend_txn.len(), 3);
4800 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4801 check_spends!(spend_txn[1], node_txn[0]);
4802 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4806 fn test_static_spendable_outputs_preimage_tx() {
4807 let chanmon_cfgs = create_chanmon_cfgs(2);
4808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4810 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4812 // Create some initial channels
4813 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4815 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4817 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4818 assert_eq!(commitment_tx[0].input.len(), 1);
4819 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4821 // Settle A's commitment tx on B's chain
4822 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4823 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4824 check_added_monitors!(nodes[1], 1);
4825 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4826 check_added_monitors!(nodes[1], 1);
4827 let events = nodes[1].node.get_and_clear_pending_msg_events();
4829 MessageSendEvent::UpdateHTLCs { .. } => {},
4830 _ => panic!("Unexpected event"),
4833 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4834 _ => panic!("Unexepected event"),
4837 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4838 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4839 assert_eq!(node_txn.len(), 3);
4840 check_spends!(node_txn[0], commitment_tx[0]);
4841 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4842 check_spends!(node_txn[1], chan_1.3);
4843 check_spends!(node_txn[2], node_txn[1]);
4845 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4846 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4847 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4849 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4850 assert_eq!(spend_txn.len(), 1);
4851 check_spends!(spend_txn[0], node_txn[0]);
4855 fn test_static_spendable_outputs_timeout_tx() {
4856 let chanmon_cfgs = create_chanmon_cfgs(2);
4857 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4858 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4859 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4861 // Create some initial channels
4862 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4864 // Rebalance the network a bit by relaying one payment through all the channels ...
4865 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4867 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4869 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4870 assert_eq!(commitment_tx[0].input.len(), 1);
4871 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4873 // Settle A's commitment tx on B' chain
4874 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4875 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4876 check_added_monitors!(nodes[1], 1);
4877 let events = nodes[1].node.get_and_clear_pending_msg_events();
4879 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4880 _ => panic!("Unexpected event"),
4883 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4884 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4885 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4886 check_spends!(node_txn[0], commitment_tx[0].clone());
4887 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4888 check_spends!(node_txn[1], chan_1.3.clone());
4889 check_spends!(node_txn[2], node_txn[1]);
4891 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4892 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4893 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4894 expect_payment_failed!(nodes[1], our_payment_hash, true);
4896 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4897 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4898 check_spends!(spend_txn[0], commitment_tx[0]);
4899 check_spends!(spend_txn[1], node_txn[0]);
4900 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4904 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4905 let chanmon_cfgs = create_chanmon_cfgs(2);
4906 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4907 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4908 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4910 // Create some initial channels
4911 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4913 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4914 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4915 assert_eq!(revoked_local_txn[0].input.len(), 1);
4916 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4918 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4920 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4921 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4922 check_closed_broadcast!(nodes[1], false);
4923 check_added_monitors!(nodes[1], 1);
4925 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4926 assert_eq!(node_txn.len(), 2);
4927 assert_eq!(node_txn[0].input.len(), 2);
4928 check_spends!(node_txn[0], revoked_local_txn[0]);
4930 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4931 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4932 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4934 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4935 assert_eq!(spend_txn.len(), 1);
4936 check_spends!(spend_txn[0], node_txn[0]);
4940 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4941 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4942 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4943 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4944 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4945 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4947 // Create some initial channels
4948 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4950 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4951 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4952 assert_eq!(revoked_local_txn[0].input.len(), 1);
4953 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4955 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4957 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4958 // A will generate HTLC-Timeout from revoked commitment tx
4959 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4960 check_closed_broadcast!(nodes[0], false);
4961 check_added_monitors!(nodes[0], 1);
4963 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4964 assert_eq!(revoked_htlc_txn.len(), 2);
4965 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4966 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4967 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4968 check_spends!(revoked_htlc_txn[1], chan_1.3);
4970 // B will generate justice tx from A's revoked commitment/HTLC tx
4971 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4972 check_closed_broadcast!(nodes[1], false);
4973 check_added_monitors!(nodes[1], 1);
4975 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4976 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4977 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4978 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4979 // transactions next...
4980 assert_eq!(node_txn[0].input.len(), 3);
4981 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4983 assert_eq!(node_txn[1].input.len(), 2);
4984 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4985 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4986 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4988 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4989 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4992 assert_eq!(node_txn[2].input.len(), 1);
4993 check_spends!(node_txn[2], chan_1.3);
4995 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4996 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
4997 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4999 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5000 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5001 assert_eq!(spend_txn.len(), 1);
5002 assert_eq!(spend_txn[0].input.len(), 1);
5003 check_spends!(spend_txn[0], node_txn[1]);
5007 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5008 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5009 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5010 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5011 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5012 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5014 // Create some initial channels
5015 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5017 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5018 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5019 assert_eq!(revoked_local_txn[0].input.len(), 1);
5020 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5022 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5023 assert_eq!(revoked_local_txn[0].output.len(), 2);
5025 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5027 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5028 // B will generate HTLC-Success from revoked commitment tx
5029 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5030 check_closed_broadcast!(nodes[1], false);
5031 check_added_monitors!(nodes[1], 1);
5032 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5034 assert_eq!(revoked_htlc_txn.len(), 2);
5035 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5036 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5037 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5039 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5040 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5041 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5043 // A will generate justice tx from B's revoked commitment/HTLC tx
5044 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5045 check_closed_broadcast!(nodes[0], false);
5046 check_added_monitors!(nodes[0], 1);
5048 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5049 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5051 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5052 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5053 // transactions next...
5054 assert_eq!(node_txn[0].input.len(), 2);
5055 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5056 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5057 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5059 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5060 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5063 assert_eq!(node_txn[1].input.len(), 1);
5064 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5066 check_spends!(node_txn[2], chan_1.3);
5068 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5069 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5070 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5072 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5073 // didn't try to generate any new transactions.
5075 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5076 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5077 assert_eq!(spend_txn.len(), 3);
5078 assert_eq!(spend_txn[0].input.len(), 1);
5079 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5080 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5081 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5082 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5086 fn test_onchain_to_onchain_claim() {
5087 // Test that in case of channel closure, we detect the state of output and claim HTLC
5088 // on downstream peer's remote commitment tx.
5089 // First, have C claim an HTLC against its own latest commitment transaction.
5090 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5092 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5095 let chanmon_cfgs = create_chanmon_cfgs(3);
5096 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5097 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5098 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5100 // Create some initial channels
5101 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5102 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5104 // Rebalance the network a bit by relaying one payment through all the channels ...
5105 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5106 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5108 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5109 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5110 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5111 check_spends!(commitment_tx[0], chan_2.3);
5112 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5113 check_added_monitors!(nodes[2], 1);
5114 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5115 assert!(updates.update_add_htlcs.is_empty());
5116 assert!(updates.update_fail_htlcs.is_empty());
5117 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5118 assert!(updates.update_fail_malformed_htlcs.is_empty());
5120 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5121 check_closed_broadcast!(nodes[2], false);
5122 check_added_monitors!(nodes[2], 1);
5124 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5125 assert_eq!(c_txn.len(), 3);
5126 assert_eq!(c_txn[0], c_txn[2]);
5127 assert_eq!(commitment_tx[0], c_txn[1]);
5128 check_spends!(c_txn[1], chan_2.3);
5129 check_spends!(c_txn[2], c_txn[1]);
5130 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5131 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5132 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5133 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5135 // 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
5136 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5138 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5139 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5140 assert_eq!(b_txn.len(), 3);
5141 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5142 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5143 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5144 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5145 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5146 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5147 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5148 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5149 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5152 check_added_monitors!(nodes[1], 1);
5153 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5154 check_added_monitors!(nodes[1], 1);
5155 match msg_events[0] {
5156 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5157 _ => panic!("Unexpected event"),
5159 match msg_events[1] {
5160 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, .. } } => {
5161 assert!(update_add_htlcs.is_empty());
5162 assert!(update_fail_htlcs.is_empty());
5163 assert_eq!(update_fulfill_htlcs.len(), 1);
5164 assert!(update_fail_malformed_htlcs.is_empty());
5165 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5167 _ => panic!("Unexpected event"),
5169 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5170 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5171 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5172 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5173 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5174 assert_eq!(b_txn.len(), 3);
5175 check_spends!(b_txn[1], chan_1.3);
5176 check_spends!(b_txn[2], b_txn[1]);
5177 check_spends!(b_txn[0], commitment_tx[0]);
5178 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5179 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5180 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5182 check_closed_broadcast!(nodes[1], false);
5183 check_added_monitors!(nodes[1], 1);
5187 fn test_duplicate_payment_hash_one_failure_one_success() {
5188 // Topology : A --> B --> C
5189 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5190 let chanmon_cfgs = create_chanmon_cfgs(3);
5191 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5192 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5193 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5195 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5196 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5198 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5199 *nodes[0].network_payment_count.borrow_mut() -= 1;
5200 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5202 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5203 assert_eq!(commitment_txn[0].input.len(), 1);
5204 check_spends!(commitment_txn[0], chan_2.3);
5206 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5207 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5208 check_closed_broadcast!(nodes[1], false);
5209 check_added_monitors!(nodes[1], 1);
5211 let htlc_timeout_tx;
5212 { // Extract one of the two HTLC-Timeout transaction
5213 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5214 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5215 assert_eq!(node_txn.len(), 5);
5216 check_spends!(node_txn[0], commitment_txn[0]);
5217 assert_eq!(node_txn[0].input.len(), 1);
5218 check_spends!(node_txn[1], commitment_txn[0]);
5219 assert_eq!(node_txn[1].input.len(), 1);
5220 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5221 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5222 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5223 check_spends!(node_txn[2], chan_2.3);
5224 check_spends!(node_txn[3], node_txn[2]);
5225 check_spends!(node_txn[4], node_txn[2]);
5226 htlc_timeout_tx = node_txn[1].clone();
5229 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5230 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5231 check_added_monitors!(nodes[2], 3);
5232 let events = nodes[2].node.get_and_clear_pending_msg_events();
5234 MessageSendEvent::UpdateHTLCs { .. } => {},
5235 _ => panic!("Unexpected event"),
5238 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5239 _ => panic!("Unexepected event"),
5241 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5242 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)
5243 check_spends!(htlc_success_txn[2], chan_2.3);
5244 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5245 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5246 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5247 assert_eq!(htlc_success_txn[0].input.len(), 1);
5248 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5249 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5250 assert_eq!(htlc_success_txn[1].input.len(), 1);
5251 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5252 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5253 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5254 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5256 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5257 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5258 expect_pending_htlcs_forwardable!(nodes[1]);
5259 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5260 assert!(htlc_updates.update_add_htlcs.is_empty());
5261 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5262 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5263 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5264 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5265 check_added_monitors!(nodes[1], 1);
5267 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5268 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5270 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5271 let events = nodes[0].node.get_and_clear_pending_msg_events();
5272 assert_eq!(events.len(), 1);
5274 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5276 _ => { panic!("Unexpected event"); }
5279 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5281 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5282 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5283 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5284 assert!(updates.update_add_htlcs.is_empty());
5285 assert!(updates.update_fail_htlcs.is_empty());
5286 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5287 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5288 assert!(updates.update_fail_malformed_htlcs.is_empty());
5289 check_added_monitors!(nodes[1], 1);
5291 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5292 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5294 let events = nodes[0].node.get_and_clear_pending_events();
5296 Event::PaymentSent { ref payment_preimage } => {
5297 assert_eq!(*payment_preimage, our_payment_preimage);
5299 _ => panic!("Unexpected event"),
5304 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5305 let chanmon_cfgs = create_chanmon_cfgs(2);
5306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5308 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5310 // Create some initial channels
5311 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5313 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5314 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5315 assert_eq!(local_txn.len(), 1);
5316 assert_eq!(local_txn[0].input.len(), 1);
5317 check_spends!(local_txn[0], chan_1.3);
5319 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5320 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5321 check_added_monitors!(nodes[1], 1);
5322 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5323 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5324 check_added_monitors!(nodes[1], 1);
5325 let events = nodes[1].node.get_and_clear_pending_msg_events();
5327 MessageSendEvent::UpdateHTLCs { .. } => {},
5328 _ => panic!("Unexpected event"),
5331 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5332 _ => panic!("Unexepected event"),
5335 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5336 assert_eq!(node_txn.len(), 3);
5337 assert_eq!(node_txn[0], node_txn[2]);
5338 assert_eq!(node_txn[1], local_txn[0]);
5339 assert_eq!(node_txn[0].input.len(), 1);
5340 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5341 check_spends!(node_txn[0], local_txn[0]);
5342 vec![node_txn[0].clone()]
5345 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5346 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5347 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5349 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5350 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5351 assert_eq!(spend_txn.len(), 1);
5352 check_spends!(spend_txn[0], node_txn[0]);
5355 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5356 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5357 // unrevoked commitment transaction.
5358 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5359 // a remote RAA before they could be failed backwards (and combinations thereof).
5360 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5361 // use the same payment hashes.
5362 // Thus, we use a six-node network:
5367 // And test where C fails back to A/B when D announces its latest commitment transaction
5368 let chanmon_cfgs = create_chanmon_cfgs(6);
5369 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5370 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5371 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5372 let logger = test_utils::TestLogger::new();
5374 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5375 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5376 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5377 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5378 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5380 // Rebalance and check output sanity...
5381 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5382 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5383 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5385 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5387 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
5389 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
5390 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5391 let our_node_id = &nodes[1].node.get_our_node_id();
5392 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5394 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
5396 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
5398 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5400 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5401 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5403 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5405 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5408 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5410 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5411 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
5414 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
5416 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5417 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5419 // Double-check that six of the new HTLC were added
5420 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5421 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5422 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5423 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5425 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5426 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5427 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5428 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5429 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5430 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5431 check_added_monitors!(nodes[4], 0);
5432 expect_pending_htlcs_forwardable!(nodes[4]);
5433 check_added_monitors!(nodes[4], 1);
5435 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5436 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5437 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5438 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5439 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5440 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5442 // Fail 3rd below-dust and 7th above-dust HTLCs
5443 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5444 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5445 check_added_monitors!(nodes[5], 0);
5446 expect_pending_htlcs_forwardable!(nodes[5]);
5447 check_added_monitors!(nodes[5], 1);
5449 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5450 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5451 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5452 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5454 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5456 expect_pending_htlcs_forwardable!(nodes[3]);
5457 check_added_monitors!(nodes[3], 1);
5458 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5459 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5460 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5461 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5462 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5463 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5464 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5465 if deliver_last_raa {
5466 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5468 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5471 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5472 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5473 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5474 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5476 // We now broadcast the latest commitment transaction, which *should* result in failures for
5477 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5478 // the non-broadcast above-dust HTLCs.
5480 // Alternatively, we may broadcast the previous commitment transaction, which should only
5481 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5482 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5484 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5485 if announce_latest {
5486 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5488 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5490 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5491 check_closed_broadcast!(nodes[2], false);
5492 expect_pending_htlcs_forwardable!(nodes[2]);
5493 check_added_monitors!(nodes[2], 3);
5495 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5496 assert_eq!(cs_msgs.len(), 2);
5497 let mut a_done = false;
5498 for msg in cs_msgs {
5500 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5501 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5502 // should be failed-backwards here.
5503 let target = if *node_id == nodes[0].node.get_our_node_id() {
5504 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5505 for htlc in &updates.update_fail_htlcs {
5506 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 });
5508 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5513 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5514 for htlc in &updates.update_fail_htlcs {
5515 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5517 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5518 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5521 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5522 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5523 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5524 if announce_latest {
5525 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5526 if *node_id == nodes[0].node.get_our_node_id() {
5527 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5530 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5532 _ => panic!("Unexpected event"),
5536 let as_events = nodes[0].node.get_and_clear_pending_events();
5537 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5538 let mut as_failds = HashSet::new();
5539 for event in as_events.iter() {
5540 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5541 assert!(as_failds.insert(*payment_hash));
5542 if *payment_hash != payment_hash_2 {
5543 assert_eq!(*rejected_by_dest, deliver_last_raa);
5545 assert!(!rejected_by_dest);
5547 } else { panic!("Unexpected event"); }
5549 assert!(as_failds.contains(&payment_hash_1));
5550 assert!(as_failds.contains(&payment_hash_2));
5551 if announce_latest {
5552 assert!(as_failds.contains(&payment_hash_3));
5553 assert!(as_failds.contains(&payment_hash_5));
5555 assert!(as_failds.contains(&payment_hash_6));
5557 let bs_events = nodes[1].node.get_and_clear_pending_events();
5558 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5559 let mut bs_failds = HashSet::new();
5560 for event in bs_events.iter() {
5561 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5562 assert!(bs_failds.insert(*payment_hash));
5563 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5564 assert_eq!(*rejected_by_dest, deliver_last_raa);
5566 assert!(!rejected_by_dest);
5568 } else { panic!("Unexpected event"); }
5570 assert!(bs_failds.contains(&payment_hash_1));
5571 assert!(bs_failds.contains(&payment_hash_2));
5572 if announce_latest {
5573 assert!(bs_failds.contains(&payment_hash_4));
5575 assert!(bs_failds.contains(&payment_hash_5));
5577 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5578 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5579 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5580 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5581 // PaymentFailureNetworkUpdates.
5582 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5583 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5584 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5585 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5586 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5588 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5589 _ => panic!("Unexpected event"),
5595 fn test_fail_backwards_latest_remote_announce_a() {
5596 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5600 fn test_fail_backwards_latest_remote_announce_b() {
5601 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5605 fn test_fail_backwards_previous_remote_announce() {
5606 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5607 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5608 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5612 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5613 let chanmon_cfgs = create_chanmon_cfgs(2);
5614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5616 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5618 // Create some initial channels
5619 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5621 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5622 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5623 assert_eq!(local_txn[0].input.len(), 1);
5624 check_spends!(local_txn[0], chan_1.3);
5626 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5627 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5628 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5629 check_closed_broadcast!(nodes[0], false);
5630 check_added_monitors!(nodes[0], 1);
5632 let htlc_timeout = {
5633 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5634 assert_eq!(node_txn[0].input.len(), 1);
5635 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5636 check_spends!(node_txn[0], local_txn[0]);
5640 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5641 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5642 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5643 expect_payment_failed!(nodes[0], our_payment_hash, true);
5645 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5646 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5647 assert_eq!(spend_txn.len(), 3);
5648 check_spends!(spend_txn[0], local_txn[0]);
5649 check_spends!(spend_txn[1], htlc_timeout);
5650 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5654 fn test_key_derivation_params() {
5655 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5656 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5657 // let us re-derive the channel key set to then derive a delayed_payment_key.
5659 let chanmon_cfgs = create_chanmon_cfgs(3);
5661 // We manually create the node configuration to backup the seed.
5662 let seed = [42; 32];
5663 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5664 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);
5665 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 };
5666 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5667 node_cfgs.remove(0);
5668 node_cfgs.insert(0, node);
5670 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5671 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5673 // Create some initial channels
5674 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5676 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5677 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5678 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5680 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5681 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5682 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5683 assert_eq!(local_txn_1[0].input.len(), 1);
5684 check_spends!(local_txn_1[0], chan_1.3);
5686 // We check funding pubkey are unique
5687 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]));
5688 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]));
5689 if from_0_funding_key_0 == from_1_funding_key_0
5690 || from_0_funding_key_0 == from_1_funding_key_1
5691 || from_0_funding_key_1 == from_1_funding_key_0
5692 || from_0_funding_key_1 == from_1_funding_key_1 {
5693 panic!("Funding pubkeys aren't unique");
5696 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5697 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5698 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5699 check_closed_broadcast!(nodes[0], false);
5700 check_added_monitors!(nodes[0], 1);
5702 let htlc_timeout = {
5703 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5704 assert_eq!(node_txn[0].input.len(), 1);
5705 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5706 check_spends!(node_txn[0], local_txn_1[0]);
5710 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5711 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5712 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5713 expect_payment_failed!(nodes[0], our_payment_hash, true);
5715 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5716 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5717 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5718 assert_eq!(spend_txn.len(), 3);
5719 check_spends!(spend_txn[0], local_txn_1[0]);
5720 check_spends!(spend_txn[1], htlc_timeout);
5721 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5725 fn test_static_output_closing_tx() {
5726 let chanmon_cfgs = create_chanmon_cfgs(2);
5727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5731 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5733 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5734 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5736 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5737 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5738 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5740 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5741 assert_eq!(spend_txn.len(), 1);
5742 check_spends!(spend_txn[0], closing_tx);
5744 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5745 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5747 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5748 assert_eq!(spend_txn.len(), 1);
5749 check_spends!(spend_txn[0], closing_tx);
5752 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5753 let chanmon_cfgs = create_chanmon_cfgs(2);
5754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5756 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5757 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5759 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5761 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5762 // present in B's local commitment transaction, but none of A's commitment transactions.
5763 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5764 check_added_monitors!(nodes[1], 1);
5766 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5767 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5768 let events = nodes[0].node.get_and_clear_pending_events();
5769 assert_eq!(events.len(), 1);
5771 Event::PaymentSent { payment_preimage } => {
5772 assert_eq!(payment_preimage, our_payment_preimage);
5774 _ => panic!("Unexpected event"),
5777 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5778 check_added_monitors!(nodes[0], 1);
5779 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5780 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5781 check_added_monitors!(nodes[1], 1);
5783 let mut block = Block {
5784 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5787 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5788 connect_block(&nodes[1], &block, i);
5789 block.header.prev_blockhash = block.block_hash();
5791 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5792 check_closed_broadcast!(nodes[1], false);
5793 check_added_monitors!(nodes[1], 1);
5796 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5797 let chanmon_cfgs = create_chanmon_cfgs(2);
5798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5800 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5801 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5802 let logger = test_utils::TestLogger::new();
5804 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5805 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5806 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, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5807 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5808 check_added_monitors!(nodes[0], 1);
5810 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5812 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5813 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5814 // to "time out" the HTLC.
5816 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5818 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5819 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5820 header.prev_blockhash = header.block_hash();
5822 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5823 check_closed_broadcast!(nodes[0], false);
5824 check_added_monitors!(nodes[0], 1);
5827 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5828 let chanmon_cfgs = create_chanmon_cfgs(3);
5829 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5830 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5831 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5832 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5834 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5835 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5836 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5837 // actually revoked.
5838 let htlc_value = if use_dust { 50000 } else { 3000000 };
5839 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5840 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5841 expect_pending_htlcs_forwardable!(nodes[1]);
5842 check_added_monitors!(nodes[1], 1);
5844 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5845 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5846 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5847 check_added_monitors!(nodes[0], 1);
5848 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5849 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5850 check_added_monitors!(nodes[1], 1);
5851 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5852 check_added_monitors!(nodes[1], 1);
5853 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5855 if check_revoke_no_close {
5856 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5857 check_added_monitors!(nodes[0], 1);
5860 let mut block = Block {
5861 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5864 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5865 connect_block(&nodes[0], &block, i);
5866 block.header.prev_blockhash = block.block_hash();
5868 if !check_revoke_no_close {
5869 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5870 check_closed_broadcast!(nodes[0], false);
5871 check_added_monitors!(nodes[0], 1);
5873 expect_payment_failed!(nodes[0], our_payment_hash, true);
5877 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5878 // There are only a few cases to test here:
5879 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5880 // broadcastable commitment transactions result in channel closure,
5881 // * its included in an unrevoked-but-previous remote commitment transaction,
5882 // * its included in the latest remote or local commitment transactions.
5883 // We test each of the three possible commitment transactions individually and use both dust and
5885 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5886 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5887 // tested for at least one of the cases in other tests.
5889 fn htlc_claim_single_commitment_only_a() {
5890 do_htlc_claim_local_commitment_only(true);
5891 do_htlc_claim_local_commitment_only(false);
5893 do_htlc_claim_current_remote_commitment_only(true);
5894 do_htlc_claim_current_remote_commitment_only(false);
5898 fn htlc_claim_single_commitment_only_b() {
5899 do_htlc_claim_previous_remote_commitment_only(true, false);
5900 do_htlc_claim_previous_remote_commitment_only(false, false);
5901 do_htlc_claim_previous_remote_commitment_only(true, true);
5902 do_htlc_claim_previous_remote_commitment_only(false, true);
5907 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5908 let chanmon_cfgs = create_chanmon_cfgs(2);
5909 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5910 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5911 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5912 //Force duplicate channel ids
5913 for node in nodes.iter() {
5914 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5917 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5918 let channel_value_satoshis=10000;
5919 let push_msat=10001;
5920 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5921 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5922 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5924 //Create a second channel with a channel_id collision
5925 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5929 fn bolt2_open_channel_sending_node_checks_part2() {
5930 let chanmon_cfgs = create_chanmon_cfgs(2);
5931 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5932 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5933 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5935 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5936 let channel_value_satoshis=2^24;
5937 let push_msat=10001;
5938 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5940 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5941 let channel_value_satoshis=10000;
5942 // Test when push_msat is equal to 1000 * funding_satoshis.
5943 let push_msat=1000*channel_value_satoshis+1;
5944 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5946 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5947 let channel_value_satoshis=10000;
5948 let push_msat=10001;
5949 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
5950 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5951 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5953 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5954 // 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
5955 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5957 // 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.
5958 assert!(BREAKDOWN_TIMEOUT>0);
5959 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5961 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5962 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5963 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5965 // 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.
5966 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5967 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5968 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5969 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5970 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5973 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5974 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5975 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5976 // is no longer affordable once it's freed.
5978 fn test_fail_holding_cell_htlc_upon_free() {
5979 let chanmon_cfgs = create_chanmon_cfgs(2);
5980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5983 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5984 let logger = test_utils::TestLogger::new();
5986 // First nodes[0] generates an update_fee, setting the channel's
5987 // pending_update_fee.
5988 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5989 check_added_monitors!(nodes[0], 1);
5991 let events = nodes[0].node.get_and_clear_pending_msg_events();
5992 assert_eq!(events.len(), 1);
5993 let (update_msg, commitment_signed) = match events[0] {
5994 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5995 (update_fee.as_ref(), commitment_signed)
5997 _ => panic!("Unexpected event"),
6000 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6002 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6003 let channel_reserve = chan_stat.channel_reserve_msat;
6004 let feerate = get_feerate!(nodes[0], chan.2);
6006 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6007 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6008 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6009 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6010 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, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6012 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6013 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6014 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6015 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6017 // Flush the pending fee update.
6018 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6019 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6020 check_added_monitors!(nodes[1], 1);
6021 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6022 check_added_monitors!(nodes[0], 1);
6024 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6025 // HTLC, but now that the fee has been raised the payment will now fail, causing
6026 // us to surface its failure to the user.
6027 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6028 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6029 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6030 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);
6031 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6033 // Check that the payment failed to be sent out.
6034 let events = nodes[0].node.get_and_clear_pending_events();
6035 assert_eq!(events.len(), 1);
6037 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6038 assert_eq!(our_payment_hash.clone(), *payment_hash);
6039 assert_eq!(*rejected_by_dest, false);
6040 assert_eq!(*error_code, None);
6041 assert_eq!(*error_data, None);
6043 _ => panic!("Unexpected event"),
6047 // Test that if multiple HTLCs are released from the holding cell and one is
6048 // valid but the other is no longer valid upon release, the valid HTLC can be
6049 // successfully completed while the other one fails as expected.
6051 fn test_free_and_fail_holding_cell_htlcs() {
6052 let chanmon_cfgs = create_chanmon_cfgs(2);
6053 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6054 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6055 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6056 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6057 let logger = test_utils::TestLogger::new();
6059 // First nodes[0] generates an update_fee, setting the channel's
6060 // pending_update_fee.
6061 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6062 check_added_monitors!(nodes[0], 1);
6064 let events = nodes[0].node.get_and_clear_pending_msg_events();
6065 assert_eq!(events.len(), 1);
6066 let (update_msg, commitment_signed) = match events[0] {
6067 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6068 (update_fee.as_ref(), commitment_signed)
6070 _ => panic!("Unexpected event"),
6073 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6075 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6076 let channel_reserve = chan_stat.channel_reserve_msat;
6077 let feerate = get_feerate!(nodes[0], chan.2);
6079 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6080 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6082 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6083 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6084 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6085 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, &[], amt_1, TEST_FINAL_CLTV, &logger).unwrap();
6086 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, &[], amt_2, TEST_FINAL_CLTV, &logger).unwrap();
6088 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6089 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6090 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6091 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6092 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6093 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6094 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6096 // Flush the pending fee update.
6097 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6098 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6099 check_added_monitors!(nodes[1], 1);
6100 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6101 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6102 check_added_monitors!(nodes[0], 2);
6104 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6105 // but now that the fee has been raised the second payment will now fail, causing us
6106 // to surface its failure to the user. The first payment should succeed.
6107 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6108 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6109 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6110 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);
6111 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6113 // Check that the second payment failed to be sent out.
6114 let events = nodes[0].node.get_and_clear_pending_events();
6115 assert_eq!(events.len(), 1);
6117 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6118 assert_eq!(payment_hash_2.clone(), *payment_hash);
6119 assert_eq!(*rejected_by_dest, false);
6120 assert_eq!(*error_code, None);
6121 assert_eq!(*error_data, None);
6123 _ => panic!("Unexpected event"),
6126 // Complete the first payment and the RAA from the fee update.
6127 let (payment_event, send_raa_event) = {
6128 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6129 assert_eq!(msgs.len(), 2);
6130 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6132 let raa = match send_raa_event {
6133 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6134 _ => panic!("Unexpected event"),
6136 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6137 check_added_monitors!(nodes[1], 1);
6138 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6139 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6140 let events = nodes[1].node.get_and_clear_pending_events();
6141 assert_eq!(events.len(), 1);
6143 Event::PendingHTLCsForwardable { .. } => {},
6144 _ => panic!("Unexpected event"),
6146 nodes[1].node.process_pending_htlc_forwards();
6147 let events = nodes[1].node.get_and_clear_pending_events();
6148 assert_eq!(events.len(), 1);
6150 Event::PaymentReceived { .. } => {},
6151 _ => panic!("Unexpected event"),
6153 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6154 check_added_monitors!(nodes[1], 1);
6155 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6156 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6157 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6158 let events = nodes[0].node.get_and_clear_pending_events();
6159 assert_eq!(events.len(), 1);
6161 Event::PaymentSent { ref payment_preimage } => {
6162 assert_eq!(*payment_preimage, payment_preimage_1);
6164 _ => panic!("Unexpected event"),
6168 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6169 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6170 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6173 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6174 let chanmon_cfgs = create_chanmon_cfgs(3);
6175 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6176 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6177 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6178 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6179 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6180 let logger = test_utils::TestLogger::new();
6182 // First nodes[1] generates an update_fee, setting the channel's
6183 // pending_update_fee.
6184 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6185 check_added_monitors!(nodes[1], 1);
6187 let events = nodes[1].node.get_and_clear_pending_msg_events();
6188 assert_eq!(events.len(), 1);
6189 let (update_msg, commitment_signed) = match events[0] {
6190 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6191 (update_fee.as_ref(), commitment_signed)
6193 _ => panic!("Unexpected event"),
6196 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6198 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6199 let channel_reserve = chan_stat.channel_reserve_msat;
6200 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6202 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6204 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6205 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6206 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6207 let payment_event = {
6208 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6209 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, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6210 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6211 check_added_monitors!(nodes[0], 1);
6213 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6214 assert_eq!(events.len(), 1);
6216 SendEvent::from_event(events.remove(0))
6218 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6219 check_added_monitors!(nodes[1], 0);
6220 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6221 expect_pending_htlcs_forwardable!(nodes[1]);
6223 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6224 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6226 // Flush the pending fee update.
6227 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6228 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6229 check_added_monitors!(nodes[2], 1);
6230 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6231 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6232 check_added_monitors!(nodes[1], 2);
6234 // A final RAA message is generated to finalize the fee update.
6235 let events = nodes[1].node.get_and_clear_pending_msg_events();
6236 assert_eq!(events.len(), 1);
6238 let raa_msg = match &events[0] {
6239 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6242 _ => panic!("Unexpected event"),
6245 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6246 check_added_monitors!(nodes[2], 1);
6247 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6249 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6250 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6251 assert_eq!(process_htlc_forwards_event.len(), 1);
6252 match &process_htlc_forwards_event[0] {
6253 &Event::PendingHTLCsForwardable { .. } => {},
6254 _ => panic!("Unexpected event"),
6257 // In response, we call ChannelManager's process_pending_htlc_forwards
6258 nodes[1].node.process_pending_htlc_forwards();
6259 check_added_monitors!(nodes[1], 1);
6261 // This causes the HTLC to be failed backwards.
6262 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6263 assert_eq!(fail_event.len(), 1);
6264 let (fail_msg, commitment_signed) = match &fail_event[0] {
6265 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6266 assert_eq!(updates.update_add_htlcs.len(), 0);
6267 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6268 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6269 assert_eq!(updates.update_fail_htlcs.len(), 1);
6270 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6272 _ => panic!("Unexpected event"),
6275 // Pass the failure messages back to nodes[0].
6276 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6277 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6279 // Complete the HTLC failure+removal process.
6280 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6281 check_added_monitors!(nodes[0], 1);
6282 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6283 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6284 check_added_monitors!(nodes[1], 2);
6285 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6286 assert_eq!(final_raa_event.len(), 1);
6287 let raa = match &final_raa_event[0] {
6288 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6289 _ => panic!("Unexpected event"),
6291 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6292 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6293 assert_eq!(fail_msg_event.len(), 1);
6294 match &fail_msg_event[0] {
6295 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6296 _ => panic!("Unexpected event"),
6298 let failure_event = nodes[0].node.get_and_clear_pending_events();
6299 assert_eq!(failure_event.len(), 1);
6300 match &failure_event[0] {
6301 &Event::PaymentFailed { rejected_by_dest, .. } => {
6302 assert!(!rejected_by_dest);
6304 _ => panic!("Unexpected event"),
6306 check_added_monitors!(nodes[0], 1);
6309 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6310 // 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.
6311 //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.
6314 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6315 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6316 let chanmon_cfgs = create_chanmon_cfgs(2);
6317 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6318 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6319 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6320 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]);
6323 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6324 let logger = test_utils::TestLogger::new();
6325 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6326 route.paths[0][0].fee_msat = 100;
6328 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6329 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6330 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6331 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6335 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6336 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6337 let chanmon_cfgs = create_chanmon_cfgs(2);
6338 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6339 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6340 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6341 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6342 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6344 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6345 let logger = test_utils::TestLogger::new();
6346 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6347 route.paths[0][0].fee_msat = 0;
6348 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6349 assert_eq!(err, "Cannot send 0-msat HTLC"));
6351 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6352 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6356 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6357 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6358 let chanmon_cfgs = create_chanmon_cfgs(2);
6359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6361 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6362 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6364 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6365 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6366 let logger = test_utils::TestLogger::new();
6367 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6368 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6369 check_added_monitors!(nodes[0], 1);
6370 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6371 updates.update_add_htlcs[0].amount_msat = 0;
6373 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6374 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6375 check_closed_broadcast!(nodes[1], true).unwrap();
6376 check_added_monitors!(nodes[1], 1);
6380 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6381 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6382 //It is enforced when constructing a route.
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, 100000, 0, InitFeatures::known(), InitFeatures::known());
6388 let logger = test_utils::TestLogger::new();
6390 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6392 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6393 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, &logger).unwrap();
6394 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6395 assert_eq!(err, &"Channel CLTV overflowed?"));
6399 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6400 //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.
6401 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6402 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6403 let chanmon_cfgs = create_chanmon_cfgs(2);
6404 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6405 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6406 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6407 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6408 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6410 let logger = test_utils::TestLogger::new();
6411 for i in 0..max_accepted_htlcs {
6412 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6413 let payment_event = {
6414 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6415 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6416 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6417 check_added_monitors!(nodes[0], 1);
6419 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6420 assert_eq!(events.len(), 1);
6421 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6422 assert_eq!(htlcs[0].htlc_id, i);
6426 SendEvent::from_event(events.remove(0))
6428 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6429 check_added_monitors!(nodes[1], 0);
6430 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6432 expect_pending_htlcs_forwardable!(nodes[1]);
6433 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6435 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6436 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6437 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6438 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6439 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6441 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6442 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6446 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6447 //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.
6448 let chanmon_cfgs = create_chanmon_cfgs(2);
6449 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6450 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6451 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6452 let channel_value = 100000;
6453 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6454 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6456 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6458 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6459 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6460 let logger = test_utils::TestLogger::new();
6461 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, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6462 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6463 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)));
6465 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6466 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);
6468 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6471 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6473 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6474 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6475 let chanmon_cfgs = create_chanmon_cfgs(2);
6476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6478 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6479 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6480 let htlc_minimum_msat: u64;
6482 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6483 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6484 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6487 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6488 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6489 let logger = test_utils::TestLogger::new();
6490 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, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6491 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6492 check_added_monitors!(nodes[0], 1);
6493 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6494 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6495 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6496 assert!(nodes[1].node.list_channels().is_empty());
6497 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6498 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()));
6499 check_added_monitors!(nodes[1], 1);
6503 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6504 //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
6505 let chanmon_cfgs = create_chanmon_cfgs(2);
6506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6508 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6509 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6510 let logger = test_utils::TestLogger::new();
6512 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6513 let channel_reserve = chan_stat.channel_reserve_msat;
6514 let feerate = get_feerate!(nodes[0], chan.2);
6515 // The 2* and +1 are for the fee spike reserve.
6516 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6518 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6519 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6520 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6521 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, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6522 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6523 check_added_monitors!(nodes[0], 1);
6524 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6526 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6527 // at this time channel-initiatee receivers are not required to enforce that senders
6528 // respect the fee_spike_reserve.
6529 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6530 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6532 assert!(nodes[1].node.list_channels().is_empty());
6533 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6534 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6535 check_added_monitors!(nodes[1], 1);
6539 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6540 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6541 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6542 let chanmon_cfgs = create_chanmon_cfgs(2);
6543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6545 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6546 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6547 let logger = test_utils::TestLogger::new();
6549 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6550 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6552 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6553 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, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6555 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6556 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6557 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6558 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6560 let mut msg = msgs::UpdateAddHTLC {
6564 payment_hash: our_payment_hash,
6565 cltv_expiry: htlc_cltv,
6566 onion_routing_packet: onion_packet.clone(),
6569 for i in 0..super::channel::OUR_MAX_HTLCS {
6570 msg.htlc_id = i as u64;
6571 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6573 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6574 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6576 assert!(nodes[1].node.list_channels().is_empty());
6577 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6578 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6579 check_added_monitors!(nodes[1], 1);
6583 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6584 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6585 let chanmon_cfgs = create_chanmon_cfgs(2);
6586 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6587 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6588 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6589 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6590 let logger = test_utils::TestLogger::new();
6592 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6593 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6594 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6595 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6596 check_added_monitors!(nodes[0], 1);
6597 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6598 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6599 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6601 assert!(nodes[1].node.list_channels().is_empty());
6602 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6603 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6604 check_added_monitors!(nodes[1], 1);
6608 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6609 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6610 let chanmon_cfgs = create_chanmon_cfgs(2);
6611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6613 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6614 let logger = test_utils::TestLogger::new();
6616 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6617 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6618 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6619 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6620 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6621 check_added_monitors!(nodes[0], 1);
6622 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6623 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6624 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6626 assert!(nodes[1].node.list_channels().is_empty());
6627 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6628 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6629 check_added_monitors!(nodes[1], 1);
6633 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6634 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6635 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6636 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6637 let chanmon_cfgs = create_chanmon_cfgs(2);
6638 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6639 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6640 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6641 let logger = test_utils::TestLogger::new();
6643 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6644 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6645 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6646 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6647 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6648 check_added_monitors!(nodes[0], 1);
6649 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6650 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6652 //Disconnect and Reconnect
6653 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6654 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6655 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6656 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6657 assert_eq!(reestablish_1.len(), 1);
6658 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6659 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6660 assert_eq!(reestablish_2.len(), 1);
6661 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6662 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6663 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6664 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6667 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6668 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6669 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6670 check_added_monitors!(nodes[1], 1);
6671 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6673 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6675 assert!(nodes[1].node.list_channels().is_empty());
6676 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6677 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6678 check_added_monitors!(nodes[1], 1);
6682 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6683 //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.
6685 let chanmon_cfgs = create_chanmon_cfgs(2);
6686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6688 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6689 let logger = test_utils::TestLogger::new();
6690 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6691 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6692 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6693 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6694 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6696 check_added_monitors!(nodes[0], 1);
6697 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6698 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6700 let update_msg = msgs::UpdateFulfillHTLC{
6703 payment_preimage: our_payment_preimage,
6706 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6708 assert!(nodes[0].node.list_channels().is_empty());
6709 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6710 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()));
6711 check_added_monitors!(nodes[0], 1);
6715 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6716 //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.
6718 let chanmon_cfgs = create_chanmon_cfgs(2);
6719 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6720 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6721 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6722 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6723 let logger = test_utils::TestLogger::new();
6725 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6726 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6727 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6728 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6729 check_added_monitors!(nodes[0], 1);
6730 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6731 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6733 let update_msg = msgs::UpdateFailHTLC{
6736 reason: msgs::OnionErrorPacket { data: Vec::new()},
6739 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6741 assert!(nodes[0].node.list_channels().is_empty());
6742 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6743 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()));
6744 check_added_monitors!(nodes[0], 1);
6748 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6749 //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.
6751 let chanmon_cfgs = create_chanmon_cfgs(2);
6752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6755 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6756 let logger = test_utils::TestLogger::new();
6758 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6759 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6760 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6761 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6762 check_added_monitors!(nodes[0], 1);
6763 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6764 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6766 let update_msg = msgs::UpdateFailMalformedHTLC{
6769 sha256_of_onion: [1; 32],
6770 failure_code: 0x8000,
6773 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6775 assert!(nodes[0].node.list_channels().is_empty());
6776 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6777 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()));
6778 check_added_monitors!(nodes[0], 1);
6782 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6783 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6785 let chanmon_cfgs = create_chanmon_cfgs(2);
6786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6789 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6791 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6793 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6794 check_added_monitors!(nodes[1], 1);
6796 let events = nodes[1].node.get_and_clear_pending_msg_events();
6797 assert_eq!(events.len(), 1);
6798 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6800 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6801 assert!(update_add_htlcs.is_empty());
6802 assert_eq!(update_fulfill_htlcs.len(), 1);
6803 assert!(update_fail_htlcs.is_empty());
6804 assert!(update_fail_malformed_htlcs.is_empty());
6805 assert!(update_fee.is_none());
6806 update_fulfill_htlcs[0].clone()
6808 _ => panic!("Unexpected event"),
6812 update_fulfill_msg.htlc_id = 1;
6814 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6816 assert!(nodes[0].node.list_channels().is_empty());
6817 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6818 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6819 check_added_monitors!(nodes[0], 1);
6823 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6824 //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.
6826 let chanmon_cfgs = create_chanmon_cfgs(2);
6827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6829 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6830 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6832 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6834 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6835 check_added_monitors!(nodes[1], 1);
6837 let events = nodes[1].node.get_and_clear_pending_msg_events();
6838 assert_eq!(events.len(), 1);
6839 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6841 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, .. } } => {
6842 assert!(update_add_htlcs.is_empty());
6843 assert_eq!(update_fulfill_htlcs.len(), 1);
6844 assert!(update_fail_htlcs.is_empty());
6845 assert!(update_fail_malformed_htlcs.is_empty());
6846 assert!(update_fee.is_none());
6847 update_fulfill_htlcs[0].clone()
6849 _ => panic!("Unexpected event"),
6853 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6855 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6857 assert!(nodes[0].node.list_channels().is_empty());
6858 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6859 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6860 check_added_monitors!(nodes[0], 1);
6864 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6865 //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.
6867 let chanmon_cfgs = create_chanmon_cfgs(2);
6868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6870 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6871 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6872 let logger = test_utils::TestLogger::new();
6874 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6875 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6876 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, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6877 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6878 check_added_monitors!(nodes[0], 1);
6880 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6881 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6883 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6884 check_added_monitors!(nodes[1], 0);
6885 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6887 let events = nodes[1].node.get_and_clear_pending_msg_events();
6889 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6891 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, .. } } => {
6892 assert!(update_add_htlcs.is_empty());
6893 assert!(update_fulfill_htlcs.is_empty());
6894 assert!(update_fail_htlcs.is_empty());
6895 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6896 assert!(update_fee.is_none());
6897 update_fail_malformed_htlcs[0].clone()
6899 _ => panic!("Unexpected event"),
6902 update_msg.failure_code &= !0x8000;
6903 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6905 assert!(nodes[0].node.list_channels().is_empty());
6906 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6907 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6908 check_added_monitors!(nodes[0], 1);
6912 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6913 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6914 // * 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.
6916 let chanmon_cfgs = create_chanmon_cfgs(3);
6917 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6918 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6919 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6920 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6921 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6922 let logger = test_utils::TestLogger::new();
6924 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6927 let mut payment_event = {
6928 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6929 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, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6930 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6931 check_added_monitors!(nodes[0], 1);
6932 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6933 assert_eq!(events.len(), 1);
6934 SendEvent::from_event(events.remove(0))
6936 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6937 check_added_monitors!(nodes[1], 0);
6938 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6939 expect_pending_htlcs_forwardable!(nodes[1]);
6940 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6941 assert_eq!(events_2.len(), 1);
6942 check_added_monitors!(nodes[1], 1);
6943 payment_event = SendEvent::from_event(events_2.remove(0));
6944 assert_eq!(payment_event.msgs.len(), 1);
6947 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6948 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6949 check_added_monitors!(nodes[2], 0);
6950 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6952 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6953 assert_eq!(events_3.len(), 1);
6954 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6956 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 } } => {
6957 assert!(update_add_htlcs.is_empty());
6958 assert!(update_fulfill_htlcs.is_empty());
6959 assert!(update_fail_htlcs.is_empty());
6960 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6961 assert!(update_fee.is_none());
6962 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6964 _ => panic!("Unexpected event"),
6968 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6970 check_added_monitors!(nodes[1], 0);
6971 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6972 expect_pending_htlcs_forwardable!(nodes[1]);
6973 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6974 assert_eq!(events_4.len(), 1);
6976 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6978 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, .. } } => {
6979 assert!(update_add_htlcs.is_empty());
6980 assert!(update_fulfill_htlcs.is_empty());
6981 assert_eq!(update_fail_htlcs.len(), 1);
6982 assert!(update_fail_malformed_htlcs.is_empty());
6983 assert!(update_fee.is_none());
6985 _ => panic!("Unexpected event"),
6988 check_added_monitors!(nodes[1], 1);
6991 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6992 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6993 // 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
6994 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6996 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6997 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6998 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6999 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7000 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7001 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7003 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7005 // We route 2 dust-HTLCs between A and B
7006 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7007 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7008 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7010 // Cache one local commitment tx as previous
7011 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7013 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7014 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7015 check_added_monitors!(nodes[1], 0);
7016 expect_pending_htlcs_forwardable!(nodes[1]);
7017 check_added_monitors!(nodes[1], 1);
7019 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7020 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7021 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7022 check_added_monitors!(nodes[0], 1);
7024 // Cache one local commitment tx as lastest
7025 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7027 let events = nodes[0].node.get_and_clear_pending_msg_events();
7029 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7030 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7032 _ => panic!("Unexpected event"),
7035 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7036 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7038 _ => panic!("Unexpected event"),
7041 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7042 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7043 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7045 if announce_latest {
7046 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7048 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7051 check_closed_broadcast!(nodes[0], false);
7052 check_added_monitors!(nodes[0], 1);
7054 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7055 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7056 let events = nodes[0].node.get_and_clear_pending_events();
7057 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7058 assert_eq!(events.len(), 2);
7059 let mut first_failed = false;
7060 for event in events {
7062 Event::PaymentFailed { payment_hash, .. } => {
7063 if payment_hash == payment_hash_1 {
7064 assert!(!first_failed);
7065 first_failed = true;
7067 assert_eq!(payment_hash, payment_hash_2);
7070 _ => panic!("Unexpected event"),
7076 fn test_failure_delay_dust_htlc_local_commitment() {
7077 do_test_failure_delay_dust_htlc_local_commitment(true);
7078 do_test_failure_delay_dust_htlc_local_commitment(false);
7081 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7082 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7083 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7084 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7085 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7086 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7087 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7089 let chanmon_cfgs = create_chanmon_cfgs(3);
7090 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7091 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7092 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7093 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7095 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7097 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7098 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7100 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7101 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7103 // We revoked bs_commitment_tx
7105 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7106 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7109 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7110 let mut timeout_tx = Vec::new();
7112 // We fail dust-HTLC 1 by broadcast of local commitment tx
7113 connect_block(&nodes[0], &Block { header, txdata: vec![as_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 expect_payment_failed!(nodes[0], dust_hash, true);
7120 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7121 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7122 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7123 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7124 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7125 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7126 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7127 expect_payment_failed!(nodes[0], non_dust_hash, true);
7129 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7130 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7131 check_closed_broadcast!(nodes[0], false);
7132 check_added_monitors!(nodes[0], 1);
7133 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7134 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7135 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7136 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7138 expect_payment_failed!(nodes[0], dust_hash, true);
7139 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7140 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7141 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7142 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7143 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7144 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7145 expect_payment_failed!(nodes[0], non_dust_hash, true);
7147 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7149 let events = nodes[0].node.get_and_clear_pending_events();
7150 assert_eq!(events.len(), 2);
7153 Event::PaymentFailed { payment_hash, .. } => {
7154 if payment_hash == dust_hash { first = true; }
7155 else { first = false; }
7157 _ => panic!("Unexpected event"),
7160 Event::PaymentFailed { payment_hash, .. } => {
7161 if first { assert_eq!(payment_hash, non_dust_hash); }
7162 else { assert_eq!(payment_hash, dust_hash); }
7164 _ => panic!("Unexpected event"),
7171 fn test_sweep_outbound_htlc_failure_update() {
7172 do_test_sweep_outbound_htlc_failure_update(false, true);
7173 do_test_sweep_outbound_htlc_failure_update(false, false);
7174 do_test_sweep_outbound_htlc_failure_update(true, false);
7178 fn test_upfront_shutdown_script() {
7179 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7180 // enforce it at shutdown message
7182 let mut config = UserConfig::default();
7183 config.channel_options.announced_channel = true;
7184 config.peer_channel_config_limits.force_announced_channel_preference = false;
7185 config.channel_options.commit_upfront_shutdown_pubkey = false;
7186 let user_cfgs = [None, Some(config), None];
7187 let chanmon_cfgs = create_chanmon_cfgs(3);
7188 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7189 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7190 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7192 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7193 let flags = InitFeatures::known();
7194 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7195 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7196 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7197 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7198 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7199 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7200 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()));
7201 check_added_monitors!(nodes[2], 1);
7203 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7204 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7205 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7206 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7207 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7208 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7209 let events = nodes[2].node.get_and_clear_pending_msg_events();
7210 assert_eq!(events.len(), 1);
7212 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7213 _ => panic!("Unexpected event"),
7216 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7217 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7218 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7219 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7220 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7221 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7222 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7223 let events = nodes[1].node.get_and_clear_pending_msg_events();
7224 assert_eq!(events.len(), 1);
7226 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7227 _ => panic!("Unexpected event"),
7230 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7231 // channel smoothly, opt-out is from channel initiator here
7232 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7233 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7234 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7235 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7236 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7237 let events = nodes[0].node.get_and_clear_pending_msg_events();
7238 assert_eq!(events.len(), 1);
7240 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7241 _ => panic!("Unexpected event"),
7244 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7245 //// channel smoothly
7246 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7247 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7248 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7249 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7250 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7251 let events = nodes[0].node.get_and_clear_pending_msg_events();
7252 assert_eq!(events.len(), 2);
7254 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7255 _ => panic!("Unexpected event"),
7258 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7259 _ => panic!("Unexpected event"),
7264 fn test_upfront_shutdown_script_unsupport_segwit() {
7265 // We test that channel is closed early
7266 // if a segwit program is passed as upfront shutdown script,
7267 // but the peer does not support segwit.
7268 let chanmon_cfgs = create_chanmon_cfgs(2);
7269 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7270 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7271 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7273 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7275 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7276 open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7277 .push_slice(&[0, 0])
7280 let features = InitFeatures::known().clear_shutdown_anysegwit();
7281 nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7283 let events = nodes[0].node.get_and_clear_pending_msg_events();
7284 assert_eq!(events.len(), 1);
7286 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7287 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7288 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));
7290 _ => panic!("Unexpected event"),
7295 fn test_shutdown_script_any_segwit_allowed() {
7296 let mut config = UserConfig::default();
7297 config.channel_options.announced_channel = true;
7298 config.peer_channel_config_limits.force_announced_channel_preference = false;
7299 config.channel_options.commit_upfront_shutdown_pubkey = false;
7300 let user_cfgs = [None, Some(config), None];
7301 let chanmon_cfgs = create_chanmon_cfgs(3);
7302 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7303 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7304 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7306 //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7307 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7308 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7309 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7310 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7311 .push_slice(&[0, 0])
7313 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7314 let events = nodes[0].node.get_and_clear_pending_msg_events();
7315 assert_eq!(events.len(), 2);
7317 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7318 _ => panic!("Unexpected event"),
7321 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7322 _ => panic!("Unexpected event"),
7327 fn test_shutdown_script_any_segwit_not_allowed() {
7328 let mut config = UserConfig::default();
7329 config.channel_options.announced_channel = true;
7330 config.peer_channel_config_limits.force_announced_channel_preference = false;
7331 config.channel_options.commit_upfront_shutdown_pubkey = false;
7332 let user_cfgs = [None, Some(config), None];
7333 let chanmon_cfgs = create_chanmon_cfgs(3);
7334 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7335 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7336 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7338 //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7339 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7340 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7341 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7342 // Make an any segwit version script
7343 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7344 .push_slice(&[0, 0])
7346 let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7347 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7348 let events = nodes[0].node.get_and_clear_pending_msg_events();
7349 assert_eq!(events.len(), 2);
7351 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7352 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7353 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7355 _ => panic!("Unexpected event"),
7357 check_added_monitors!(nodes[0], 1);
7361 fn test_shutdown_script_segwit_but_not_anysegwit() {
7362 let mut config = UserConfig::default();
7363 config.channel_options.announced_channel = true;
7364 config.peer_channel_config_limits.force_announced_channel_preference = false;
7365 config.channel_options.commit_upfront_shutdown_pubkey = false;
7366 let user_cfgs = [None, Some(config), None];
7367 let chanmon_cfgs = create_chanmon_cfgs(3);
7368 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7369 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7370 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7372 //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7373 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7374 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7375 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7376 // Make a segwit script that is not a valid as any segwit
7377 node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7378 .push_slice(&[0, 0])
7380 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7381 let events = nodes[0].node.get_and_clear_pending_msg_events();
7382 assert_eq!(events.len(), 2);
7384 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7385 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7386 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7388 _ => panic!("Unexpected event"),
7390 check_added_monitors!(nodes[0], 1);
7394 fn test_user_configurable_csv_delay() {
7395 // We test our channel constructors yield errors when we pass them absurd csv delay
7397 let mut low_our_to_self_config = UserConfig::default();
7398 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7399 let mut high_their_to_self_config = UserConfig::default();
7400 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7401 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7402 let chanmon_cfgs = create_chanmon_cfgs(2);
7403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7405 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7407 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7408 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) {
7410 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())); },
7411 _ => panic!("Unexpected event"),
7413 } else { assert!(false) }
7415 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7416 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7417 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7418 open_channel.to_self_delay = 200;
7419 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) {
7421 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())); },
7422 _ => panic!("Unexpected event"),
7424 } else { assert!(false); }
7426 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7427 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7428 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()));
7429 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7430 accept_channel.to_self_delay = 200;
7431 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7432 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7434 &ErrorAction::SendErrorMessage { ref msg } => {
7435 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()));
7437 _ => { assert!(false); }
7439 } else { assert!(false); }
7441 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7442 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7443 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7444 open_channel.to_self_delay = 200;
7445 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) {
7447 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())); },
7448 _ => panic!("Unexpected event"),
7450 } else { assert!(false); }
7454 fn test_data_loss_protect() {
7455 // We want to be sure that :
7456 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7457 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7458 // * we close channel in case of detecting other being fallen behind
7459 // * we are able to claim our own outputs thanks to to_remote being static
7460 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7466 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7467 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7468 // during signing due to revoked tx
7469 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7470 let keys_manager = &chanmon_cfgs[0].keys_manager;
7473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7475 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7477 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7479 // Cache node A state before any channel update
7480 let previous_node_state = nodes[0].node.encode();
7481 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7482 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7484 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7485 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7487 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7488 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7490 // Restore node A from previous state
7491 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7492 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7493 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7494 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7495 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7496 persister = test_utils::TestPersister::new();
7497 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7499 let mut channel_monitors = HashMap::new();
7500 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7501 <(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 {
7502 keys_manager: keys_manager,
7503 fee_estimator: &fee_estimator,
7504 chain_monitor: &monitor,
7506 tx_broadcaster: &tx_broadcaster,
7507 default_config: UserConfig::default(),
7511 nodes[0].node = &node_state_0;
7512 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7513 nodes[0].chain_monitor = &monitor;
7514 nodes[0].chain_source = &chain_source;
7516 check_added_monitors!(nodes[0], 1);
7518 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7519 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7521 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7523 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7524 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7525 check_added_monitors!(nodes[0], 1);
7528 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7529 assert_eq!(node_txn.len(), 0);
7532 let mut reestablish_1 = Vec::with_capacity(1);
7533 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7534 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7535 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7536 reestablish_1.push(msg.clone());
7537 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7538 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7540 &ErrorAction::SendErrorMessage { ref msg } => {
7541 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");
7543 _ => panic!("Unexpected event!"),
7546 panic!("Unexpected event")
7550 // Check we close channel detecting A is fallen-behind
7551 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7552 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7553 check_added_monitors!(nodes[1], 1);
7556 // Check A is able to claim to_remote output
7557 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7558 assert_eq!(node_txn.len(), 1);
7559 check_spends!(node_txn[0], chan.3);
7560 assert_eq!(node_txn[0].output.len(), 2);
7561 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7562 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7563 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7564 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7565 assert_eq!(spend_txn.len(), 1);
7566 check_spends!(spend_txn[0], node_txn[0]);
7570 fn test_check_htlc_underpaying() {
7571 // Send payment through A -> B but A is maliciously
7572 // sending a probe payment (i.e less than expected value0
7573 // to B, B should refuse payment.
7575 let chanmon_cfgs = create_chanmon_cfgs(2);
7576 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7577 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7578 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7580 // Create some initial channels
7581 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7583 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7585 // Node 3 is expecting payment of 100_000 but receive 10_000,
7586 // fail htlc like we didn't know the preimage.
7587 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7588 nodes[1].node.process_pending_htlc_forwards();
7590 let events = nodes[1].node.get_and_clear_pending_msg_events();
7591 assert_eq!(events.len(), 1);
7592 let (update_fail_htlc, commitment_signed) = match events[0] {
7593 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 } } => {
7594 assert!(update_add_htlcs.is_empty());
7595 assert!(update_fulfill_htlcs.is_empty());
7596 assert_eq!(update_fail_htlcs.len(), 1);
7597 assert!(update_fail_malformed_htlcs.is_empty());
7598 assert!(update_fee.is_none());
7599 (update_fail_htlcs[0].clone(), commitment_signed)
7601 _ => panic!("Unexpected event"),
7603 check_added_monitors!(nodes[1], 1);
7605 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7606 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7608 // 10_000 msat as u64, followed by a height of 99 as u32
7609 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7610 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7611 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7612 nodes[1].node.get_and_clear_pending_events();
7616 fn test_announce_disable_channels() {
7617 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7618 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7620 let chanmon_cfgs = create_chanmon_cfgs(2);
7621 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7622 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7623 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7625 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7626 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7627 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7630 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7631 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7633 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7634 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7635 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7636 assert_eq!(msg_events.len(), 3);
7637 for e in msg_events {
7639 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7640 let short_id = msg.contents.short_channel_id;
7641 // Check generated channel_update match list in PendingChannelUpdate
7642 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7643 panic!("Generated ChannelUpdate for wrong chan!");
7646 _ => panic!("Unexpected event"),
7650 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7651 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7652 assert_eq!(reestablish_1.len(), 3);
7653 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7654 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7655 assert_eq!(reestablish_2.len(), 3);
7657 // Reestablish chan_1
7658 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7659 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7661 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7662 // Reestablish chan_2
7663 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7664 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7665 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7666 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7667 // Reestablish chan_3
7668 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7669 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7670 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7671 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7673 nodes[0].node.timer_chan_freshness_every_min();
7674 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7678 fn test_bump_penalty_txn_on_revoked_commitment() {
7679 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7680 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7682 let chanmon_cfgs = create_chanmon_cfgs(2);
7683 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7684 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7685 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7687 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7688 let logger = test_utils::TestLogger::new();
7691 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7692 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7693 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, &Vec::new(), 3000000, 30, &logger).unwrap();
7694 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7696 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7697 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7698 assert_eq!(revoked_txn[0].output.len(), 4);
7699 assert_eq!(revoked_txn[0].input.len(), 1);
7700 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7701 let revoked_txid = revoked_txn[0].txid();
7703 let mut penalty_sum = 0;
7704 for outp in revoked_txn[0].output.iter() {
7705 if outp.script_pubkey.is_v0_p2wsh() {
7706 penalty_sum += outp.value;
7710 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7711 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7713 // Actually revoke tx by claiming a HTLC
7714 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7715 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7716 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7717 check_added_monitors!(nodes[1], 1);
7719 // One or more justice tx should have been broadcast, check it
7723 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7724 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
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 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7729 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7730 penalty_1 = node_txn[0].txid();
7734 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7735 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7736 let mut penalty_2 = penalty_1;
7737 let mut feerate_2 = 0;
7739 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7740 assert_eq!(node_txn.len(), 1);
7741 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7742 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7743 assert_eq!(node_txn[0].output.len(), 1);
7744 check_spends!(node_txn[0], revoked_txn[0]);
7745 penalty_2 = node_txn[0].txid();
7746 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7747 assert_ne!(penalty_2, penalty_1);
7748 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7749 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7750 // Verify 25% bump heuristic
7751 assert!(feerate_2 * 100 >= feerate_1 * 125);
7755 assert_ne!(feerate_2, 0);
7757 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7758 connect_blocks(&nodes[1], 3, 118, true, header);
7760 let mut feerate_3 = 0;
7762 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7763 assert_eq!(node_txn.len(), 1);
7764 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7765 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7766 assert_eq!(node_txn[0].output.len(), 1);
7767 check_spends!(node_txn[0], revoked_txn[0]);
7768 penalty_3 = node_txn[0].txid();
7769 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7770 assert_ne!(penalty_3, penalty_2);
7771 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7772 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7773 // Verify 25% bump heuristic
7774 assert!(feerate_3 * 100 >= feerate_2 * 125);
7778 assert_ne!(feerate_3, 0);
7780 nodes[1].node.get_and_clear_pending_events();
7781 nodes[1].node.get_and_clear_pending_msg_events();
7785 fn test_bump_penalty_txn_on_revoked_htlcs() {
7786 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7787 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7789 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7790 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7791 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7792 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7793 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7795 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7796 // Lock HTLC in both directions
7797 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7798 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7800 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7801 assert_eq!(revoked_local_txn[0].input.len(), 1);
7802 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7804 // Revoke local commitment tx
7805 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7807 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7808 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7809 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7810 check_closed_broadcast!(nodes[1], false);
7811 check_added_monitors!(nodes[1], 1);
7813 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7814 assert_eq!(revoked_htlc_txn.len(), 4);
7815 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7816 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7817 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7818 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7819 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7820 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7821 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7822 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7823 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7824 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7825 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7826 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7827 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7828 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7831 // Broadcast set of revoked txn on A
7832 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7833 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7834 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7835 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7836 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7841 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7842 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7843 // Verify claim tx are spending revoked HTLC txn
7845 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7846 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7847 // which are included in the same block (they are broadcasted because we scan the
7848 // transactions linearly and generate claims as we go, they likely should be removed in the
7850 assert_eq!(node_txn[0].input.len(), 1);
7851 check_spends!(node_txn[0], revoked_local_txn[0]);
7852 assert_eq!(node_txn[1].input.len(), 1);
7853 check_spends!(node_txn[1], revoked_local_txn[0]);
7854 assert_eq!(node_txn[2].input.len(), 1);
7855 check_spends!(node_txn[2], revoked_local_txn[0]);
7857 // Each of the three justice transactions claim a separate (single) output of the three
7858 // available, which we check here:
7859 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7860 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7861 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7863 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7864 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7866 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7867 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7868 // a remote commitment tx has already been confirmed).
7869 check_spends!(node_txn[3], chan.3);
7871 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7872 // output, checked above).
7873 assert_eq!(node_txn[4].input.len(), 2);
7874 assert_eq!(node_txn[4].output.len(), 1);
7875 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7877 first = node_txn[4].txid();
7878 // Store both feerates for later comparison
7879 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7880 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7881 penalty_txn = vec![node_txn[2].clone()];
7885 // Connect one more block to see if bumped penalty are issued for HTLC txn
7886 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7887 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7888 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7889 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7891 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7892 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7894 check_spends!(node_txn[0], revoked_local_txn[0]);
7895 check_spends!(node_txn[1], revoked_local_txn[0]);
7896 // Note that these are both bogus - they spend outputs already claimed in block 129:
7897 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7898 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7900 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7901 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7907 // Few more blocks to confirm penalty txn
7908 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7909 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7910 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7912 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7913 assert_eq!(node_txn.len(), 1);
7915 assert_eq!(node_txn[0].input.len(), 2);
7916 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7917 // Verify bumped tx is different and 25% bump heuristic
7918 assert_ne!(first, node_txn[0].txid());
7919 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7920 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7921 assert!(feerate_2 * 100 > feerate_1 * 125);
7922 let txn = vec![node_txn[0].clone()];
7926 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7927 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7928 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7929 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7931 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7932 // We verify than no new transaction has been broadcast because previously
7933 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7934 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7935 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7936 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7937 // up bumped justice generation.
7938 assert_eq!(node_txn.len(), 0);
7941 check_closed_broadcast!(nodes[0], false);
7942 check_added_monitors!(nodes[0], 1);
7946 fn test_bump_penalty_txn_on_remote_commitment() {
7947 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7948 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7951 // Provide preimage for one
7952 // Check aggregation
7954 let chanmon_cfgs = create_chanmon_cfgs(2);
7955 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7956 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7957 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7959 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7960 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7961 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7963 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7964 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7965 assert_eq!(remote_txn[0].output.len(), 4);
7966 assert_eq!(remote_txn[0].input.len(), 1);
7967 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7969 // Claim a HTLC without revocation (provide B monitor with preimage)
7970 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7971 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7972 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7973 check_added_monitors!(nodes[1], 2);
7975 // One or more claim tx should have been broadcast, check it
7978 let feerate_timeout;
7979 let feerate_preimage;
7981 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7982 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7983 assert_eq!(node_txn[0].input.len(), 1);
7984 assert_eq!(node_txn[1].input.len(), 1);
7985 check_spends!(node_txn[0], remote_txn[0]);
7986 check_spends!(node_txn[1], remote_txn[0]);
7987 check_spends!(node_txn[2], chan.3);
7988 check_spends!(node_txn[3], node_txn[2]);
7989 check_spends!(node_txn[4], node_txn[2]);
7990 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7991 timeout = node_txn[0].txid();
7992 let index = node_txn[0].input[0].previous_output.vout;
7993 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7994 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7996 preimage = node_txn[1].txid();
7997 let index = node_txn[1].input[0].previous_output.vout;
7998 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7999 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
8001 timeout = node_txn[1].txid();
8002 let index = node_txn[1].input[0].previous_output.vout;
8003 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8004 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8006 preimage = node_txn[0].txid();
8007 let index = node_txn[0].input[0].previous_output.vout;
8008 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8009 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8013 assert_ne!(feerate_timeout, 0);
8014 assert_ne!(feerate_preimage, 0);
8016 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8017 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
8019 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8020 assert_eq!(node_txn.len(), 2);
8021 assert_eq!(node_txn[0].input.len(), 1);
8022 assert_eq!(node_txn[1].input.len(), 1);
8023 check_spends!(node_txn[0], remote_txn[0]);
8024 check_spends!(node_txn[1], remote_txn[0]);
8025 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8026 let index = node_txn[0].input[0].previous_output.vout;
8027 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8028 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8029 assert!(new_feerate * 100 > feerate_timeout * 125);
8030 assert_ne!(timeout, node_txn[0].txid());
8032 let index = node_txn[1].input[0].previous_output.vout;
8033 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8034 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8035 assert!(new_feerate * 100 > feerate_preimage * 125);
8036 assert_ne!(preimage, node_txn[1].txid());
8038 let index = node_txn[1].input[0].previous_output.vout;
8039 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8040 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8041 assert!(new_feerate * 100 > feerate_timeout * 125);
8042 assert_ne!(timeout, node_txn[1].txid());
8044 let index = node_txn[0].input[0].previous_output.vout;
8045 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8046 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8047 assert!(new_feerate * 100 > feerate_preimage * 125);
8048 assert_ne!(preimage, node_txn[0].txid());
8053 nodes[1].node.get_and_clear_pending_events();
8054 nodes[1].node.get_and_clear_pending_msg_events();
8058 fn test_set_outpoints_partial_claiming() {
8059 // - remote party claim tx, new bump tx
8060 // - disconnect remote claiming tx, new bump
8061 // - disconnect tx, see no tx anymore
8062 let chanmon_cfgs = create_chanmon_cfgs(2);
8063 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8064 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8065 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8067 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8068 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8069 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8071 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8072 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8073 assert_eq!(remote_txn.len(), 3);
8074 assert_eq!(remote_txn[0].output.len(), 4);
8075 assert_eq!(remote_txn[0].input.len(), 1);
8076 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8077 check_spends!(remote_txn[1], remote_txn[0]);
8078 check_spends!(remote_txn[2], remote_txn[0]);
8080 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8081 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8082 // Provide node A with both preimage
8083 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8084 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8085 check_added_monitors!(nodes[0], 2);
8086 nodes[0].node.get_and_clear_pending_events();
8087 nodes[0].node.get_and_clear_pending_msg_events();
8089 // Connect blocks on node A commitment transaction
8090 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8091 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8092 check_closed_broadcast!(nodes[0], false);
8093 check_added_monitors!(nodes[0], 1);
8094 // Verify node A broadcast tx claiming both HTLCs
8096 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8097 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8098 assert_eq!(node_txn.len(), 4);
8099 check_spends!(node_txn[0], remote_txn[0]);
8100 check_spends!(node_txn[1], chan.3);
8101 check_spends!(node_txn[2], node_txn[1]);
8102 check_spends!(node_txn[3], node_txn[1]);
8103 assert_eq!(node_txn[0].input.len(), 2);
8107 // Connect blocks on node B
8108 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8109 check_closed_broadcast!(nodes[1], false);
8110 check_added_monitors!(nodes[1], 1);
8111 // Verify node B broadcast 2 HTLC-timeout txn
8112 let partial_claim_tx = {
8113 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8114 assert_eq!(node_txn.len(), 3);
8115 check_spends!(node_txn[1], node_txn[0]);
8116 check_spends!(node_txn[2], node_txn[0]);
8117 assert_eq!(node_txn[1].input.len(), 1);
8118 assert_eq!(node_txn[2].input.len(), 1);
8122 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8123 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8124 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8126 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8127 assert_eq!(node_txn.len(), 1);
8128 check_spends!(node_txn[0], remote_txn[0]);
8129 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8132 nodes[0].node.get_and_clear_pending_msg_events();
8134 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8135 disconnect_block(&nodes[0], &header, 102);
8137 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8138 assert_eq!(node_txn.len(), 1);
8139 check_spends!(node_txn[0], remote_txn[0]);
8140 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8144 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8145 disconnect_block(&nodes[0], &header, 101);
8146 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8148 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8149 assert_eq!(node_txn.len(), 0);
8155 fn test_counterparty_raa_skip_no_crash() {
8156 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8157 // commitment transaction, we would have happily carried on and provided them the next
8158 // commitment transaction based on one RAA forward. This would probably eventually have led to
8159 // channel closure, but it would not have resulted in funds loss. Still, our
8160 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8161 // check simply that the channel is closed in response to such an RAA, but don't check whether
8162 // we decide to punish our counterparty for revoking their funds (as we don't currently
8164 let chanmon_cfgs = create_chanmon_cfgs(2);
8165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8168 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8170 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8171 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8172 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8173 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8174 // Must revoke without gaps
8175 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8176 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8177 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8179 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8180 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8181 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8182 check_added_monitors!(nodes[1], 1);
8186 fn test_bump_txn_sanitize_tracking_maps() {
8187 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8188 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8190 let chanmon_cfgs = create_chanmon_cfgs(2);
8191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8193 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8195 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8196 // Lock HTLC in both directions
8197 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8198 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8200 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8201 assert_eq!(revoked_local_txn[0].input.len(), 1);
8202 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8204 // Revoke local commitment tx
8205 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8207 // Broadcast set of revoked txn on A
8208 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8209 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8211 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8212 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8213 check_closed_broadcast!(nodes[0], false);
8214 check_added_monitors!(nodes[0], 1);
8216 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8217 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8218 check_spends!(node_txn[0], revoked_local_txn[0]);
8219 check_spends!(node_txn[1], revoked_local_txn[0]);
8220 check_spends!(node_txn[2], revoked_local_txn[0]);
8221 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8225 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8226 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8227 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8229 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8230 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8231 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8232 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8238 fn test_override_channel_config() {
8239 let chanmon_cfgs = create_chanmon_cfgs(2);
8240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8242 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8244 // Node0 initiates a channel to node1 using the override config.
8245 let mut override_config = UserConfig::default();
8246 override_config.own_channel_config.our_to_self_delay = 200;
8248 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8250 // Assert the channel created by node0 is using the override config.
8251 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8252 assert_eq!(res.channel_flags, 0);
8253 assert_eq!(res.to_self_delay, 200);
8257 fn test_override_0msat_htlc_minimum() {
8258 let mut zero_config = UserConfig::default();
8259 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8260 let chanmon_cfgs = create_chanmon_cfgs(2);
8261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8263 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8265 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8266 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8267 assert_eq!(res.htlc_minimum_msat, 1);
8269 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8270 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8271 assert_eq!(res.htlc_minimum_msat, 1);
8275 fn test_simple_payment_secret() {
8276 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8277 // features, however.
8278 let chanmon_cfgs = create_chanmon_cfgs(3);
8279 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8280 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8281 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8283 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8284 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8285 let logger = test_utils::TestLogger::new();
8287 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8288 let payment_secret = PaymentSecret([0xdb; 32]);
8289 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8290 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8291 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8292 // Claiming with all the correct values but the wrong secret should result in nothing...
8293 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8294 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8295 // ...but with the right secret we should be able to claim all the way back
8296 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8300 fn test_simple_mpp() {
8301 // Simple test of sending a multi-path payment.
8302 let chanmon_cfgs = create_chanmon_cfgs(4);
8303 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8304 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8305 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8307 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8308 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8309 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8310 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8311 let logger = test_utils::TestLogger::new();
8313 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8314 let payment_secret = PaymentSecret([0xdb; 32]);
8315 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8316 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, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8317 let path = route.paths[0].clone();
8318 route.paths.push(path);
8319 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8320 route.paths[0][0].short_channel_id = chan_1_id;
8321 route.paths[0][1].short_channel_id = chan_3_id;
8322 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8323 route.paths[1][0].short_channel_id = chan_2_id;
8324 route.paths[1][1].short_channel_id = chan_4_id;
8325 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8326 // Claiming with all the correct values but the wrong secret should result in nothing...
8327 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8328 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8329 // ...but with the right secret we should be able to claim all the way back
8330 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8334 fn test_update_err_monitor_lockdown() {
8335 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8336 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8337 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8339 // This scenario may happen in a watchtower setup, where watchtower process a block height
8340 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8341 // commitment at same time.
8343 let chanmon_cfgs = create_chanmon_cfgs(2);
8344 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8345 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8346 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8348 // Create some initial channel
8349 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8350 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8352 // Rebalance the network to generate htlc in the two directions
8353 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8355 // Route a HTLC from node 0 to node 1 (but don't settle)
8356 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8358 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8359 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8360 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8361 let persister = test_utils::TestPersister::new();
8363 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8364 let monitor = monitors.get(&outpoint).unwrap();
8365 let mut w = test_utils::TestVecWriter(Vec::new());
8366 monitor.write(&mut w).unwrap();
8367 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8368 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8369 assert!(new_monitor == *monitor);
8370 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);
8371 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8374 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8375 watchtower.chain_monitor.block_connected(&header, &[], 200);
8377 // Try to update ChannelMonitor
8378 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8379 check_added_monitors!(nodes[1], 1);
8380 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8381 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8382 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8383 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8384 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8385 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8386 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8387 } else { assert!(false); }
8388 } else { assert!(false); };
8389 // Our local monitor is in-sync and hasn't processed yet timeout
8390 check_added_monitors!(nodes[0], 1);
8391 let events = nodes[0].node.get_and_clear_pending_events();
8392 assert_eq!(events.len(), 1);
8396 fn test_concurrent_monitor_claim() {
8397 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8398 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8399 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8400 // state N+1 confirms. Alice claims output from state N+1.
8402 let chanmon_cfgs = create_chanmon_cfgs(2);
8403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8405 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8407 // Create some initial channel
8408 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8409 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8411 // Rebalance the network to generate htlc in the two directions
8412 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8414 // Route a HTLC from node 0 to node 1 (but don't settle)
8415 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8417 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8418 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8419 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8420 let persister = test_utils::TestPersister::new();
8421 let watchtower_alice = {
8422 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8423 let monitor = monitors.get(&outpoint).unwrap();
8424 let mut w = test_utils::TestVecWriter(Vec::new());
8425 monitor.write(&mut w).unwrap();
8426 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8427 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8428 assert!(new_monitor == *monitor);
8429 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);
8430 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8433 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8434 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8436 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8438 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8439 assert_eq!(txn.len(), 2);
8443 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8444 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8445 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8446 let persister = test_utils::TestPersister::new();
8447 let watchtower_bob = {
8448 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8449 let monitor = monitors.get(&outpoint).unwrap();
8450 let mut w = test_utils::TestVecWriter(Vec::new());
8451 monitor.write(&mut w).unwrap();
8452 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8453 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8454 assert!(new_monitor == *monitor);
8455 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);
8456 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8459 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8460 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8462 // Route another payment to generate another update with still previous HTLC pending
8463 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8465 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8466 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, &Vec::new(), 3000000 , TEST_FINAL_CLTV, &logger).unwrap();
8467 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8469 check_added_monitors!(nodes[1], 1);
8471 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8472 assert_eq!(updates.update_add_htlcs.len(), 1);
8473 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8474 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8475 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8476 // Watchtower Alice should already have seen the block and reject the update
8477 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8478 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8479 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8480 } else { assert!(false); }
8481 } else { assert!(false); };
8482 // Our local monitor is in-sync and hasn't processed yet timeout
8483 check_added_monitors!(nodes[0], 1);
8485 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8486 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8488 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8491 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8492 assert_eq!(txn.len(), 2);
8493 bob_state_y = txn[0].clone();
8497 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8498 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8500 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8501 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8502 // the onchain detection of the HTLC output
8503 assert_eq!(htlc_txn.len(), 2);
8504 check_spends!(htlc_txn[0], bob_state_y);
8505 check_spends!(htlc_txn[1], bob_state_y);
8510 fn test_pre_lockin_no_chan_closed_update() {
8511 // Test that if a peer closes a channel in response to a funding_created message we don't
8512 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8515 // Doing so would imply a channel monitor update before the initial channel monitor
8516 // registration, violating our API guarantees.
8518 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8519 // then opening a second channel with the same funding output as the first (which is not
8520 // rejected because the first channel does not exist in the ChannelManager) and closing it
8521 // before receiving funding_signed.
8522 let chanmon_cfgs = create_chanmon_cfgs(2);
8523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8525 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8527 // Create an initial channel
8528 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8529 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8530 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8531 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8532 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8534 // Move the first channel through the funding flow...
8535 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8537 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8538 check_added_monitors!(nodes[0], 0);
8540 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8541 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8542 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8543 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8547 fn test_htlc_no_detection() {
8548 // This test is a mutation to underscore the detection logic bug we had
8549 // before #653. HTLC value routed is above the remaining balance, thus
8550 // inverting HTLC and `to_remote` output. HTLC will come second and
8551 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8552 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8553 // outputs order detection for correct spending children filtring.
8555 let chanmon_cfgs = create_chanmon_cfgs(2);
8556 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8557 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8558 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8560 // Create some initial channels
8561 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8563 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8564 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8565 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8566 assert_eq!(local_txn[0].input.len(), 1);
8567 assert_eq!(local_txn[0].output.len(), 3);
8568 check_spends!(local_txn[0], chan_1.3);
8570 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8571 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8572 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8573 // We deliberately connect the local tx twice as this should provoke a failure calling
8574 // this test before #653 fix.
8575 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8576 check_closed_broadcast!(nodes[0], false);
8577 check_added_monitors!(nodes[0], 1);
8579 let htlc_timeout = {
8580 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8581 assert_eq!(node_txn[0].input.len(), 1);
8582 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8583 check_spends!(node_txn[0], local_txn[0]);
8587 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8588 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8589 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8590 expect_payment_failed!(nodes[0], our_payment_hash, true);
8593 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8594 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8595 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8596 // Carol, Alice would be the upstream node, and Carol the downstream.)
8598 // Steps of the test:
8599 // 1) Alice sends a HTLC to Carol through Bob.
8600 // 2) Carol doesn't settle the HTLC.
8601 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8602 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8603 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8604 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8605 // 5) Carol release the preimage to Bob off-chain.
8606 // 6) Bob claims the offered output on the broadcasted commitment.
8607 let chanmon_cfgs = create_chanmon_cfgs(3);
8608 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8609 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8610 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8612 // Create some initial channels
8613 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8614 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8616 // Steps (1) and (2):
8617 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8618 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8620 // Check that Alice's commitment transaction now contains an output for this HTLC.
8621 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8622 check_spends!(alice_txn[0], chan_ab.3);
8623 assert_eq!(alice_txn[0].output.len(), 2);
8624 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8625 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8626 assert_eq!(alice_txn.len(), 2);
8628 // Steps (3) and (4):
8629 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8630 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8631 let mut force_closing_node = 0; // Alice force-closes
8632 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8633 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8634 check_closed_broadcast!(nodes[force_closing_node], false);
8635 check_added_monitors!(nodes[force_closing_node], 1);
8636 if go_onchain_before_fulfill {
8637 let txn_to_broadcast = match broadcast_alice {
8638 true => alice_txn.clone(),
8639 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8641 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8642 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8643 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8644 if broadcast_alice {
8645 check_closed_broadcast!(nodes[1], false);
8646 check_added_monitors!(nodes[1], 1);
8648 assert_eq!(bob_txn.len(), 1);
8649 check_spends!(bob_txn[0], chan_ab.3);
8653 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8654 // process of removing the HTLC from their commitment transactions.
8655 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8656 check_added_monitors!(nodes[2], 1);
8657 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8658 assert!(carol_updates.update_add_htlcs.is_empty());
8659 assert!(carol_updates.update_fail_htlcs.is_empty());
8660 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8661 assert!(carol_updates.update_fee.is_none());
8662 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8664 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8665 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8666 if !go_onchain_before_fulfill && broadcast_alice {
8667 let events = nodes[1].node.get_and_clear_pending_msg_events();
8668 assert_eq!(events.len(), 1);
8670 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8671 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8673 _ => panic!("Unexpected event"),
8676 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8677 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8678 // Carol<->Bob's updated commitment transaction info.
8679 check_added_monitors!(nodes[1], 2);
8681 let events = nodes[1].node.get_and_clear_pending_msg_events();
8682 assert_eq!(events.len(), 2);
8683 let bob_revocation = match events[0] {
8684 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8685 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8688 _ => panic!("Unexpected event"),
8690 let bob_updates = match events[1] {
8691 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8692 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8695 _ => panic!("Unexpected event"),
8698 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8699 check_added_monitors!(nodes[2], 1);
8700 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8701 check_added_monitors!(nodes[2], 1);
8703 let events = nodes[2].node.get_and_clear_pending_msg_events();
8704 assert_eq!(events.len(), 1);
8705 let carol_revocation = match events[0] {
8706 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8707 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8710 _ => panic!("Unexpected event"),
8712 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8713 check_added_monitors!(nodes[1], 1);
8715 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8716 // here's where we put said channel's commitment tx on-chain.
8717 let mut txn_to_broadcast = alice_txn.clone();
8718 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8719 if !go_onchain_before_fulfill {
8720 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8721 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8722 // If Bob was the one to force-close, he will have already passed these checks earlier.
8723 if broadcast_alice {
8724 check_closed_broadcast!(nodes[1], false);
8725 check_added_monitors!(nodes[1], 1);
8727 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8728 if broadcast_alice {
8729 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8730 // new block being connected. The ChannelManager being notified triggers a monitor update,
8731 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8732 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8734 assert_eq!(bob_txn.len(), 3);
8735 check_spends!(bob_txn[1], chan_ab.3);
8737 assert_eq!(bob_txn.len(), 2);
8738 check_spends!(bob_txn[0], chan_ab.3);
8743 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8744 // broadcasted commitment transaction.
8746 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8747 if go_onchain_before_fulfill {
8748 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8749 assert_eq!(bob_txn.len(), 2);
8751 let script_weight = match broadcast_alice {
8752 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8753 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8755 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8756 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8757 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8758 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8759 if broadcast_alice && !go_onchain_before_fulfill {
8760 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8761 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8763 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8764 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8770 fn test_onchain_htlc_settlement_after_close() {
8771 do_test_onchain_htlc_settlement_after_close(true, true);
8772 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8773 do_test_onchain_htlc_settlement_after_close(true, false);
8774 do_test_onchain_htlc_settlement_after_close(false, false);
8778 fn test_duplicate_chan_id() {
8779 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8780 // already open we reject it and keep the old channel.
8782 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8783 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8784 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8785 // updating logic for the existing channel.
8786 let chanmon_cfgs = create_chanmon_cfgs(2);
8787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8789 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8791 // Create an initial channel
8792 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8793 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8794 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8795 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()));
8797 // Try to create a second channel with the same temporary_channel_id as the first and check
8798 // that it is rejected.
8799 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8801 let events = nodes[1].node.get_and_clear_pending_msg_events();
8802 assert_eq!(events.len(), 1);
8804 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8805 // Technically, at this point, nodes[1] would be justified in thinking both the
8806 // first (valid) and second (invalid) channels are closed, given they both have
8807 // the same non-temporary channel_id. However, currently we do not, so we just
8808 // move forward with it.
8809 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8810 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8812 _ => panic!("Unexpected event"),
8816 // Move the first channel through the funding flow...
8817 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8819 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8820 check_added_monitors!(nodes[0], 0);
8822 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8823 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8825 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8826 assert_eq!(added_monitors.len(), 1);
8827 assert_eq!(added_monitors[0].0, funding_output);
8828 added_monitors.clear();
8830 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8832 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8833 let channel_id = funding_outpoint.to_channel_id();
8835 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8838 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8839 // Technically this is allowed by the spec, but we don't support it and there's little reason
8840 // to. Still, it shouldn't cause any other issues.
8841 open_chan_msg.temporary_channel_id = channel_id;
8842 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8844 let events = nodes[1].node.get_and_clear_pending_msg_events();
8845 assert_eq!(events.len(), 1);
8847 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8848 // Technically, at this point, nodes[1] would be justified in thinking both
8849 // channels are closed, but currently we do not, so we just move forward with it.
8850 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8851 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8853 _ => panic!("Unexpected event"),
8857 // Now try to create a second channel which has a duplicate funding output.
8858 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8859 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8860 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8861 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()));
8862 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8864 let funding_created = {
8865 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8866 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8867 let logger = test_utils::TestLogger::new();
8868 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8870 check_added_monitors!(nodes[0], 0);
8871 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8872 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8873 // still needs to be cleared here.
8874 check_added_monitors!(nodes[1], 1);
8876 // ...still, nodes[1] will reject the duplicate channel.
8878 let events = nodes[1].node.get_and_clear_pending_msg_events();
8879 assert_eq!(events.len(), 1);
8881 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8882 // Technically, at this point, nodes[1] would be justified in thinking both
8883 // channels are closed, but currently we do not, so we just move forward with it.
8884 assert_eq!(msg.channel_id, channel_id);
8885 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8887 _ => panic!("Unexpected event"),
8891 // finally, finish creating the original channel and send a payment over it to make sure
8892 // everything is functional.
8893 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8895 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8896 assert_eq!(added_monitors.len(), 1);
8897 assert_eq!(added_monitors[0].0, funding_output);
8898 added_monitors.clear();
8901 let events_4 = nodes[0].node.get_and_clear_pending_events();
8902 assert_eq!(events_4.len(), 1);
8904 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8905 assert_eq!(user_channel_id, 42);
8906 assert_eq!(*funding_txo, funding_output);
8908 _ => panic!("Unexpected event"),
8911 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8912 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8913 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8914 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8918 fn test_error_chans_closed() {
8919 // Test that we properly handle error messages, closing appropriate channels.
8921 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8922 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8923 // we can test various edge cases around it to ensure we don't regress.
8924 let chanmon_cfgs = create_chanmon_cfgs(3);
8925 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8926 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8927 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8929 // Create some initial channels
8930 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8931 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8932 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8934 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8935 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8936 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8938 // Closing a channel from a different peer has no effect
8939 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8940 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8942 // Closing one channel doesn't impact others
8943 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8944 check_added_monitors!(nodes[0], 1);
8945 check_closed_broadcast!(nodes[0], false);
8946 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8947 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);
8948 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);
8950 // A null channel ID should close all channels
8951 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8952 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8953 check_added_monitors!(nodes[0], 2);
8954 let events = nodes[0].node.get_and_clear_pending_msg_events();
8955 assert_eq!(events.len(), 2);
8957 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8958 assert_eq!(msg.contents.flags & 2, 2);
8960 _ => panic!("Unexpected event"),
8963 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8964 assert_eq!(msg.contents.flags & 2, 2);
8966 _ => panic!("Unexpected event"),
8968 // Note that at this point users of a standard PeerHandler will end up calling
8969 // peer_disconnected with no_connection_possible set to false, duplicating the
8970 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8971 // users with their own peer handling logic. We duplicate the call here, however.
8972 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8973 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8975 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8976 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8977 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);