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 (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1973 route.paths[0].last_mut().unwrap().fee_msat += 1;
1974 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1975 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1976 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)));
1977 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1978 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);
1981 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1982 // nodes[0]'s wealth
1984 let amt_msat = recv_value_0 + total_fee_msat;
1985 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1986 // Also, ensure that each payment has enough to be over the dust limit to
1987 // ensure it'll be included in each commit tx fee calculation.
1988 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1989 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1990 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1993 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1995 let (stat01_, stat11_, stat12_, stat22_) = (
1996 get_channel_value_stat!(nodes[0], chan_1.2),
1997 get_channel_value_stat!(nodes[1], chan_1.2),
1998 get_channel_value_stat!(nodes[1], chan_2.2),
1999 get_channel_value_stat!(nodes[2], chan_2.2),
2002 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2003 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2004 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2005 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2006 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2009 // adding pending output.
2010 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2011 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2012 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2013 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2014 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2015 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2016 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2017 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2018 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2020 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2021 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2022 let amt_msat_1 = recv_value_1 + total_fee_msat;
2024 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2025 let payment_event_1 = {
2026 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2027 check_added_monitors!(nodes[0], 1);
2029 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2030 assert_eq!(events.len(), 1);
2031 SendEvent::from_event(events.remove(0))
2033 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2035 // channel reserve test with htlc pending output > 0
2036 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2038 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2039 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2040 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2041 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2044 // split the rest to test holding cell
2045 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2046 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2047 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2048 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2050 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2051 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);
2054 // now see if they go through on both sides
2055 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2056 // but this will stuck in the holding cell
2057 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2058 check_added_monitors!(nodes[0], 0);
2059 let events = nodes[0].node.get_and_clear_pending_events();
2060 assert_eq!(events.len(), 0);
2062 // test with outbound holding cell amount > 0
2064 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2065 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2066 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2067 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2068 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);
2071 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2072 // this will also stuck in the holding cell
2073 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2074 check_added_monitors!(nodes[0], 0);
2075 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2076 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2078 // flush the pending htlc
2079 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2080 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2081 check_added_monitors!(nodes[1], 1);
2083 // the pending htlc should be promoted to committed
2084 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2085 check_added_monitors!(nodes[0], 1);
2086 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2088 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2089 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2090 // No commitment_signed so get_event_msg's assert(len == 1) passes
2091 check_added_monitors!(nodes[0], 1);
2093 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2094 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2095 check_added_monitors!(nodes[1], 1);
2097 expect_pending_htlcs_forwardable!(nodes[1]);
2099 let ref payment_event_11 = expect_forward!(nodes[1]);
2100 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2101 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2103 expect_pending_htlcs_forwardable!(nodes[2]);
2104 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2106 // flush the htlcs in the holding cell
2107 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2108 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2109 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2110 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2111 expect_pending_htlcs_forwardable!(nodes[1]);
2113 let ref payment_event_3 = expect_forward!(nodes[1]);
2114 assert_eq!(payment_event_3.msgs.len(), 2);
2115 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2116 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2118 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2119 expect_pending_htlcs_forwardable!(nodes[2]);
2121 let events = nodes[2].node.get_and_clear_pending_events();
2122 assert_eq!(events.len(), 2);
2124 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2125 assert_eq!(our_payment_hash_21, *payment_hash);
2126 assert_eq!(*payment_secret, None);
2127 assert_eq!(recv_value_21, amt);
2129 _ => panic!("Unexpected event"),
2132 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2133 assert_eq!(our_payment_hash_22, *payment_hash);
2134 assert_eq!(None, *payment_secret);
2135 assert_eq!(recv_value_22, amt);
2137 _ => panic!("Unexpected event"),
2140 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2141 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2142 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2144 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2145 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2146 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2148 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2149 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);
2150 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2151 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2152 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2154 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2155 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2159 fn channel_reserve_in_flight_removes() {
2160 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2161 // can send to its counterparty, but due to update ordering, the other side may not yet have
2162 // considered those HTLCs fully removed.
2163 // This tests that we don't count HTLCs which will not be included in the next remote
2164 // commitment transaction towards the reserve value (as it implies no commitment transaction
2165 // will be generated which violates the remote reserve value).
2166 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2168 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2169 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2170 // you only consider the value of the first HTLC, it may not),
2171 // * start routing a third HTLC from A to B,
2172 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2173 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2174 // * deliver the first fulfill from B
2175 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2177 // * deliver A's response CS and RAA.
2178 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2179 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2180 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2181 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2182 let chanmon_cfgs = create_chanmon_cfgs(2);
2183 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2184 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2185 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2186 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2187 let logger = test_utils::TestLogger::new();
2189 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2190 // Route the first two HTLCs.
2191 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2192 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2194 // Start routing the third HTLC (this is just used to get everyone in the right state).
2195 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2197 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2198 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();
2199 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2200 check_added_monitors!(nodes[0], 1);
2201 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2202 assert_eq!(events.len(), 1);
2203 SendEvent::from_event(events.remove(0))
2206 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2207 // initial fulfill/CS.
2208 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2209 check_added_monitors!(nodes[1], 1);
2210 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2212 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2213 // remove the second HTLC when we send the HTLC back from B to A.
2214 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2215 check_added_monitors!(nodes[1], 1);
2216 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2218 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2219 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2220 check_added_monitors!(nodes[0], 1);
2221 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2222 expect_payment_sent!(nodes[0], payment_preimage_1);
2224 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2225 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2226 check_added_monitors!(nodes[1], 1);
2227 // B is already AwaitingRAA, so cant generate a CS here
2228 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2230 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2231 check_added_monitors!(nodes[1], 1);
2232 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2234 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2235 check_added_monitors!(nodes[0], 1);
2236 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2238 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2239 check_added_monitors!(nodes[1], 1);
2240 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2242 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2243 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2244 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2245 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2246 // on-chain as necessary).
2247 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2248 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2249 check_added_monitors!(nodes[0], 1);
2250 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2251 expect_payment_sent!(nodes[0], payment_preimage_2);
2253 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2254 check_added_monitors!(nodes[1], 1);
2255 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2257 expect_pending_htlcs_forwardable!(nodes[1]);
2258 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2260 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2261 // resolve the second HTLC from A's point of view.
2262 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2263 check_added_monitors!(nodes[0], 1);
2264 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2266 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2267 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2268 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2270 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2271 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();
2272 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2273 check_added_monitors!(nodes[1], 1);
2274 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2275 assert_eq!(events.len(), 1);
2276 SendEvent::from_event(events.remove(0))
2279 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2280 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2281 check_added_monitors!(nodes[0], 1);
2282 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2284 // Now just resolve all the outstanding messages/HTLCs for completeness...
2286 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2287 check_added_monitors!(nodes[1], 1);
2288 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2290 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2291 check_added_monitors!(nodes[1], 1);
2293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2294 check_added_monitors!(nodes[0], 1);
2295 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2297 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2298 check_added_monitors!(nodes[1], 1);
2299 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2302 check_added_monitors!(nodes[0], 1);
2304 expect_pending_htlcs_forwardable!(nodes[0]);
2305 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2307 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2308 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2312 fn channel_monitor_network_test() {
2313 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2314 // tests that ChannelMonitor is able to recover from various states.
2315 let chanmon_cfgs = create_chanmon_cfgs(5);
2316 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2317 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2318 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2320 // Create some initial channels
2321 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2322 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2323 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2324 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2326 // Rebalance the network a bit by relaying one payment through all the channels...
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);
2330 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2332 // Simple case with no pending HTLCs:
2333 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2334 check_added_monitors!(nodes[1], 1);
2336 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2337 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2338 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2339 check_added_monitors!(nodes[0], 1);
2340 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2342 get_announce_close_broadcast_events(&nodes, 0, 1);
2343 assert_eq!(nodes[0].node.list_channels().len(), 0);
2344 assert_eq!(nodes[1].node.list_channels().len(), 1);
2346 // One pending HTLC is discarded by the force-close:
2347 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2349 // Simple case of one pending HTLC to HTLC-Timeout
2350 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2351 check_added_monitors!(nodes[1], 1);
2353 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2354 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2355 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2356 check_added_monitors!(nodes[2], 1);
2357 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2359 get_announce_close_broadcast_events(&nodes, 1, 2);
2360 assert_eq!(nodes[1].node.list_channels().len(), 0);
2361 assert_eq!(nodes[2].node.list_channels().len(), 1);
2363 macro_rules! claim_funds {
2364 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2366 assert!($node.node.claim_funds($preimage, &None, $amount));
2367 check_added_monitors!($node, 1);
2369 let events = $node.node.get_and_clear_pending_msg_events();
2370 assert_eq!(events.len(), 1);
2372 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2373 assert!(update_add_htlcs.is_empty());
2374 assert!(update_fail_htlcs.is_empty());
2375 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2377 _ => panic!("Unexpected event"),
2383 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2384 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2385 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2386 check_added_monitors!(nodes[2], 1);
2387 let node2_commitment_txid;
2389 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2390 node2_commitment_txid = node_txn[0].txid();
2392 // Claim the payment on nodes[3], giving it knowledge of the preimage
2393 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2395 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2396 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2397 check_added_monitors!(nodes[3], 1);
2399 check_preimage_claim(&nodes[3], &node_txn);
2401 get_announce_close_broadcast_events(&nodes, 2, 3);
2402 assert_eq!(nodes[2].node.list_channels().len(), 0);
2403 assert_eq!(nodes[3].node.list_channels().len(), 1);
2405 { // Cheat and reset nodes[4]'s height to 1
2406 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2407 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2410 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2411 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2412 // One pending HTLC to time out:
2413 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2414 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2417 let (close_chan_update_1, close_chan_update_2) = {
2418 let mut block = Block {
2419 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2422 connect_block(&nodes[3], &block, 2);
2423 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2425 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2428 connect_block(&nodes[3], &block, i);
2430 let events = nodes[3].node.get_and_clear_pending_msg_events();
2431 assert_eq!(events.len(), 1);
2432 let close_chan_update_1 = match events[0] {
2433 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2436 _ => panic!("Unexpected event"),
2438 check_added_monitors!(nodes[3], 1);
2440 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2442 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2443 node_txn.retain(|tx| {
2444 if tx.input[0].previous_output.txid == node2_commitment_txid {
2450 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2452 // Claim the payment on nodes[4], giving it knowledge of the preimage
2453 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2456 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2460 connect_block(&nodes[4], &block, 2);
2461 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2463 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2466 connect_block(&nodes[4], &block, i);
2468 let events = nodes[4].node.get_and_clear_pending_msg_events();
2469 assert_eq!(events.len(), 1);
2470 let close_chan_update_2 = match events[0] {
2471 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2474 _ => panic!("Unexpected event"),
2476 check_added_monitors!(nodes[4], 1);
2477 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2480 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2481 txdata: vec![node_txn[0].clone()],
2483 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2485 check_preimage_claim(&nodes[4], &node_txn);
2486 (close_chan_update_1, close_chan_update_2)
2488 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2489 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2490 assert_eq!(nodes[3].node.list_channels().len(), 0);
2491 assert_eq!(nodes[4].node.list_channels().len(), 0);
2495 fn test_justice_tx() {
2496 // Test justice txn built on revoked HTLC-Success tx, against both sides
2497 let mut alice_config = UserConfig::default();
2498 alice_config.channel_options.announced_channel = true;
2499 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2500 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2501 let mut bob_config = UserConfig::default();
2502 bob_config.channel_options.announced_channel = true;
2503 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2504 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2505 let user_cfgs = [Some(alice_config), Some(bob_config)];
2506 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2507 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2508 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2509 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2510 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2511 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2512 // Create some new channels:
2513 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2515 // A pending HTLC which will be revoked:
2516 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2517 // Get the will-be-revoked local txn from nodes[0]
2518 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2519 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2520 assert_eq!(revoked_local_txn[0].input.len(), 1);
2521 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2522 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2523 assert_eq!(revoked_local_txn[1].input.len(), 1);
2524 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2525 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2526 // Revoke the old state
2527 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2530 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2531 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2533 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2534 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2535 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2537 check_spends!(node_txn[0], revoked_local_txn[0]);
2538 node_txn.swap_remove(0);
2539 node_txn.truncate(1);
2541 check_added_monitors!(nodes[1], 1);
2542 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2544 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2545 // Verify broadcast of revoked HTLC-timeout
2546 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2547 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2548 check_added_monitors!(nodes[0], 1);
2549 // Broadcast revoked HTLC-timeout on node 1
2550 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2551 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2553 get_announce_close_broadcast_events(&nodes, 0, 1);
2555 assert_eq!(nodes[0].node.list_channels().len(), 0);
2556 assert_eq!(nodes[1].node.list_channels().len(), 0);
2558 // We test justice_tx build by A on B's revoked HTLC-Success tx
2559 // Create some new channels:
2560 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2562 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2566 // A pending HTLC which will be revoked:
2567 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2568 // Get the will-be-revoked local txn from B
2569 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2570 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2571 assert_eq!(revoked_local_txn[0].input.len(), 1);
2572 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2573 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2574 // Revoke the old state
2575 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2577 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2578 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2580 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2581 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2582 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2584 check_spends!(node_txn[0], revoked_local_txn[0]);
2585 node_txn.swap_remove(0);
2587 check_added_monitors!(nodes[0], 1);
2588 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2590 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2591 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2592 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2593 check_added_monitors!(nodes[1], 1);
2594 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2595 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2597 get_announce_close_broadcast_events(&nodes, 0, 1);
2598 assert_eq!(nodes[0].node.list_channels().len(), 0);
2599 assert_eq!(nodes[1].node.list_channels().len(), 0);
2603 fn revoked_output_claim() {
2604 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2605 // transaction is broadcast by its counterparty
2606 let chanmon_cfgs = create_chanmon_cfgs(2);
2607 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2608 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2609 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2610 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2611 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2612 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2613 assert_eq!(revoked_local_txn.len(), 1);
2614 // Only output is the full channel value back to nodes[0]:
2615 assert_eq!(revoked_local_txn[0].output.len(), 1);
2616 // Send a payment through, updating everyone's latest commitment txn
2617 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2619 // Inform nodes[1] that nodes[0] broadcast a stale tx
2620 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2621 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2622 check_added_monitors!(nodes[1], 1);
2623 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2624 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2626 check_spends!(node_txn[0], revoked_local_txn[0]);
2627 check_spends!(node_txn[1], chan_1.3);
2629 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2630 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2631 get_announce_close_broadcast_events(&nodes, 0, 1);
2632 check_added_monitors!(nodes[0], 1)
2636 fn claim_htlc_outputs_shared_tx() {
2637 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2638 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2639 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2644 // Create some new channel:
2645 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2647 // Rebalance the network to generate htlc in the two directions
2648 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2649 // 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
2650 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2651 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2653 // Get the will-be-revoked local txn from node[0]
2654 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2655 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2656 assert_eq!(revoked_local_txn[0].input.len(), 1);
2657 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2658 assert_eq!(revoked_local_txn[1].input.len(), 1);
2659 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2660 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2661 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2663 //Revoke the old state
2664 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2667 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2668 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2669 check_added_monitors!(nodes[0], 1);
2670 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2671 check_added_monitors!(nodes[1], 1);
2672 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2673 expect_payment_failed!(nodes[1], payment_hash_2, true);
2675 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2676 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2678 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2679 check_spends!(node_txn[0], revoked_local_txn[0]);
2681 let mut witness_lens = BTreeSet::new();
2682 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2683 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2684 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2685 assert_eq!(witness_lens.len(), 3);
2686 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2687 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2688 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2690 // Next nodes[1] broadcasts its current local tx state:
2691 assert_eq!(node_txn[1].input.len(), 1);
2692 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2694 assert_eq!(node_txn[2].input.len(), 1);
2695 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2696 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2697 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2698 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2699 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2701 get_announce_close_broadcast_events(&nodes, 0, 1);
2702 assert_eq!(nodes[0].node.list_channels().len(), 0);
2703 assert_eq!(nodes[1].node.list_channels().len(), 0);
2707 fn claim_htlc_outputs_single_tx() {
2708 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2709 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2710 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2715 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2717 // Rebalance the network to generate htlc in the two directions
2718 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2719 // 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
2720 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2721 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2722 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2724 // Get the will-be-revoked local txn from node[0]
2725 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2727 //Revoke the old state
2728 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2731 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2732 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2733 check_added_monitors!(nodes[0], 1);
2734 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2735 check_added_monitors!(nodes[1], 1);
2736 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2738 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2739 expect_payment_failed!(nodes[1], payment_hash_2, true);
2741 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2742 assert_eq!(node_txn.len(), 9);
2743 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2744 // ChannelManager: local commmitment + local HTLC-timeout (2)
2745 // 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)
2746 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2748 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2749 assert_eq!(node_txn[2].input.len(), 1);
2750 check_spends!(node_txn[2], chan_1.3);
2751 assert_eq!(node_txn[3].input.len(), 1);
2752 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2753 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2754 check_spends!(node_txn[3], node_txn[2]);
2756 // Justice transactions are indices 1-2-4
2757 assert_eq!(node_txn[0].input.len(), 1);
2758 assert_eq!(node_txn[1].input.len(), 1);
2759 assert_eq!(node_txn[4].input.len(), 1);
2761 check_spends!(node_txn[0], revoked_local_txn[0]);
2762 check_spends!(node_txn[1], revoked_local_txn[0]);
2763 check_spends!(node_txn[4], revoked_local_txn[0]);
2765 let mut witness_lens = BTreeSet::new();
2766 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2767 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2768 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2769 assert_eq!(witness_lens.len(), 3);
2770 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2771 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2772 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2774 get_announce_close_broadcast_events(&nodes, 0, 1);
2775 assert_eq!(nodes[0].node.list_channels().len(), 0);
2776 assert_eq!(nodes[1].node.list_channels().len(), 0);
2780 fn test_htlc_on_chain_success() {
2781 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2782 // the preimage backward accordingly. So here we test that ChannelManager is
2783 // broadcasting the right event to other nodes in payment path.
2784 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2785 // A --------------------> B ----------------------> C (preimage)
2786 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2787 // commitment transaction was broadcast.
2788 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2790 // B should be able to claim via preimage if A then broadcasts its local tx.
2791 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2792 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2793 // PaymentSent event).
2795 let chanmon_cfgs = create_chanmon_cfgs(3);
2796 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2797 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2798 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2800 // Create some initial channels
2801 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2802 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2804 // Rebalance the network a bit by relaying one payment through all the channels...
2805 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2806 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2808 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2809 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2810 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2812 // Broadcast legit commitment tx from C on B's chain
2813 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2814 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2815 assert_eq!(commitment_tx.len(), 1);
2816 check_spends!(commitment_tx[0], chan_2.3);
2817 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2818 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2819 check_added_monitors!(nodes[2], 2);
2820 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2821 assert!(updates.update_add_htlcs.is_empty());
2822 assert!(updates.update_fail_htlcs.is_empty());
2823 assert!(updates.update_fail_malformed_htlcs.is_empty());
2824 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2826 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2827 check_closed_broadcast!(nodes[2], false);
2828 check_added_monitors!(nodes[2], 1);
2829 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)
2830 assert_eq!(node_txn.len(), 5);
2831 assert_eq!(node_txn[0], node_txn[3]);
2832 assert_eq!(node_txn[1], node_txn[4]);
2833 assert_eq!(node_txn[2], commitment_tx[0]);
2834 check_spends!(node_txn[0], commitment_tx[0]);
2835 check_spends!(node_txn[1], commitment_tx[0]);
2836 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2837 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2838 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2839 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2840 assert_eq!(node_txn[0].lock_time, 0);
2841 assert_eq!(node_txn[1].lock_time, 0);
2843 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2844 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2846 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2847 assert_eq!(added_monitors.len(), 1);
2848 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2849 added_monitors.clear();
2851 let events = nodes[1].node.get_and_clear_pending_msg_events();
2853 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2854 assert_eq!(added_monitors.len(), 2);
2855 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2856 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2857 added_monitors.clear();
2859 assert_eq!(events.len(), 2);
2861 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2862 _ => panic!("Unexpected event"),
2865 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, .. } } => {
2866 assert!(update_add_htlcs.is_empty());
2867 assert!(update_fail_htlcs.is_empty());
2868 assert_eq!(update_fulfill_htlcs.len(), 1);
2869 assert!(update_fail_malformed_htlcs.is_empty());
2870 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2872 _ => panic!("Unexpected event"),
2874 macro_rules! check_tx_local_broadcast {
2875 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2876 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2877 assert_eq!(node_txn.len(), 5);
2878 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2879 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2880 check_spends!(node_txn[0], $commitment_tx);
2881 check_spends!(node_txn[1], $commitment_tx);
2882 assert_ne!(node_txn[0].lock_time, 0);
2883 assert_ne!(node_txn[1].lock_time, 0);
2885 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2890 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2891 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2892 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2893 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2895 check_spends!(node_txn[2], $chan_tx);
2896 check_spends!(node_txn[3], node_txn[2]);
2897 check_spends!(node_txn[4], node_txn[2]);
2898 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2899 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2900 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2901 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2902 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2903 assert_ne!(node_txn[3].lock_time, 0);
2904 assert_ne!(node_txn[4].lock_time, 0);
2908 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2909 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2910 // timeout-claim of the output that nodes[2] just claimed via success.
2911 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2913 // Broadcast legit commitment tx from A on B's chain
2914 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2915 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2916 check_spends!(commitment_tx[0], chan_1.3);
2917 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2918 check_closed_broadcast!(nodes[1], false);
2919 check_added_monitors!(nodes[1], 1);
2920 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2921 assert_eq!(node_txn.len(), 4);
2922 check_spends!(node_txn[0], commitment_tx[0]);
2923 assert_eq!(node_txn[0].input.len(), 2);
2924 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2925 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2926 assert_eq!(node_txn[0].lock_time, 0);
2927 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2928 check_spends!(node_txn[1], chan_1.3);
2929 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2930 check_spends!(node_txn[2], node_txn[1]);
2931 check_spends!(node_txn[3], node_txn[1]);
2932 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2933 // we already checked the same situation with A.
2935 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2936 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2937 check_closed_broadcast!(nodes[0], false);
2938 check_added_monitors!(nodes[0], 1);
2939 let events = nodes[0].node.get_and_clear_pending_events();
2940 assert_eq!(events.len(), 2);
2941 let mut first_claimed = false;
2942 for event in events {
2944 Event::PaymentSent { payment_preimage } => {
2945 if payment_preimage == our_payment_preimage {
2946 assert!(!first_claimed);
2947 first_claimed = true;
2949 assert_eq!(payment_preimage, our_payment_preimage_2);
2952 _ => panic!("Unexpected event"),
2955 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2959 fn test_htlc_on_chain_timeout() {
2960 // Test that in case of a unilateral close onchain, we detect the state of output and
2961 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2962 // broadcasting the right event to other nodes in payment path.
2963 // A ------------------> B ----------------------> C (timeout)
2964 // B's commitment tx C's commitment tx
2966 // B's HTLC timeout tx B's timeout tx
2968 let chanmon_cfgs = create_chanmon_cfgs(3);
2969 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2970 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2971 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2973 // Create some intial channels
2974 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2975 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2977 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2978 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2979 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2981 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2982 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2984 // Broadcast legit commitment tx from C on B's chain
2985 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2986 check_spends!(commitment_tx[0], chan_2.3);
2987 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2988 check_added_monitors!(nodes[2], 0);
2989 expect_pending_htlcs_forwardable!(nodes[2]);
2990 check_added_monitors!(nodes[2], 1);
2992 let events = nodes[2].node.get_and_clear_pending_msg_events();
2993 assert_eq!(events.len(), 1);
2995 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, .. } } => {
2996 assert!(update_add_htlcs.is_empty());
2997 assert!(!update_fail_htlcs.is_empty());
2998 assert!(update_fulfill_htlcs.is_empty());
2999 assert!(update_fail_malformed_htlcs.is_empty());
3000 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3002 _ => panic!("Unexpected event"),
3004 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3005 check_closed_broadcast!(nodes[2], false);
3006 check_added_monitors!(nodes[2], 1);
3007 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3008 assert_eq!(node_txn.len(), 1);
3009 check_spends!(node_txn[0], chan_2.3);
3010 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3012 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3013 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3014 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3017 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3018 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3019 assert_eq!(node_txn[1], node_txn[3]);
3020 assert_eq!(node_txn[2], node_txn[4]);
3022 check_spends!(node_txn[0], commitment_tx[0]);
3023 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3025 check_spends!(node_txn[1], chan_2.3);
3026 check_spends!(node_txn[2], node_txn[1]);
3027 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3028 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3030 timeout_tx = node_txn[0].clone();
3034 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3035 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3036 check_added_monitors!(nodes[1], 1);
3037 check_closed_broadcast!(nodes[1], false);
3039 expect_pending_htlcs_forwardable!(nodes[1]);
3040 check_added_monitors!(nodes[1], 1);
3041 let events = nodes[1].node.get_and_clear_pending_msg_events();
3042 assert_eq!(events.len(), 1);
3044 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3045 assert!(update_add_htlcs.is_empty());
3046 assert!(!update_fail_htlcs.is_empty());
3047 assert!(update_fulfill_htlcs.is_empty());
3048 assert!(update_fail_malformed_htlcs.is_empty());
3049 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3051 _ => panic!("Unexpected event"),
3053 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
3054 assert_eq!(node_txn.len(), 0);
3056 // Broadcast legit commitment tx from B on A's chain
3057 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3058 check_spends!(commitment_tx[0], chan_1.3);
3060 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3061 check_closed_broadcast!(nodes[0], false);
3062 check_added_monitors!(nodes[0], 1);
3063 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3064 assert_eq!(node_txn.len(), 3);
3065 check_spends!(node_txn[0], commitment_tx[0]);
3066 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3067 check_spends!(node_txn[1], chan_1.3);
3068 check_spends!(node_txn[2], node_txn[1]);
3069 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3070 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3074 fn test_simple_commitment_revoked_fail_backward() {
3075 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3076 // and fail backward accordingly.
3078 let chanmon_cfgs = create_chanmon_cfgs(3);
3079 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3080 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3081 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3083 // Create some initial channels
3084 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3085 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3087 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3088 // Get the will-be-revoked local txn from nodes[2]
3089 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3090 // Revoke the old state
3091 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3093 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3095 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3096 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3097 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3098 check_added_monitors!(nodes[1], 1);
3099 check_closed_broadcast!(nodes[1], false);
3101 expect_pending_htlcs_forwardable!(nodes[1]);
3102 check_added_monitors!(nodes[1], 1);
3103 let events = nodes[1].node.get_and_clear_pending_msg_events();
3104 assert_eq!(events.len(), 1);
3106 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, .. } } => {
3107 assert!(update_add_htlcs.is_empty());
3108 assert_eq!(update_fail_htlcs.len(), 1);
3109 assert!(update_fulfill_htlcs.is_empty());
3110 assert!(update_fail_malformed_htlcs.is_empty());
3111 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3113 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3114 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3116 let events = nodes[0].node.get_and_clear_pending_msg_events();
3117 assert_eq!(events.len(), 1);
3119 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3120 _ => panic!("Unexpected event"),
3122 expect_payment_failed!(nodes[0], payment_hash, false);
3124 _ => panic!("Unexpected event"),
3128 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3129 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3130 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3131 // commitment transaction anymore.
3132 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3133 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3134 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3135 // technically disallowed and we should probably handle it reasonably.
3136 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3137 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3139 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3140 // commitment_signed (implying it will be in the latest remote commitment transaction).
3141 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3142 // and once they revoke the previous commitment transaction (allowing us to send a new
3143 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3144 let chanmon_cfgs = create_chanmon_cfgs(3);
3145 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3146 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3147 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3149 // Create some initial channels
3150 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3151 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3153 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3154 // Get the will-be-revoked local txn from nodes[2]
3155 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3156 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3157 // Revoke the old state
3158 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3160 let value = if use_dust {
3161 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3162 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3163 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3166 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3167 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3168 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3170 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3171 expect_pending_htlcs_forwardable!(nodes[2]);
3172 check_added_monitors!(nodes[2], 1);
3173 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3174 assert!(updates.update_add_htlcs.is_empty());
3175 assert!(updates.update_fulfill_htlcs.is_empty());
3176 assert!(updates.update_fail_malformed_htlcs.is_empty());
3177 assert_eq!(updates.update_fail_htlcs.len(), 1);
3178 assert!(updates.update_fee.is_none());
3179 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3180 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3181 // Drop the last RAA from 3 -> 2
3183 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3184 expect_pending_htlcs_forwardable!(nodes[2]);
3185 check_added_monitors!(nodes[2], 1);
3186 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3187 assert!(updates.update_add_htlcs.is_empty());
3188 assert!(updates.update_fulfill_htlcs.is_empty());
3189 assert!(updates.update_fail_malformed_htlcs.is_empty());
3190 assert_eq!(updates.update_fail_htlcs.len(), 1);
3191 assert!(updates.update_fee.is_none());
3192 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3193 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3194 check_added_monitors!(nodes[1], 1);
3195 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3196 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3197 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3198 check_added_monitors!(nodes[2], 1);
3200 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3201 expect_pending_htlcs_forwardable!(nodes[2]);
3202 check_added_monitors!(nodes[2], 1);
3203 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3204 assert!(updates.update_add_htlcs.is_empty());
3205 assert!(updates.update_fulfill_htlcs.is_empty());
3206 assert!(updates.update_fail_malformed_htlcs.is_empty());
3207 assert_eq!(updates.update_fail_htlcs.len(), 1);
3208 assert!(updates.update_fee.is_none());
3209 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3210 // At this point first_payment_hash has dropped out of the latest two commitment
3211 // transactions that nodes[1] is tracking...
3212 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3213 check_added_monitors!(nodes[1], 1);
3214 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3215 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3216 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3217 check_added_monitors!(nodes[2], 1);
3219 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3220 // on nodes[2]'s RAA.
3221 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3222 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3223 let logger = test_utils::TestLogger::new();
3224 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();
3225 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3226 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3227 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3228 check_added_monitors!(nodes[1], 0);
3231 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3232 // One monitor for the new revocation preimage, no second on as we won't generate a new
3233 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3234 check_added_monitors!(nodes[1], 1);
3235 let events = nodes[1].node.get_and_clear_pending_events();
3236 assert_eq!(events.len(), 1);
3238 Event::PendingHTLCsForwardable { .. } => { },
3239 _ => panic!("Unexpected event"),
3241 // Deliberately don't process the pending fail-back so they all fail back at once after
3242 // block connection just like the !deliver_bs_raa case
3245 let mut failed_htlcs = HashSet::new();
3246 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3248 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3249 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3250 check_added_monitors!(nodes[1], 1);
3251 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3253 let events = nodes[1].node.get_and_clear_pending_events();
3254 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3256 Event::PaymentFailed { ref payment_hash, .. } => {
3257 assert_eq!(*payment_hash, fourth_payment_hash);
3259 _ => panic!("Unexpected event"),
3261 if !deliver_bs_raa {
3263 Event::PendingHTLCsForwardable { .. } => { },
3264 _ => panic!("Unexpected event"),
3267 nodes[1].node.process_pending_htlc_forwards();
3268 check_added_monitors!(nodes[1], 1);
3270 let events = nodes[1].node.get_and_clear_pending_msg_events();
3271 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3272 match events[if deliver_bs_raa { 1 } else { 0 }] {
3273 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3274 _ => panic!("Unexpected event"),
3278 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3279 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3280 assert_eq!(update_add_htlcs.len(), 1);
3281 assert!(update_fulfill_htlcs.is_empty());
3282 assert!(update_fail_htlcs.is_empty());
3283 assert!(update_fail_malformed_htlcs.is_empty());
3285 _ => panic!("Unexpected event"),
3288 match events[if deliver_bs_raa { 2 } else { 1 }] {
3289 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3290 assert!(update_add_htlcs.is_empty());
3291 assert_eq!(update_fail_htlcs.len(), 3);
3292 assert!(update_fulfill_htlcs.is_empty());
3293 assert!(update_fail_malformed_htlcs.is_empty());
3294 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3296 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3297 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3298 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3300 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3302 let events = nodes[0].node.get_and_clear_pending_msg_events();
3303 // If we delivered B's RAA we got an unknown preimage error, not something
3304 // that we should update our routing table for.
3305 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3306 for event in events {
3308 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3309 _ => panic!("Unexpected event"),
3312 let events = nodes[0].node.get_and_clear_pending_events();
3313 assert_eq!(events.len(), 3);
3315 Event::PaymentFailed { ref payment_hash, .. } => {
3316 assert!(failed_htlcs.insert(payment_hash.0));
3318 _ => panic!("Unexpected event"),
3321 Event::PaymentFailed { ref payment_hash, .. } => {
3322 assert!(failed_htlcs.insert(payment_hash.0));
3324 _ => panic!("Unexpected event"),
3327 Event::PaymentFailed { ref payment_hash, .. } => {
3328 assert!(failed_htlcs.insert(payment_hash.0));
3330 _ => panic!("Unexpected event"),
3333 _ => panic!("Unexpected event"),
3336 assert!(failed_htlcs.contains(&first_payment_hash.0));
3337 assert!(failed_htlcs.contains(&second_payment_hash.0));
3338 assert!(failed_htlcs.contains(&third_payment_hash.0));
3342 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3343 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3344 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3345 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3346 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3350 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3351 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3352 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3353 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3354 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3358 fn fail_backward_pending_htlc_upon_channel_failure() {
3359 let chanmon_cfgs = create_chanmon_cfgs(2);
3360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3363 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3364 let logger = test_utils::TestLogger::new();
3366 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3368 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3369 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3370 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();
3371 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3372 check_added_monitors!(nodes[0], 1);
3374 let payment_event = {
3375 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3376 assert_eq!(events.len(), 1);
3377 SendEvent::from_event(events.remove(0))
3379 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3380 assert_eq!(payment_event.msgs.len(), 1);
3383 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3384 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3386 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3387 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();
3388 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3389 check_added_monitors!(nodes[0], 0);
3391 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3394 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3396 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3398 let secp_ctx = Secp256k1::new();
3399 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3400 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3401 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3402 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();
3403 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3404 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3405 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3407 // Send a 0-msat update_add_htlc to fail the channel.
3408 let update_add_htlc = msgs::UpdateAddHTLC {
3414 onion_routing_packet,
3416 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3419 // Check that Alice fails backward the pending HTLC from the second payment.
3420 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3421 check_closed_broadcast!(nodes[0], true);
3422 check_added_monitors!(nodes[0], 1);
3426 fn test_htlc_ignore_latest_remote_commitment() {
3427 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3428 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3429 let chanmon_cfgs = create_chanmon_cfgs(2);
3430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3433 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3435 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3436 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3437 check_closed_broadcast!(nodes[0], false);
3438 check_added_monitors!(nodes[0], 1);
3440 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3441 assert_eq!(node_txn.len(), 2);
3443 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3444 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3445 check_closed_broadcast!(nodes[1], false);
3446 check_added_monitors!(nodes[1], 1);
3448 // Duplicate the connect_block call since this may happen due to other listeners
3449 // registering new transactions
3450 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3454 fn test_force_close_fail_back() {
3455 // Check which HTLCs are failed-backwards on channel force-closure
3456 let chanmon_cfgs = create_chanmon_cfgs(3);
3457 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3458 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3459 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3460 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3461 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3462 let logger = test_utils::TestLogger::new();
3464 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3466 let mut payment_event = {
3467 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3468 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();
3469 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3470 check_added_monitors!(nodes[0], 1);
3472 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3473 assert_eq!(events.len(), 1);
3474 SendEvent::from_event(events.remove(0))
3477 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3478 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3480 expect_pending_htlcs_forwardable!(nodes[1]);
3482 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3483 assert_eq!(events_2.len(), 1);
3484 payment_event = SendEvent::from_event(events_2.remove(0));
3485 assert_eq!(payment_event.msgs.len(), 1);
3487 check_added_monitors!(nodes[1], 1);
3488 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3489 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3490 check_added_monitors!(nodes[2], 1);
3491 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3493 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3494 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3495 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3497 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3498 check_closed_broadcast!(nodes[2], false);
3499 check_added_monitors!(nodes[2], 1);
3501 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3502 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3503 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3504 // back to nodes[1] upon timeout otherwise.
3505 assert_eq!(node_txn.len(), 1);
3510 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3511 txdata: vec![tx.clone()],
3513 connect_block(&nodes[1], &block, 1);
3515 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3516 check_closed_broadcast!(nodes[1], false);
3517 check_added_monitors!(nodes[1], 1);
3519 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3521 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.read().unwrap();
3522 monitors.get(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3523 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3525 connect_block(&nodes[2], &block, 1);
3526 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3527 assert_eq!(node_txn.len(), 1);
3528 assert_eq!(node_txn[0].input.len(), 1);
3529 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3530 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3531 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3533 check_spends!(node_txn[0], tx);
3537 fn test_unconf_chan() {
3538 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3539 let chanmon_cfgs = create_chanmon_cfgs(2);
3540 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3541 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3542 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3543 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3545 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3546 assert_eq!(channel_state.by_id.len(), 1);
3547 assert_eq!(channel_state.short_to_id.len(), 1);
3548 mem::drop(channel_state);
3550 let mut headers = Vec::new();
3551 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3552 headers.push(header.clone());
3554 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3555 headers.push(header.clone());
3557 while !headers.is_empty() {
3558 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3560 check_closed_broadcast!(nodes[0], false);
3561 check_added_monitors!(nodes[0], 1);
3562 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3563 assert_eq!(channel_state.by_id.len(), 0);
3564 assert_eq!(channel_state.short_to_id.len(), 0);
3568 fn test_simple_peer_disconnect() {
3569 // Test that we can reconnect when there are no lost messages
3570 let chanmon_cfgs = create_chanmon_cfgs(3);
3571 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3572 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3573 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3574 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3575 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3577 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3578 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3579 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3581 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3582 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3583 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3584 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3586 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3587 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3588 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3590 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3591 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3592 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3593 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3595 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3596 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3598 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3599 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3601 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3603 let events = nodes[0].node.get_and_clear_pending_events();
3604 assert_eq!(events.len(), 2);
3606 Event::PaymentSent { payment_preimage } => {
3607 assert_eq!(payment_preimage, payment_preimage_3);
3609 _ => panic!("Unexpected event"),
3612 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3613 assert_eq!(payment_hash, payment_hash_5);
3614 assert!(rejected_by_dest);
3616 _ => panic!("Unexpected event"),
3620 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3621 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3624 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3625 // Test that we can reconnect when in-flight HTLC updates get dropped
3626 let chanmon_cfgs = create_chanmon_cfgs(2);
3627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3629 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630 if messages_delivered == 0 {
3631 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3632 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3634 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3637 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3639 let logger = test_utils::TestLogger::new();
3640 let payment_event = {
3641 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3642 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3643 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3644 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3645 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3646 check_added_monitors!(nodes[0], 1);
3648 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3649 assert_eq!(events.len(), 1);
3650 SendEvent::from_event(events.remove(0))
3652 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3654 if messages_delivered < 2 {
3655 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3657 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3658 if messages_delivered >= 3 {
3659 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3660 check_added_monitors!(nodes[1], 1);
3661 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3663 if messages_delivered >= 4 {
3664 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3665 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3666 check_added_monitors!(nodes[0], 1);
3668 if messages_delivered >= 5 {
3669 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3670 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3671 // No commitment_signed so get_event_msg's assert(len == 1) passes
3672 check_added_monitors!(nodes[0], 1);
3674 if messages_delivered >= 6 {
3675 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3676 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3677 check_added_monitors!(nodes[1], 1);
3684 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3685 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3686 if messages_delivered < 3 {
3687 // Even if the funding_locked messages get exchanged, as long as nothing further was
3688 // received on either side, both sides will need to resend them.
3689 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3690 } else if messages_delivered == 3 {
3691 // nodes[0] still wants its RAA + commitment_signed
3692 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3693 } else if messages_delivered == 4 {
3694 // nodes[0] still wants its commitment_signed
3695 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3696 } else if messages_delivered == 5 {
3697 // nodes[1] still wants its final RAA
3698 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3699 } else if messages_delivered == 6 {
3700 // Everything was delivered...
3701 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3704 let events_1 = nodes[1].node.get_and_clear_pending_events();
3705 assert_eq!(events_1.len(), 1);
3707 Event::PendingHTLCsForwardable { .. } => { },
3708 _ => panic!("Unexpected event"),
3711 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3712 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3713 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3715 nodes[1].node.process_pending_htlc_forwards();
3717 let events_2 = nodes[1].node.get_and_clear_pending_events();
3718 assert_eq!(events_2.len(), 1);
3720 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3721 assert_eq!(payment_hash_1, *payment_hash);
3722 assert_eq!(*payment_secret, None);
3723 assert_eq!(amt, 1000000);
3725 _ => panic!("Unexpected event"),
3728 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3729 check_added_monitors!(nodes[1], 1);
3731 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3732 assert_eq!(events_3.len(), 1);
3733 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3734 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3735 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3736 assert!(updates.update_add_htlcs.is_empty());
3737 assert!(updates.update_fail_htlcs.is_empty());
3738 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3739 assert!(updates.update_fail_malformed_htlcs.is_empty());
3740 assert!(updates.update_fee.is_none());
3741 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3743 _ => panic!("Unexpected event"),
3746 if messages_delivered >= 1 {
3747 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3749 let events_4 = nodes[0].node.get_and_clear_pending_events();
3750 assert_eq!(events_4.len(), 1);
3752 Event::PaymentSent { ref payment_preimage } => {
3753 assert_eq!(payment_preimage_1, *payment_preimage);
3755 _ => panic!("Unexpected event"),
3758 if messages_delivered >= 2 {
3759 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3760 check_added_monitors!(nodes[0], 1);
3761 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3763 if messages_delivered >= 3 {
3764 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3765 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3766 check_added_monitors!(nodes[1], 1);
3768 if messages_delivered >= 4 {
3769 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3770 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3771 // No commitment_signed so get_event_msg's assert(len == 1) passes
3772 check_added_monitors!(nodes[1], 1);
3774 if messages_delivered >= 5 {
3775 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3776 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3777 check_added_monitors!(nodes[0], 1);
3784 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3785 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3786 if messages_delivered < 2 {
3787 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3788 //TODO: Deduplicate PaymentSent events, then enable this if:
3789 //if messages_delivered < 1 {
3790 let events_4 = nodes[0].node.get_and_clear_pending_events();
3791 assert_eq!(events_4.len(), 1);
3793 Event::PaymentSent { ref payment_preimage } => {
3794 assert_eq!(payment_preimage_1, *payment_preimage);
3796 _ => panic!("Unexpected event"),
3799 } else if messages_delivered == 2 {
3800 // nodes[0] still wants its RAA + commitment_signed
3801 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3802 } else if messages_delivered == 3 {
3803 // nodes[0] still wants its commitment_signed
3804 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3805 } else if messages_delivered == 4 {
3806 // nodes[1] still wants its final RAA
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3808 } else if messages_delivered == 5 {
3809 // Everything was delivered...
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3813 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3814 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3815 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3817 // Channel should still work fine...
3818 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3819 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3820 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3821 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3822 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3823 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3827 fn test_drop_messages_peer_disconnect_a() {
3828 do_test_drop_messages_peer_disconnect(0);
3829 do_test_drop_messages_peer_disconnect(1);
3830 do_test_drop_messages_peer_disconnect(2);
3831 do_test_drop_messages_peer_disconnect(3);
3835 fn test_drop_messages_peer_disconnect_b() {
3836 do_test_drop_messages_peer_disconnect(4);
3837 do_test_drop_messages_peer_disconnect(5);
3838 do_test_drop_messages_peer_disconnect(6);
3842 fn test_funding_peer_disconnect() {
3843 // Test that we can lock in our funding tx while disconnected
3844 let chanmon_cfgs = create_chanmon_cfgs(2);
3845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3847 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3848 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3850 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3851 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3853 confirm_transaction(&nodes[0], &tx);
3854 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3855 assert_eq!(events_1.len(), 1);
3857 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3858 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3860 _ => panic!("Unexpected event"),
3863 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3865 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3866 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3868 confirm_transaction(&nodes[1], &tx);
3869 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3870 assert_eq!(events_2.len(), 2);
3871 let funding_locked = match events_2[0] {
3872 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3873 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3876 _ => panic!("Unexpected event"),
3878 let bs_announcement_sigs = match events_2[1] {
3879 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3880 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3883 _ => panic!("Unexpected event"),
3886 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3888 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3889 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3890 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3891 assert_eq!(events_3.len(), 2);
3892 let as_announcement_sigs = match events_3[0] {
3893 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3894 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3897 _ => panic!("Unexpected event"),
3899 let (as_announcement, as_update) = match events_3[1] {
3900 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3901 (msg.clone(), update_msg.clone())
3903 _ => panic!("Unexpected event"),
3906 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3907 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3908 assert_eq!(events_4.len(), 1);
3909 let (_, bs_update) = match events_4[0] {
3910 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3911 (msg.clone(), update_msg.clone())
3913 _ => panic!("Unexpected event"),
3916 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3917 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3918 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3920 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3921 let logger = test_utils::TestLogger::new();
3922 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();
3923 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3924 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3928 fn test_drop_messages_peer_disconnect_dual_htlc() {
3929 // Test that we can handle reconnecting when both sides of a channel have pending
3930 // commitment_updates when we disconnect.
3931 let chanmon_cfgs = create_chanmon_cfgs(2);
3932 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3933 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3934 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3935 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3936 let logger = test_utils::TestLogger::new();
3938 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3940 // Now try to send a second payment which will fail to send
3941 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3942 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3943 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();
3944 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3945 check_added_monitors!(nodes[0], 1);
3947 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3948 assert_eq!(events_1.len(), 1);
3950 MessageSendEvent::UpdateHTLCs { .. } => {},
3951 _ => panic!("Unexpected event"),
3954 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3955 check_added_monitors!(nodes[1], 1);
3957 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3958 assert_eq!(events_2.len(), 1);
3960 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 } } => {
3961 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3962 assert!(update_add_htlcs.is_empty());
3963 assert_eq!(update_fulfill_htlcs.len(), 1);
3964 assert!(update_fail_htlcs.is_empty());
3965 assert!(update_fail_malformed_htlcs.is_empty());
3966 assert!(update_fee.is_none());
3968 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3969 let events_3 = nodes[0].node.get_and_clear_pending_events();
3970 assert_eq!(events_3.len(), 1);
3972 Event::PaymentSent { ref payment_preimage } => {
3973 assert_eq!(*payment_preimage, payment_preimage_1);
3975 _ => panic!("Unexpected event"),
3978 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3979 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3980 // No commitment_signed so get_event_msg's assert(len == 1) passes
3981 check_added_monitors!(nodes[0], 1);
3983 _ => panic!("Unexpected event"),
3986 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3987 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3989 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3990 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3991 assert_eq!(reestablish_1.len(), 1);
3992 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3993 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3994 assert_eq!(reestablish_2.len(), 1);
3996 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3997 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3998 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3999 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4001 assert!(as_resp.0.is_none());
4002 assert!(bs_resp.0.is_none());
4004 assert!(bs_resp.1.is_none());
4005 assert!(bs_resp.2.is_none());
4007 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4009 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4010 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4011 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4012 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4013 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4014 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4015 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4016 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4017 // No commitment_signed so get_event_msg's assert(len == 1) passes
4018 check_added_monitors!(nodes[1], 1);
4020 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4021 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4022 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4023 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4024 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4025 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4026 assert!(bs_second_commitment_signed.update_fee.is_none());
4027 check_added_monitors!(nodes[1], 1);
4029 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4030 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4031 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4032 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4033 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4034 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4035 assert!(as_commitment_signed.update_fee.is_none());
4036 check_added_monitors!(nodes[0], 1);
4038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4039 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4040 // No commitment_signed so get_event_msg's assert(len == 1) passes
4041 check_added_monitors!(nodes[0], 1);
4043 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4044 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4045 // No commitment_signed so get_event_msg's assert(len == 1) passes
4046 check_added_monitors!(nodes[1], 1);
4048 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4049 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4050 check_added_monitors!(nodes[1], 1);
4052 expect_pending_htlcs_forwardable!(nodes[1]);
4054 let events_5 = nodes[1].node.get_and_clear_pending_events();
4055 assert_eq!(events_5.len(), 1);
4057 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4058 assert_eq!(payment_hash_2, *payment_hash);
4059 assert_eq!(*payment_secret, None);
4061 _ => panic!("Unexpected event"),
4064 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4065 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4066 check_added_monitors!(nodes[0], 1);
4068 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4071 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4072 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4073 // to avoid our counterparty failing the channel.
4074 let chanmon_cfgs = create_chanmon_cfgs(2);
4075 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4076 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4077 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4079 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4080 let logger = test_utils::TestLogger::new();
4082 let our_payment_hash = if send_partial_mpp {
4083 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4084 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();
4085 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4086 let payment_secret = PaymentSecret([0xdb; 32]);
4087 // Use the utility function send_payment_along_path to send the payment with MPP data which
4088 // indicates there are more HTLCs coming.
4089 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4090 check_added_monitors!(nodes[0], 1);
4091 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4092 assert_eq!(events.len(), 1);
4093 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4094 // hop should *not* yet generate any PaymentReceived event(s).
4095 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4098 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4101 let mut block = Block {
4102 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4105 connect_block(&nodes[0], &block, 101);
4106 connect_block(&nodes[1], &block, 101);
4107 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4108 block.header.prev_blockhash = block.block_hash();
4109 connect_block(&nodes[0], &block, i);
4110 connect_block(&nodes[1], &block, i);
4113 expect_pending_htlcs_forwardable!(nodes[1]);
4115 check_added_monitors!(nodes[1], 1);
4116 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4117 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4118 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4119 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4120 assert!(htlc_timeout_updates.update_fee.is_none());
4122 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4123 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4124 // 100_000 msat as u64, followed by a height of 123 as u32
4125 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4126 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4127 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4131 fn test_htlc_timeout() {
4132 do_test_htlc_timeout(true);
4133 do_test_htlc_timeout(false);
4136 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4137 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4138 let chanmon_cfgs = create_chanmon_cfgs(3);
4139 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4140 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4141 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4142 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4143 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4144 let logger = test_utils::TestLogger::new();
4146 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4147 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4149 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4150 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();
4151 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4153 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4154 check_added_monitors!(nodes[1], 1);
4156 // Now attempt to route a second payment, which should be placed in the holding cell
4157 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4159 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4160 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();
4161 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4162 check_added_monitors!(nodes[0], 1);
4163 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4164 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4165 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4166 expect_pending_htlcs_forwardable!(nodes[1]);
4167 check_added_monitors!(nodes[1], 0);
4169 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4170 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();
4171 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4172 check_added_monitors!(nodes[1], 0);
4175 let mut block = Block {
4176 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4179 connect_block(&nodes[1], &block, 101);
4180 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4181 block.header.prev_blockhash = block.block_hash();
4182 connect_block(&nodes[1], &block, i);
4185 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4186 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4188 block.header.prev_blockhash = block.block_hash();
4189 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4192 expect_pending_htlcs_forwardable!(nodes[1]);
4193 check_added_monitors!(nodes[1], 1);
4194 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4195 assert_eq!(fail_commit.len(), 1);
4196 match fail_commit[0] {
4197 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4198 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4199 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4201 _ => unreachable!(),
4203 expect_payment_failed!(nodes[0], second_payment_hash, false);
4204 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4206 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4207 _ => panic!("Unexpected event"),
4210 panic!("Unexpected event");
4213 expect_payment_failed!(nodes[1], second_payment_hash, true);
4218 fn test_holding_cell_htlc_add_timeouts() {
4219 do_test_holding_cell_htlc_add_timeouts(false);
4220 do_test_holding_cell_htlc_add_timeouts(true);
4224 fn test_invalid_channel_announcement() {
4225 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4226 let secp_ctx = Secp256k1::new();
4227 let chanmon_cfgs = create_chanmon_cfgs(2);
4228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4230 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4232 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4234 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4235 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4236 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4237 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4239 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 } );
4241 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4242 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4244 let as_network_key = nodes[0].node.get_our_node_id();
4245 let bs_network_key = nodes[1].node.get_our_node_id();
4247 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4249 let mut chan_announcement;
4251 macro_rules! dummy_unsigned_msg {
4253 msgs::UnsignedChannelAnnouncement {
4254 features: ChannelFeatures::known(),
4255 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4256 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4257 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4258 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4259 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4260 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4261 excess_data: Vec::new(),
4266 macro_rules! sign_msg {
4267 ($unsigned_msg: expr) => {
4268 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4269 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4270 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4271 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4272 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4273 chan_announcement = msgs::ChannelAnnouncement {
4274 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4275 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4276 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4277 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4278 contents: $unsigned_msg
4283 let unsigned_msg = dummy_unsigned_msg!();
4284 sign_msg!(unsigned_msg);
4285 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4286 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 } );
4288 // Configured with Network::Testnet
4289 let mut unsigned_msg = dummy_unsigned_msg!();
4290 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4291 sign_msg!(unsigned_msg);
4292 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4294 let mut unsigned_msg = dummy_unsigned_msg!();
4295 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4296 sign_msg!(unsigned_msg);
4297 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4301 fn test_no_txn_manager_serialize_deserialize() {
4302 let chanmon_cfgs = create_chanmon_cfgs(2);
4303 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4304 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4305 let logger: test_utils::TestLogger;
4306 let fee_estimator: test_utils::TestFeeEstimator;
4307 let persister: test_utils::TestPersister;
4308 let new_chain_monitor: test_utils::TestChainMonitor;
4309 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4310 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4312 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4314 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4316 let nodes_0_serialized = nodes[0].node.encode();
4317 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4318 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4320 logger = test_utils::TestLogger::new();
4321 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4322 persister = test_utils::TestPersister::new();
4323 let keys_manager = &chanmon_cfgs[0].keys_manager;
4324 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4325 nodes[0].chain_monitor = &new_chain_monitor;
4326 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4327 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4328 &mut chan_0_monitor_read, keys_manager).unwrap();
4329 assert!(chan_0_monitor_read.is_empty());
4331 let mut nodes_0_read = &nodes_0_serialized[..];
4332 let config = UserConfig::default();
4333 let (_, nodes_0_deserialized_tmp) = {
4334 let mut channel_monitors = HashMap::new();
4335 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4336 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4337 default_config: config,
4339 fee_estimator: &fee_estimator,
4340 chain_monitor: nodes[0].chain_monitor,
4341 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4346 nodes_0_deserialized = nodes_0_deserialized_tmp;
4347 assert!(nodes_0_read.is_empty());
4349 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4350 nodes[0].node = &nodes_0_deserialized;
4351 assert_eq!(nodes[0].node.list_channels().len(), 1);
4352 check_added_monitors!(nodes[0], 1);
4354 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4355 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4356 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4357 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4359 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4360 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4361 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4362 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4364 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4365 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4366 for node in nodes.iter() {
4367 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4368 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4369 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4372 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4376 fn test_manager_serialize_deserialize_events() {
4377 // This test makes sure the events field in ChannelManager survives de/serialization
4378 let chanmon_cfgs = create_chanmon_cfgs(2);
4379 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4380 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4381 let fee_estimator: test_utils::TestFeeEstimator;
4382 let persister: test_utils::TestPersister;
4383 let logger: test_utils::TestLogger;
4384 let new_chain_monitor: test_utils::TestChainMonitor;
4385 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4386 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4388 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4389 let channel_value = 100000;
4390 let push_msat = 10001;
4391 let a_flags = InitFeatures::known();
4392 let b_flags = InitFeatures::known();
4393 let node_a = nodes.remove(0);
4394 let node_b = nodes.remove(0);
4395 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4396 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()));
4397 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()));
4399 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4401 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4402 check_added_monitors!(node_a, 0);
4404 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()));
4406 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4407 assert_eq!(added_monitors.len(), 1);
4408 assert_eq!(added_monitors[0].0, funding_output);
4409 added_monitors.clear();
4412 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()));
4414 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4415 assert_eq!(added_monitors.len(), 1);
4416 assert_eq!(added_monitors[0].0, funding_output);
4417 added_monitors.clear();
4419 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4424 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4425 let nodes_0_serialized = nodes[0].node.encode();
4426 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4427 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4429 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4430 logger = test_utils::TestLogger::new();
4431 persister = test_utils::TestPersister::new();
4432 let keys_manager = &chanmon_cfgs[0].keys_manager;
4433 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4434 nodes[0].chain_monitor = &new_chain_monitor;
4435 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4436 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4437 &mut chan_0_monitor_read, keys_manager).unwrap();
4438 assert!(chan_0_monitor_read.is_empty());
4440 let mut nodes_0_read = &nodes_0_serialized[..];
4441 let config = UserConfig::default();
4442 let (_, nodes_0_deserialized_tmp) = {
4443 let mut channel_monitors = HashMap::new();
4444 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4445 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4446 default_config: config,
4448 fee_estimator: &fee_estimator,
4449 chain_monitor: nodes[0].chain_monitor,
4450 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4455 nodes_0_deserialized = nodes_0_deserialized_tmp;
4456 assert!(nodes_0_read.is_empty());
4458 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4460 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4461 nodes[0].node = &nodes_0_deserialized;
4463 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4464 let events_4 = nodes[0].node.get_and_clear_pending_events();
4465 assert_eq!(events_4.len(), 1);
4467 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4468 assert_eq!(user_channel_id, 42);
4469 assert_eq!(*funding_txo, funding_output);
4471 _ => panic!("Unexpected event"),
4474 // Make sure the channel is functioning as though the de/serialization never happened
4475 assert_eq!(nodes[0].node.list_channels().len(), 1);
4476 check_added_monitors!(nodes[0], 1);
4478 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4479 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4480 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4481 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4483 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4484 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4485 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4486 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4488 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4489 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4490 for node in nodes.iter() {
4491 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4492 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4493 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4496 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4500 fn test_simple_manager_serialize_deserialize() {
4501 let chanmon_cfgs = create_chanmon_cfgs(2);
4502 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4503 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4504 let logger: test_utils::TestLogger;
4505 let fee_estimator: test_utils::TestFeeEstimator;
4506 let persister: test_utils::TestPersister;
4507 let new_chain_monitor: test_utils::TestChainMonitor;
4508 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4509 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4510 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4512 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4513 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4515 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4517 let nodes_0_serialized = nodes[0].node.encode();
4518 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4519 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4521 logger = test_utils::TestLogger::new();
4522 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4523 persister = test_utils::TestPersister::new();
4524 let keys_manager = &chanmon_cfgs[0].keys_manager;
4525 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4526 nodes[0].chain_monitor = &new_chain_monitor;
4527 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4528 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4529 &mut chan_0_monitor_read, keys_manager).unwrap();
4530 assert!(chan_0_monitor_read.is_empty());
4532 let mut nodes_0_read = &nodes_0_serialized[..];
4533 let (_, nodes_0_deserialized_tmp) = {
4534 let mut channel_monitors = HashMap::new();
4535 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4536 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4537 default_config: UserConfig::default(),
4539 fee_estimator: &fee_estimator,
4540 chain_monitor: nodes[0].chain_monitor,
4541 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4546 nodes_0_deserialized = nodes_0_deserialized_tmp;
4547 assert!(nodes_0_read.is_empty());
4549 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4550 nodes[0].node = &nodes_0_deserialized;
4551 check_added_monitors!(nodes[0], 1);
4553 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4555 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4556 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4560 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4561 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4562 let chanmon_cfgs = create_chanmon_cfgs(4);
4563 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4564 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4565 let logger: test_utils::TestLogger;
4566 let fee_estimator: test_utils::TestFeeEstimator;
4567 let persister: test_utils::TestPersister;
4568 let new_chain_monitor: test_utils::TestChainMonitor;
4569 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4570 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4571 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4572 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4573 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4575 let mut node_0_stale_monitors_serialized = Vec::new();
4576 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4577 let mut writer = test_utils::TestVecWriter(Vec::new());
4578 monitor.1.write(&mut writer).unwrap();
4579 node_0_stale_monitors_serialized.push(writer.0);
4582 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4584 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4585 let nodes_0_serialized = nodes[0].node.encode();
4587 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4588 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4589 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4590 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4592 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4594 let mut node_0_monitors_serialized = Vec::new();
4595 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter() {
4596 let mut writer = test_utils::TestVecWriter(Vec::new());
4597 monitor.1.write(&mut writer).unwrap();
4598 node_0_monitors_serialized.push(writer.0);
4601 logger = test_utils::TestLogger::new();
4602 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4603 persister = test_utils::TestPersister::new();
4604 let keys_manager = &chanmon_cfgs[0].keys_manager;
4605 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4606 nodes[0].chain_monitor = &new_chain_monitor;
4609 let mut node_0_stale_monitors = Vec::new();
4610 for serialized in node_0_stale_monitors_serialized.iter() {
4611 let mut read = &serialized[..];
4612 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4613 assert!(read.is_empty());
4614 node_0_stale_monitors.push(monitor);
4617 let mut node_0_monitors = Vec::new();
4618 for serialized in node_0_monitors_serialized.iter() {
4619 let mut read = &serialized[..];
4620 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4621 assert!(read.is_empty());
4622 node_0_monitors.push(monitor);
4625 let mut nodes_0_read = &nodes_0_serialized[..];
4626 if let Err(msgs::DecodeError::InvalidValue) =
4627 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4628 default_config: UserConfig::default(),
4630 fee_estimator: &fee_estimator,
4631 chain_monitor: nodes[0].chain_monitor,
4632 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4634 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4636 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4639 let mut nodes_0_read = &nodes_0_serialized[..];
4640 let (_, nodes_0_deserialized_tmp) =
4641 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4642 default_config: UserConfig::default(),
4644 fee_estimator: &fee_estimator,
4645 chain_monitor: nodes[0].chain_monitor,
4646 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4648 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4650 nodes_0_deserialized = nodes_0_deserialized_tmp;
4651 assert!(nodes_0_read.is_empty());
4653 { // Channel close should result in a commitment tx and an HTLC tx
4654 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4655 assert_eq!(txn.len(), 2);
4656 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4657 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4660 for monitor in node_0_monitors.drain(..) {
4661 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4662 check_added_monitors!(nodes[0], 1);
4664 nodes[0].node = &nodes_0_deserialized;
4666 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4667 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4668 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4669 //... and we can even still claim the payment!
4670 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4672 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4673 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4674 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4675 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4676 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4677 assert_eq!(msg_events.len(), 1);
4678 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4680 &ErrorAction::SendErrorMessage { ref msg } => {
4681 assert_eq!(msg.channel_id, channel_id);
4683 _ => panic!("Unexpected event!"),
4688 macro_rules! check_spendable_outputs {
4689 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4691 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4692 let mut txn = Vec::new();
4693 let mut all_outputs = Vec::new();
4694 let secp_ctx = Secp256k1::new();
4695 for event in events.drain(..) {
4697 Event::SpendableOutputs { mut outputs } => {
4698 for outp in outputs.drain(..) {
4699 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4700 all_outputs.push(outp);
4703 _ => panic!("Unexpected event"),
4706 if all_outputs.len() > 1 {
4707 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) {
4717 fn test_claim_sizeable_push_msat() {
4718 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4719 let chanmon_cfgs = create_chanmon_cfgs(2);
4720 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4721 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4722 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4724 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4725 nodes[1].node.force_close_channel(&chan.2).unwrap();
4726 check_closed_broadcast!(nodes[1], false);
4727 check_added_monitors!(nodes[1], 1);
4728 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4729 assert_eq!(node_txn.len(), 1);
4730 check_spends!(node_txn[0], chan.3);
4731 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
4733 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4734 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4735 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4737 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4738 assert_eq!(spend_txn.len(), 1);
4739 check_spends!(spend_txn[0], node_txn[0]);
4743 fn test_claim_on_remote_sizeable_push_msat() {
4744 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4745 // to_remote output is encumbered by a P2WPKH
4746 let chanmon_cfgs = create_chanmon_cfgs(2);
4747 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4748 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4749 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4751 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4752 nodes[0].node.force_close_channel(&chan.2).unwrap();
4753 check_closed_broadcast!(nodes[0], false);
4754 check_added_monitors!(nodes[0], 1);
4756 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4757 assert_eq!(node_txn.len(), 1);
4758 check_spends!(node_txn[0], chan.3);
4759 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
4761 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4762 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4763 check_closed_broadcast!(nodes[1], false);
4764 check_added_monitors!(nodes[1], 1);
4765 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4767 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4768 assert_eq!(spend_txn.len(), 1);
4769 check_spends!(spend_txn[0], node_txn[0]);
4773 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4774 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4775 // to_remote output is encumbered by a P2WPKH
4777 let chanmon_cfgs = create_chanmon_cfgs(2);
4778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4780 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4782 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4783 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4784 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4785 assert_eq!(revoked_local_txn[0].input.len(), 1);
4786 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4788 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4789 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4790 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4791 check_closed_broadcast!(nodes[1], false);
4792 check_added_monitors!(nodes[1], 1);
4794 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4795 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4796 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4797 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4799 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4800 assert_eq!(spend_txn.len(), 3);
4801 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4802 check_spends!(spend_txn[1], node_txn[0]);
4803 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4807 fn test_static_spendable_outputs_preimage_tx() {
4808 let chanmon_cfgs = create_chanmon_cfgs(2);
4809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4811 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4813 // Create some initial channels
4814 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4816 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4818 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4819 assert_eq!(commitment_tx[0].input.len(), 1);
4820 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4822 // Settle A's commitment tx on B's chain
4823 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4824 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4825 check_added_monitors!(nodes[1], 1);
4826 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4827 check_added_monitors!(nodes[1], 1);
4828 let events = nodes[1].node.get_and_clear_pending_msg_events();
4830 MessageSendEvent::UpdateHTLCs { .. } => {},
4831 _ => panic!("Unexpected event"),
4834 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4835 _ => panic!("Unexepected event"),
4838 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4839 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4840 assert_eq!(node_txn.len(), 3);
4841 check_spends!(node_txn[0], commitment_tx[0]);
4842 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4843 check_spends!(node_txn[1], chan_1.3);
4844 check_spends!(node_txn[2], node_txn[1]);
4846 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4847 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4848 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4850 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4851 assert_eq!(spend_txn.len(), 1);
4852 check_spends!(spend_txn[0], node_txn[0]);
4856 fn test_static_spendable_outputs_timeout_tx() {
4857 let chanmon_cfgs = create_chanmon_cfgs(2);
4858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4862 // Create some initial channels
4863 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4865 // Rebalance the network a bit by relaying one payment through all the channels ...
4866 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4868 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4870 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4871 assert_eq!(commitment_tx[0].input.len(), 1);
4872 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4874 // Settle A's commitment tx on B' chain
4875 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4876 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4877 check_added_monitors!(nodes[1], 1);
4878 let events = nodes[1].node.get_and_clear_pending_msg_events();
4880 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4881 _ => panic!("Unexpected event"),
4884 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4885 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4886 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4887 check_spends!(node_txn[0], commitment_tx[0].clone());
4888 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4889 check_spends!(node_txn[1], chan_1.3.clone());
4890 check_spends!(node_txn[2], node_txn[1]);
4892 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4893 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4894 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4895 expect_payment_failed!(nodes[1], our_payment_hash, true);
4897 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4898 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4899 check_spends!(spend_txn[0], commitment_tx[0]);
4900 check_spends!(spend_txn[1], node_txn[0]);
4901 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4905 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4906 let chanmon_cfgs = create_chanmon_cfgs(2);
4907 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4908 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4909 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4911 // Create some initial channels
4912 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4914 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4915 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4916 assert_eq!(revoked_local_txn[0].input.len(), 1);
4917 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4919 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4921 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4922 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4923 check_closed_broadcast!(nodes[1], false);
4924 check_added_monitors!(nodes[1], 1);
4926 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4927 assert_eq!(node_txn.len(), 2);
4928 assert_eq!(node_txn[0].input.len(), 2);
4929 check_spends!(node_txn[0], revoked_local_txn[0]);
4931 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4932 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4933 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4935 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4936 assert_eq!(spend_txn.len(), 1);
4937 check_spends!(spend_txn[0], node_txn[0]);
4941 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4942 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4943 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4946 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4948 // Create some initial channels
4949 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4951 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4952 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4953 assert_eq!(revoked_local_txn[0].input.len(), 1);
4954 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4956 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4958 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4959 // A will generate HTLC-Timeout from revoked commitment tx
4960 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4961 check_closed_broadcast!(nodes[0], false);
4962 check_added_monitors!(nodes[0], 1);
4964 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4965 assert_eq!(revoked_htlc_txn.len(), 2);
4966 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4967 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4968 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4969 check_spends!(revoked_htlc_txn[1], chan_1.3);
4971 // B will generate justice tx from A's revoked commitment/HTLC tx
4972 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4973 check_closed_broadcast!(nodes[1], false);
4974 check_added_monitors!(nodes[1], 1);
4976 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4977 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4978 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4979 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4980 // transactions next...
4981 assert_eq!(node_txn[0].input.len(), 3);
4982 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4984 assert_eq!(node_txn[1].input.len(), 2);
4985 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4986 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4987 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4989 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4990 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4993 assert_eq!(node_txn[2].input.len(), 1);
4994 check_spends!(node_txn[2], chan_1.3);
4996 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4997 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
4998 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5000 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5001 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5002 assert_eq!(spend_txn.len(), 1);
5003 assert_eq!(spend_txn[0].input.len(), 1);
5004 check_spends!(spend_txn[0], node_txn[1]);
5008 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5009 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5010 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5011 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5012 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5013 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5015 // Create some initial channels
5016 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5018 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5019 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5020 assert_eq!(revoked_local_txn[0].input.len(), 1);
5021 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5023 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5024 assert_eq!(revoked_local_txn[0].output.len(), 2);
5026 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5028 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5029 // B will generate HTLC-Success from revoked commitment tx
5030 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5031 check_closed_broadcast!(nodes[1], false);
5032 check_added_monitors!(nodes[1], 1);
5033 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5035 assert_eq!(revoked_htlc_txn.len(), 2);
5036 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5037 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5038 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5040 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5041 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5042 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5044 // A will generate justice tx from B's revoked commitment/HTLC tx
5045 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5046 check_closed_broadcast!(nodes[0], false);
5047 check_added_monitors!(nodes[0], 1);
5049 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5050 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5052 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5053 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5054 // transactions next...
5055 assert_eq!(node_txn[0].input.len(), 2);
5056 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5057 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5058 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5060 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5061 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5064 assert_eq!(node_txn[1].input.len(), 1);
5065 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5067 check_spends!(node_txn[2], chan_1.3);
5069 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5070 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5071 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5073 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5074 // didn't try to generate any new transactions.
5076 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5077 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5078 assert_eq!(spend_txn.len(), 3);
5079 assert_eq!(spend_txn[0].input.len(), 1);
5080 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5081 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5082 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5083 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5087 fn test_onchain_to_onchain_claim() {
5088 // Test that in case of channel closure, we detect the state of output and claim HTLC
5089 // on downstream peer's remote commitment tx.
5090 // First, have C claim an HTLC against its own latest commitment transaction.
5091 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5093 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5096 let chanmon_cfgs = create_chanmon_cfgs(3);
5097 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5098 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5099 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5101 // Create some initial channels
5102 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5105 // Rebalance the network a bit by relaying one payment through all the channels ...
5106 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5107 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5109 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5110 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5111 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5112 check_spends!(commitment_tx[0], chan_2.3);
5113 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5114 check_added_monitors!(nodes[2], 1);
5115 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5116 assert!(updates.update_add_htlcs.is_empty());
5117 assert!(updates.update_fail_htlcs.is_empty());
5118 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5119 assert!(updates.update_fail_malformed_htlcs.is_empty());
5121 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5122 check_closed_broadcast!(nodes[2], false);
5123 check_added_monitors!(nodes[2], 1);
5125 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5126 assert_eq!(c_txn.len(), 3);
5127 assert_eq!(c_txn[0], c_txn[2]);
5128 assert_eq!(commitment_tx[0], c_txn[1]);
5129 check_spends!(c_txn[1], chan_2.3);
5130 check_spends!(c_txn[2], c_txn[1]);
5131 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5132 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5133 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5134 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5136 // 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
5137 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5139 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5140 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5141 assert_eq!(b_txn.len(), 3);
5142 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5143 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5144 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5145 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5146 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5147 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5148 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5149 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5150 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5153 check_added_monitors!(nodes[1], 1);
5154 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5155 check_added_monitors!(nodes[1], 1);
5156 match msg_events[0] {
5157 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5158 _ => panic!("Unexpected event"),
5160 match msg_events[1] {
5161 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, .. } } => {
5162 assert!(update_add_htlcs.is_empty());
5163 assert!(update_fail_htlcs.is_empty());
5164 assert_eq!(update_fulfill_htlcs.len(), 1);
5165 assert!(update_fail_malformed_htlcs.is_empty());
5166 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5168 _ => panic!("Unexpected event"),
5170 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5171 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5172 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5173 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5174 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5175 assert_eq!(b_txn.len(), 3);
5176 check_spends!(b_txn[1], chan_1.3);
5177 check_spends!(b_txn[2], b_txn[1]);
5178 check_spends!(b_txn[0], commitment_tx[0]);
5179 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5180 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5181 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5183 check_closed_broadcast!(nodes[1], false);
5184 check_added_monitors!(nodes[1], 1);
5188 fn test_duplicate_payment_hash_one_failure_one_success() {
5189 // Topology : A --> B --> C
5190 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5191 let chanmon_cfgs = create_chanmon_cfgs(3);
5192 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5193 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5194 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5196 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5197 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5199 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5200 *nodes[0].network_payment_count.borrow_mut() -= 1;
5201 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5203 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5204 assert_eq!(commitment_txn[0].input.len(), 1);
5205 check_spends!(commitment_txn[0], chan_2.3);
5207 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5208 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5209 check_closed_broadcast!(nodes[1], false);
5210 check_added_monitors!(nodes[1], 1);
5212 let htlc_timeout_tx;
5213 { // Extract one of the two HTLC-Timeout transaction
5214 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5215 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5216 assert_eq!(node_txn.len(), 5);
5217 check_spends!(node_txn[0], commitment_txn[0]);
5218 assert_eq!(node_txn[0].input.len(), 1);
5219 check_spends!(node_txn[1], commitment_txn[0]);
5220 assert_eq!(node_txn[1].input.len(), 1);
5221 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5222 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5223 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5224 check_spends!(node_txn[2], chan_2.3);
5225 check_spends!(node_txn[3], node_txn[2]);
5226 check_spends!(node_txn[4], node_txn[2]);
5227 htlc_timeout_tx = node_txn[1].clone();
5230 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5231 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5232 check_added_monitors!(nodes[2], 3);
5233 let events = nodes[2].node.get_and_clear_pending_msg_events();
5235 MessageSendEvent::UpdateHTLCs { .. } => {},
5236 _ => panic!("Unexpected event"),
5239 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5240 _ => panic!("Unexepected event"),
5242 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5243 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)
5244 check_spends!(htlc_success_txn[2], chan_2.3);
5245 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5246 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5247 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5248 assert_eq!(htlc_success_txn[0].input.len(), 1);
5249 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5250 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5251 assert_eq!(htlc_success_txn[1].input.len(), 1);
5252 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5253 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5254 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5255 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5257 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5258 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5259 expect_pending_htlcs_forwardable!(nodes[1]);
5260 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5261 assert!(htlc_updates.update_add_htlcs.is_empty());
5262 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5263 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5264 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5265 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5266 check_added_monitors!(nodes[1], 1);
5268 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5269 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5271 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5272 let events = nodes[0].node.get_and_clear_pending_msg_events();
5273 assert_eq!(events.len(), 1);
5275 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5277 _ => { panic!("Unexpected event"); }
5280 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5282 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5283 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5284 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5285 assert!(updates.update_add_htlcs.is_empty());
5286 assert!(updates.update_fail_htlcs.is_empty());
5287 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5288 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5289 assert!(updates.update_fail_malformed_htlcs.is_empty());
5290 check_added_monitors!(nodes[1], 1);
5292 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5293 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5295 let events = nodes[0].node.get_and_clear_pending_events();
5297 Event::PaymentSent { ref payment_preimage } => {
5298 assert_eq!(*payment_preimage, our_payment_preimage);
5300 _ => panic!("Unexpected event"),
5305 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5306 let chanmon_cfgs = create_chanmon_cfgs(2);
5307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5309 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5311 // Create some initial channels
5312 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5314 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5315 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5316 assert_eq!(local_txn.len(), 1);
5317 assert_eq!(local_txn[0].input.len(), 1);
5318 check_spends!(local_txn[0], chan_1.3);
5320 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5321 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5322 check_added_monitors!(nodes[1], 1);
5323 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5324 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5325 check_added_monitors!(nodes[1], 1);
5326 let events = nodes[1].node.get_and_clear_pending_msg_events();
5328 MessageSendEvent::UpdateHTLCs { .. } => {},
5329 _ => panic!("Unexpected event"),
5332 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5333 _ => panic!("Unexepected event"),
5336 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5337 assert_eq!(node_txn.len(), 3);
5338 assert_eq!(node_txn[0], node_txn[2]);
5339 assert_eq!(node_txn[1], local_txn[0]);
5340 assert_eq!(node_txn[0].input.len(), 1);
5341 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5342 check_spends!(node_txn[0], local_txn[0]);
5343 vec![node_txn[0].clone()]
5346 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5347 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5348 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5350 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5351 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5352 assert_eq!(spend_txn.len(), 1);
5353 check_spends!(spend_txn[0], node_txn[0]);
5356 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5357 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5358 // unrevoked commitment transaction.
5359 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5360 // a remote RAA before they could be failed backwards (and combinations thereof).
5361 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5362 // use the same payment hashes.
5363 // Thus, we use a six-node network:
5368 // And test where C fails back to A/B when D announces its latest commitment transaction
5369 let chanmon_cfgs = create_chanmon_cfgs(6);
5370 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5371 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5372 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5373 let logger = test_utils::TestLogger::new();
5375 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5376 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5377 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5378 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5379 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5381 // Rebalance and check output sanity...
5382 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5383 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5384 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5386 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5388 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
5390 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
5391 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5392 let our_node_id = &nodes[1].node.get_our_node_id();
5393 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();
5395 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
5397 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
5399 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5401 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5402 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();
5404 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5406 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5409 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5411 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();
5412 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
5415 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
5417 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();
5418 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5420 // Double-check that six of the new HTLC were added
5421 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5422 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5423 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5424 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5426 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5427 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5428 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5429 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5430 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5431 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5432 check_added_monitors!(nodes[4], 0);
5433 expect_pending_htlcs_forwardable!(nodes[4]);
5434 check_added_monitors!(nodes[4], 1);
5436 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5437 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5438 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5439 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5440 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5441 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5443 // Fail 3rd below-dust and 7th above-dust HTLCs
5444 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5445 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5446 check_added_monitors!(nodes[5], 0);
5447 expect_pending_htlcs_forwardable!(nodes[5]);
5448 check_added_monitors!(nodes[5], 1);
5450 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5451 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5452 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5453 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5455 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5457 expect_pending_htlcs_forwardable!(nodes[3]);
5458 check_added_monitors!(nodes[3], 1);
5459 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5460 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5461 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5462 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5463 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5464 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5465 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5466 if deliver_last_raa {
5467 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5469 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5472 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5473 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5474 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5475 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5477 // We now broadcast the latest commitment transaction, which *should* result in failures for
5478 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5479 // the non-broadcast above-dust HTLCs.
5481 // Alternatively, we may broadcast the previous commitment transaction, which should only
5482 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5483 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5485 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5486 if announce_latest {
5487 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5489 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5491 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5492 check_closed_broadcast!(nodes[2], false);
5493 expect_pending_htlcs_forwardable!(nodes[2]);
5494 check_added_monitors!(nodes[2], 3);
5496 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5497 assert_eq!(cs_msgs.len(), 2);
5498 let mut a_done = false;
5499 for msg in cs_msgs {
5501 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5502 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5503 // should be failed-backwards here.
5504 let target = if *node_id == nodes[0].node.get_our_node_id() {
5505 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5506 for htlc in &updates.update_fail_htlcs {
5507 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 });
5509 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5514 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5515 for htlc in &updates.update_fail_htlcs {
5516 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5518 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5519 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5522 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5523 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5524 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5525 if announce_latest {
5526 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5527 if *node_id == nodes[0].node.get_our_node_id() {
5528 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5531 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5533 _ => panic!("Unexpected event"),
5537 let as_events = nodes[0].node.get_and_clear_pending_events();
5538 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5539 let mut as_failds = HashSet::new();
5540 for event in as_events.iter() {
5541 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5542 assert!(as_failds.insert(*payment_hash));
5543 if *payment_hash != payment_hash_2 {
5544 assert_eq!(*rejected_by_dest, deliver_last_raa);
5546 assert!(!rejected_by_dest);
5548 } else { panic!("Unexpected event"); }
5550 assert!(as_failds.contains(&payment_hash_1));
5551 assert!(as_failds.contains(&payment_hash_2));
5552 if announce_latest {
5553 assert!(as_failds.contains(&payment_hash_3));
5554 assert!(as_failds.contains(&payment_hash_5));
5556 assert!(as_failds.contains(&payment_hash_6));
5558 let bs_events = nodes[1].node.get_and_clear_pending_events();
5559 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5560 let mut bs_failds = HashSet::new();
5561 for event in bs_events.iter() {
5562 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5563 assert!(bs_failds.insert(*payment_hash));
5564 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5565 assert_eq!(*rejected_by_dest, deliver_last_raa);
5567 assert!(!rejected_by_dest);
5569 } else { panic!("Unexpected event"); }
5571 assert!(bs_failds.contains(&payment_hash_1));
5572 assert!(bs_failds.contains(&payment_hash_2));
5573 if announce_latest {
5574 assert!(bs_failds.contains(&payment_hash_4));
5576 assert!(bs_failds.contains(&payment_hash_5));
5578 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5579 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5580 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5581 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5582 // PaymentFailureNetworkUpdates.
5583 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5584 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5585 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5586 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5587 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5589 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5590 _ => panic!("Unexpected event"),
5596 fn test_fail_backwards_latest_remote_announce_a() {
5597 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5601 fn test_fail_backwards_latest_remote_announce_b() {
5602 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5606 fn test_fail_backwards_previous_remote_announce() {
5607 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5608 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5609 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5613 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5614 let chanmon_cfgs = create_chanmon_cfgs(2);
5615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5617 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5619 // Create some initial channels
5620 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5622 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5623 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5624 assert_eq!(local_txn[0].input.len(), 1);
5625 check_spends!(local_txn[0], chan_1.3);
5627 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5628 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5629 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5630 check_closed_broadcast!(nodes[0], false);
5631 check_added_monitors!(nodes[0], 1);
5633 let htlc_timeout = {
5634 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5635 assert_eq!(node_txn[0].input.len(), 1);
5636 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5637 check_spends!(node_txn[0], local_txn[0]);
5641 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5642 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5643 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5644 expect_payment_failed!(nodes[0], our_payment_hash, true);
5646 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5647 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5648 assert_eq!(spend_txn.len(), 3);
5649 check_spends!(spend_txn[0], local_txn[0]);
5650 check_spends!(spend_txn[1], htlc_timeout);
5651 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5655 fn test_key_derivation_params() {
5656 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5657 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5658 // let us re-derive the channel key set to then derive a delayed_payment_key.
5660 let chanmon_cfgs = create_chanmon_cfgs(3);
5662 // We manually create the node configuration to backup the seed.
5663 let seed = [42; 32];
5664 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5665 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);
5666 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 };
5667 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5668 node_cfgs.remove(0);
5669 node_cfgs.insert(0, node);
5671 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5672 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5674 // Create some initial channels
5675 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5677 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5678 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5679 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5681 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5682 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5683 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5684 assert_eq!(local_txn_1[0].input.len(), 1);
5685 check_spends!(local_txn_1[0], chan_1.3);
5687 // We check funding pubkey are unique
5688 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]));
5689 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]));
5690 if from_0_funding_key_0 == from_1_funding_key_0
5691 || from_0_funding_key_0 == from_1_funding_key_1
5692 || from_0_funding_key_1 == from_1_funding_key_0
5693 || from_0_funding_key_1 == from_1_funding_key_1 {
5694 panic!("Funding pubkeys aren't unique");
5697 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5698 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5699 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5700 check_closed_broadcast!(nodes[0], false);
5701 check_added_monitors!(nodes[0], 1);
5703 let htlc_timeout = {
5704 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5705 assert_eq!(node_txn[0].input.len(), 1);
5706 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5707 check_spends!(node_txn[0], local_txn_1[0]);
5711 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5712 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5713 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5714 expect_payment_failed!(nodes[0], our_payment_hash, true);
5716 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5717 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5718 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5719 assert_eq!(spend_txn.len(), 3);
5720 check_spends!(spend_txn[0], local_txn_1[0]);
5721 check_spends!(spend_txn[1], htlc_timeout);
5722 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5726 fn test_static_output_closing_tx() {
5727 let chanmon_cfgs = create_chanmon_cfgs(2);
5728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5732 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5734 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5735 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5737 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5738 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5739 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5741 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5742 assert_eq!(spend_txn.len(), 1);
5743 check_spends!(spend_txn[0], closing_tx);
5745 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5746 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5748 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5749 assert_eq!(spend_txn.len(), 1);
5750 check_spends!(spend_txn[0], closing_tx);
5753 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5754 let chanmon_cfgs = create_chanmon_cfgs(2);
5755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5757 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5758 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5760 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5762 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5763 // present in B's local commitment transaction, but none of A's commitment transactions.
5764 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5765 check_added_monitors!(nodes[1], 1);
5767 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5768 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5769 let events = nodes[0].node.get_and_clear_pending_events();
5770 assert_eq!(events.len(), 1);
5772 Event::PaymentSent { payment_preimage } => {
5773 assert_eq!(payment_preimage, our_payment_preimage);
5775 _ => panic!("Unexpected event"),
5778 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5779 check_added_monitors!(nodes[0], 1);
5780 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5781 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5782 check_added_monitors!(nodes[1], 1);
5784 let mut block = Block {
5785 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5788 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5789 connect_block(&nodes[1], &block, i);
5790 block.header.prev_blockhash = block.block_hash();
5792 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5793 check_closed_broadcast!(nodes[1], false);
5794 check_added_monitors!(nodes[1], 1);
5797 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5798 let chanmon_cfgs = create_chanmon_cfgs(2);
5799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5801 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5802 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5803 let logger = test_utils::TestLogger::new();
5805 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5806 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5807 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();
5808 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5809 check_added_monitors!(nodes[0], 1);
5811 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5813 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5814 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5815 // to "time out" the HTLC.
5817 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5819 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5820 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5821 header.prev_blockhash = header.block_hash();
5823 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5824 check_closed_broadcast!(nodes[0], false);
5825 check_added_monitors!(nodes[0], 1);
5828 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5829 let chanmon_cfgs = create_chanmon_cfgs(3);
5830 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5831 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5832 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5833 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5835 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5836 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5837 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5838 // actually revoked.
5839 let htlc_value = if use_dust { 50000 } else { 3000000 };
5840 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5841 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5842 expect_pending_htlcs_forwardable!(nodes[1]);
5843 check_added_monitors!(nodes[1], 1);
5845 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5846 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5847 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5848 check_added_monitors!(nodes[0], 1);
5849 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5850 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5851 check_added_monitors!(nodes[1], 1);
5852 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5853 check_added_monitors!(nodes[1], 1);
5854 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5856 if check_revoke_no_close {
5857 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5858 check_added_monitors!(nodes[0], 1);
5861 let mut block = Block {
5862 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5865 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5866 connect_block(&nodes[0], &block, i);
5867 block.header.prev_blockhash = block.block_hash();
5869 if !check_revoke_no_close {
5870 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5871 check_closed_broadcast!(nodes[0], false);
5872 check_added_monitors!(nodes[0], 1);
5874 expect_payment_failed!(nodes[0], our_payment_hash, true);
5878 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5879 // There are only a few cases to test here:
5880 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5881 // broadcastable commitment transactions result in channel closure,
5882 // * its included in an unrevoked-but-previous remote commitment transaction,
5883 // * its included in the latest remote or local commitment transactions.
5884 // We test each of the three possible commitment transactions individually and use both dust and
5886 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5887 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5888 // tested for at least one of the cases in other tests.
5890 fn htlc_claim_single_commitment_only_a() {
5891 do_htlc_claim_local_commitment_only(true);
5892 do_htlc_claim_local_commitment_only(false);
5894 do_htlc_claim_current_remote_commitment_only(true);
5895 do_htlc_claim_current_remote_commitment_only(false);
5899 fn htlc_claim_single_commitment_only_b() {
5900 do_htlc_claim_previous_remote_commitment_only(true, false);
5901 do_htlc_claim_previous_remote_commitment_only(false, false);
5902 do_htlc_claim_previous_remote_commitment_only(true, true);
5903 do_htlc_claim_previous_remote_commitment_only(false, true);
5908 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5909 let chanmon_cfgs = create_chanmon_cfgs(2);
5910 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5911 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5912 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5913 //Force duplicate channel ids
5914 for node in nodes.iter() {
5915 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5918 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5919 let channel_value_satoshis=10000;
5920 let push_msat=10001;
5921 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5922 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5923 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5925 //Create a second channel with a channel_id collision
5926 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5930 fn bolt2_open_channel_sending_node_checks_part2() {
5931 let chanmon_cfgs = create_chanmon_cfgs(2);
5932 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5933 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5934 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5936 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5937 let channel_value_satoshis=2^24;
5938 let push_msat=10001;
5939 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5941 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5942 let channel_value_satoshis=10000;
5943 // Test when push_msat is equal to 1000 * funding_satoshis.
5944 let push_msat=1000*channel_value_satoshis+1;
5945 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5947 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5948 let channel_value_satoshis=10000;
5949 let push_msat=10001;
5950 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
5951 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5952 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5954 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5955 // 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
5956 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5958 // 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.
5959 assert!(BREAKDOWN_TIMEOUT>0);
5960 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5962 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5963 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5964 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5966 // 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.
5967 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5968 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5969 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5970 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5971 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5974 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5975 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5976 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5977 // is no longer affordable once it's freed.
5979 fn test_fail_holding_cell_htlc_upon_free() {
5980 let chanmon_cfgs = create_chanmon_cfgs(2);
5981 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5982 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5983 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5984 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5985 let logger = test_utils::TestLogger::new();
5987 // First nodes[0] generates an update_fee, setting the channel's
5988 // pending_update_fee.
5989 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5990 check_added_monitors!(nodes[0], 1);
5992 let events = nodes[0].node.get_and_clear_pending_msg_events();
5993 assert_eq!(events.len(), 1);
5994 let (update_msg, commitment_signed) = match events[0] {
5995 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5996 (update_fee.as_ref(), commitment_signed)
5998 _ => panic!("Unexpected event"),
6001 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6003 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6004 let channel_reserve = chan_stat.channel_reserve_msat;
6005 let feerate = get_feerate!(nodes[0], chan.2);
6007 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6008 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6009 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6010 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6011 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();
6013 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6014 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6015 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6016 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6018 // Flush the pending fee update.
6019 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6020 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6021 check_added_monitors!(nodes[1], 1);
6022 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6023 check_added_monitors!(nodes[0], 1);
6025 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6026 // HTLC, but now that the fee has been raised the payment will now fail, causing
6027 // us to surface its failure to the user.
6028 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6029 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6030 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6031 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);
6032 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6034 // Check that the payment failed to be sent out.
6035 let events = nodes[0].node.get_and_clear_pending_events();
6036 assert_eq!(events.len(), 1);
6038 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6039 assert_eq!(our_payment_hash.clone(), *payment_hash);
6040 assert_eq!(*rejected_by_dest, false);
6041 assert_eq!(*error_code, None);
6042 assert_eq!(*error_data, None);
6044 _ => panic!("Unexpected event"),
6048 // Test that if multiple HTLCs are released from the holding cell and one is
6049 // valid but the other is no longer valid upon release, the valid HTLC can be
6050 // successfully completed while the other one fails as expected.
6052 fn test_free_and_fail_holding_cell_htlcs() {
6053 let chanmon_cfgs = create_chanmon_cfgs(2);
6054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6056 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6057 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6058 let logger = test_utils::TestLogger::new();
6060 // First nodes[0] generates an update_fee, setting the channel's
6061 // pending_update_fee.
6062 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6063 check_added_monitors!(nodes[0], 1);
6065 let events = nodes[0].node.get_and_clear_pending_msg_events();
6066 assert_eq!(events.len(), 1);
6067 let (update_msg, commitment_signed) = match events[0] {
6068 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6069 (update_fee.as_ref(), commitment_signed)
6071 _ => panic!("Unexpected event"),
6074 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6076 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6077 let channel_reserve = chan_stat.channel_reserve_msat;
6078 let feerate = get_feerate!(nodes[0], chan.2);
6080 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6081 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6083 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6084 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6085 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6086 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();
6087 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();
6089 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6090 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6091 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6092 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6093 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6094 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6095 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6097 // Flush the pending fee update.
6098 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6099 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6100 check_added_monitors!(nodes[1], 1);
6101 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6102 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6103 check_added_monitors!(nodes[0], 2);
6105 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6106 // but now that the fee has been raised the second payment will now fail, causing us
6107 // to surface its failure to the user. The first payment should succeed.
6108 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6109 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6110 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6111 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);
6112 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6114 // Check that the second payment failed to be sent out.
6115 let events = nodes[0].node.get_and_clear_pending_events();
6116 assert_eq!(events.len(), 1);
6118 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6119 assert_eq!(payment_hash_2.clone(), *payment_hash);
6120 assert_eq!(*rejected_by_dest, false);
6121 assert_eq!(*error_code, None);
6122 assert_eq!(*error_data, None);
6124 _ => panic!("Unexpected event"),
6127 // Complete the first payment and the RAA from the fee update.
6128 let (payment_event, send_raa_event) = {
6129 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6130 assert_eq!(msgs.len(), 2);
6131 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6133 let raa = match send_raa_event {
6134 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6135 _ => panic!("Unexpected event"),
6137 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6138 check_added_monitors!(nodes[1], 1);
6139 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6140 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6141 let events = nodes[1].node.get_and_clear_pending_events();
6142 assert_eq!(events.len(), 1);
6144 Event::PendingHTLCsForwardable { .. } => {},
6145 _ => panic!("Unexpected event"),
6147 nodes[1].node.process_pending_htlc_forwards();
6148 let events = nodes[1].node.get_and_clear_pending_events();
6149 assert_eq!(events.len(), 1);
6151 Event::PaymentReceived { .. } => {},
6152 _ => panic!("Unexpected event"),
6154 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6155 check_added_monitors!(nodes[1], 1);
6156 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6157 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6158 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6159 let events = nodes[0].node.get_and_clear_pending_events();
6160 assert_eq!(events.len(), 1);
6162 Event::PaymentSent { ref payment_preimage } => {
6163 assert_eq!(*payment_preimage, payment_preimage_1);
6165 _ => panic!("Unexpected event"),
6169 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6170 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6171 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6174 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6175 let chanmon_cfgs = create_chanmon_cfgs(3);
6176 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6177 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6178 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6179 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6180 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6181 let logger = test_utils::TestLogger::new();
6183 // First nodes[1] generates an update_fee, setting the channel's
6184 // pending_update_fee.
6185 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6186 check_added_monitors!(nodes[1], 1);
6188 let events = nodes[1].node.get_and_clear_pending_msg_events();
6189 assert_eq!(events.len(), 1);
6190 let (update_msg, commitment_signed) = match events[0] {
6191 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6192 (update_fee.as_ref(), commitment_signed)
6194 _ => panic!("Unexpected event"),
6197 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6199 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6200 let channel_reserve = chan_stat.channel_reserve_msat;
6201 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6203 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6205 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6206 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6207 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6208 let payment_event = {
6209 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6210 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();
6211 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6212 check_added_monitors!(nodes[0], 1);
6214 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6215 assert_eq!(events.len(), 1);
6217 SendEvent::from_event(events.remove(0))
6219 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6220 check_added_monitors!(nodes[1], 0);
6221 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6222 expect_pending_htlcs_forwardable!(nodes[1]);
6224 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6225 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6227 // Flush the pending fee update.
6228 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6229 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6230 check_added_monitors!(nodes[2], 1);
6231 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6232 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6233 check_added_monitors!(nodes[1], 2);
6235 // A final RAA message is generated to finalize the fee update.
6236 let events = nodes[1].node.get_and_clear_pending_msg_events();
6237 assert_eq!(events.len(), 1);
6239 let raa_msg = match &events[0] {
6240 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6243 _ => panic!("Unexpected event"),
6246 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6247 check_added_monitors!(nodes[2], 1);
6248 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6250 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6251 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6252 assert_eq!(process_htlc_forwards_event.len(), 1);
6253 match &process_htlc_forwards_event[0] {
6254 &Event::PendingHTLCsForwardable { .. } => {},
6255 _ => panic!("Unexpected event"),
6258 // In response, we call ChannelManager's process_pending_htlc_forwards
6259 nodes[1].node.process_pending_htlc_forwards();
6260 check_added_monitors!(nodes[1], 1);
6262 // This causes the HTLC to be failed backwards.
6263 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6264 assert_eq!(fail_event.len(), 1);
6265 let (fail_msg, commitment_signed) = match &fail_event[0] {
6266 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6267 assert_eq!(updates.update_add_htlcs.len(), 0);
6268 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6269 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6270 assert_eq!(updates.update_fail_htlcs.len(), 1);
6271 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6273 _ => panic!("Unexpected event"),
6276 // Pass the failure messages back to nodes[0].
6277 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6278 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6280 // Complete the HTLC failure+removal process.
6281 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6282 check_added_monitors!(nodes[0], 1);
6283 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6284 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6285 check_added_monitors!(nodes[1], 2);
6286 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6287 assert_eq!(final_raa_event.len(), 1);
6288 let raa = match &final_raa_event[0] {
6289 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6290 _ => panic!("Unexpected event"),
6292 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6293 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6294 assert_eq!(fail_msg_event.len(), 1);
6295 match &fail_msg_event[0] {
6296 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6297 _ => panic!("Unexpected event"),
6299 let failure_event = nodes[0].node.get_and_clear_pending_events();
6300 assert_eq!(failure_event.len(), 1);
6301 match &failure_event[0] {
6302 &Event::PaymentFailed { rejected_by_dest, .. } => {
6303 assert!(!rejected_by_dest);
6305 _ => panic!("Unexpected event"),
6307 check_added_monitors!(nodes[0], 1);
6310 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6311 // 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.
6312 //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.
6315 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6316 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6317 let chanmon_cfgs = create_chanmon_cfgs(2);
6318 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6319 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6320 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6321 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6323 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6324 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6325 let logger = test_utils::TestLogger::new();
6326 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6327 route.paths[0][0].fee_msat = 100;
6329 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6330 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6331 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6332 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6336 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6337 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6338 let chanmon_cfgs = create_chanmon_cfgs(2);
6339 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6340 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6341 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6342 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6343 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6345 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6346 let logger = test_utils::TestLogger::new();
6347 let 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();
6348 route.paths[0][0].fee_msat = 0;
6349 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6350 assert_eq!(err, "Cannot send 0-msat HTLC"));
6352 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6353 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6357 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6358 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6359 let chanmon_cfgs = create_chanmon_cfgs(2);
6360 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6361 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6362 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6363 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6365 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6366 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6367 let logger = test_utils::TestLogger::new();
6368 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();
6369 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6370 check_added_monitors!(nodes[0], 1);
6371 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6372 updates.update_add_htlcs[0].amount_msat = 0;
6374 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6375 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6376 check_closed_broadcast!(nodes[1], true).unwrap();
6377 check_added_monitors!(nodes[1], 1);
6381 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6382 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6383 //It is enforced when constructing a route.
6384 let chanmon_cfgs = create_chanmon_cfgs(2);
6385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6387 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6388 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6389 let logger = test_utils::TestLogger::new();
6391 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6393 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6394 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();
6395 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6396 assert_eq!(err, &"Channel CLTV overflowed?"));
6400 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6401 //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.
6402 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6403 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6404 let chanmon_cfgs = create_chanmon_cfgs(2);
6405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6407 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6408 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6409 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6411 let logger = test_utils::TestLogger::new();
6412 for i in 0..max_accepted_htlcs {
6413 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6414 let payment_event = {
6415 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6416 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();
6417 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6418 check_added_monitors!(nodes[0], 1);
6420 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6421 assert_eq!(events.len(), 1);
6422 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6423 assert_eq!(htlcs[0].htlc_id, i);
6427 SendEvent::from_event(events.remove(0))
6429 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6430 check_added_monitors!(nodes[1], 0);
6431 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6433 expect_pending_htlcs_forwardable!(nodes[1]);
6434 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6436 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6437 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6438 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();
6439 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6440 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6442 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6443 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6447 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6448 //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.
6449 let chanmon_cfgs = create_chanmon_cfgs(2);
6450 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6451 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6452 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6453 let channel_value = 100000;
6454 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6455 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6457 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6459 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6460 // Manually create a route over our max in flight (which our router normally automatically
6462 let route = Route { paths: vec![vec![RouteHop {
6463 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6464 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6465 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6467 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6468 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)));
6470 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6471 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);
6473 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6476 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6478 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6479 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6480 let chanmon_cfgs = create_chanmon_cfgs(2);
6481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6483 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6484 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6485 let htlc_minimum_msat: u64;
6487 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6488 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6489 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6492 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6493 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6494 let logger = test_utils::TestLogger::new();
6495 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();
6496 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6497 check_added_monitors!(nodes[0], 1);
6498 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6499 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6500 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6501 assert!(nodes[1].node.list_channels().is_empty());
6502 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6503 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()));
6504 check_added_monitors!(nodes[1], 1);
6508 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6509 //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
6510 let chanmon_cfgs = create_chanmon_cfgs(2);
6511 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6512 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6513 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6514 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6515 let logger = test_utils::TestLogger::new();
6517 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6518 let channel_reserve = chan_stat.channel_reserve_msat;
6519 let feerate = get_feerate!(nodes[0], chan.2);
6520 // The 2* and +1 are for the fee spike reserve.
6521 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6523 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6524 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6525 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6526 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();
6527 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6528 check_added_monitors!(nodes[0], 1);
6529 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6531 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6532 // at this time channel-initiatee receivers are not required to enforce that senders
6533 // respect the fee_spike_reserve.
6534 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6535 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6537 assert!(nodes[1].node.list_channels().is_empty());
6538 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6539 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6540 check_added_monitors!(nodes[1], 1);
6544 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6545 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6546 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6547 let chanmon_cfgs = create_chanmon_cfgs(2);
6548 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6549 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6550 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6551 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6552 let logger = test_utils::TestLogger::new();
6554 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6555 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6557 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6558 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();
6560 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6561 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6562 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6563 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6565 let mut msg = msgs::UpdateAddHTLC {
6569 payment_hash: our_payment_hash,
6570 cltv_expiry: htlc_cltv,
6571 onion_routing_packet: onion_packet.clone(),
6574 for i in 0..super::channel::OUR_MAX_HTLCS {
6575 msg.htlc_id = i as u64;
6576 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6578 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6579 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6581 assert!(nodes[1].node.list_channels().is_empty());
6582 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6583 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6584 check_added_monitors!(nodes[1], 1);
6588 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6589 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6590 let chanmon_cfgs = create_chanmon_cfgs(2);
6591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6593 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6594 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6595 let logger = test_utils::TestLogger::new();
6597 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6598 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6599 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();
6600 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6601 check_added_monitors!(nodes[0], 1);
6602 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6603 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6604 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6606 assert!(nodes[1].node.list_channels().is_empty());
6607 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6608 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6609 check_added_monitors!(nodes[1], 1);
6613 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6614 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6615 let chanmon_cfgs = create_chanmon_cfgs(2);
6616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6618 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6619 let logger = test_utils::TestLogger::new();
6621 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6622 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6623 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6624 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();
6625 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6626 check_added_monitors!(nodes[0], 1);
6627 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6628 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6629 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6631 assert!(nodes[1].node.list_channels().is_empty());
6632 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6633 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6634 check_added_monitors!(nodes[1], 1);
6638 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6639 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6640 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6641 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6642 let chanmon_cfgs = create_chanmon_cfgs(2);
6643 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6644 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6645 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6646 let logger = test_utils::TestLogger::new();
6648 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6649 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6650 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6651 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();
6652 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6653 check_added_monitors!(nodes[0], 1);
6654 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6655 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6657 //Disconnect and Reconnect
6658 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6659 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6660 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6661 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6662 assert_eq!(reestablish_1.len(), 1);
6663 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6664 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6665 assert_eq!(reestablish_2.len(), 1);
6666 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6667 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6668 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6669 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6672 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6674 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6675 check_added_monitors!(nodes[1], 1);
6676 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6678 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6680 assert!(nodes[1].node.list_channels().is_empty());
6681 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6682 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6683 check_added_monitors!(nodes[1], 1);
6687 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6688 //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.
6690 let chanmon_cfgs = create_chanmon_cfgs(2);
6691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6693 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6694 let logger = test_utils::TestLogger::new();
6695 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6696 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6697 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6698 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();
6699 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6701 check_added_monitors!(nodes[0], 1);
6702 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6703 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6705 let update_msg = msgs::UpdateFulfillHTLC{
6708 payment_preimage: our_payment_preimage,
6711 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6713 assert!(nodes[0].node.list_channels().is_empty());
6714 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6715 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()));
6716 check_added_monitors!(nodes[0], 1);
6720 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6721 //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.
6723 let chanmon_cfgs = create_chanmon_cfgs(2);
6724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6726 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6727 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6728 let logger = test_utils::TestLogger::new();
6730 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6731 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6732 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();
6733 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6734 check_added_monitors!(nodes[0], 1);
6735 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6736 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6738 let update_msg = msgs::UpdateFailHTLC{
6741 reason: msgs::OnionErrorPacket { data: Vec::new()},
6744 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6746 assert!(nodes[0].node.list_channels().is_empty());
6747 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6748 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()));
6749 check_added_monitors!(nodes[0], 1);
6753 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6754 //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.
6756 let chanmon_cfgs = create_chanmon_cfgs(2);
6757 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6758 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6759 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6760 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6761 let logger = test_utils::TestLogger::new();
6763 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6764 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6765 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();
6766 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6767 check_added_monitors!(nodes[0], 1);
6768 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6769 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6771 let update_msg = msgs::UpdateFailMalformedHTLC{
6774 sha256_of_onion: [1; 32],
6775 failure_code: 0x8000,
6778 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6780 assert!(nodes[0].node.list_channels().is_empty());
6781 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6782 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()));
6783 check_added_monitors!(nodes[0], 1);
6787 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6788 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6790 let chanmon_cfgs = create_chanmon_cfgs(2);
6791 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6792 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6793 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6794 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6796 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6798 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6799 check_added_monitors!(nodes[1], 1);
6801 let events = nodes[1].node.get_and_clear_pending_msg_events();
6802 assert_eq!(events.len(), 1);
6803 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6805 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, .. } } => {
6806 assert!(update_add_htlcs.is_empty());
6807 assert_eq!(update_fulfill_htlcs.len(), 1);
6808 assert!(update_fail_htlcs.is_empty());
6809 assert!(update_fail_malformed_htlcs.is_empty());
6810 assert!(update_fee.is_none());
6811 update_fulfill_htlcs[0].clone()
6813 _ => panic!("Unexpected event"),
6817 update_fulfill_msg.htlc_id = 1;
6819 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6821 assert!(nodes[0].node.list_channels().is_empty());
6822 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6823 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6824 check_added_monitors!(nodes[0], 1);
6828 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6829 //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.
6831 let chanmon_cfgs = create_chanmon_cfgs(2);
6832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6834 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6835 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6837 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6839 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6840 check_added_monitors!(nodes[1], 1);
6842 let events = nodes[1].node.get_and_clear_pending_msg_events();
6843 assert_eq!(events.len(), 1);
6844 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6846 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, .. } } => {
6847 assert!(update_add_htlcs.is_empty());
6848 assert_eq!(update_fulfill_htlcs.len(), 1);
6849 assert!(update_fail_htlcs.is_empty());
6850 assert!(update_fail_malformed_htlcs.is_empty());
6851 assert!(update_fee.is_none());
6852 update_fulfill_htlcs[0].clone()
6854 _ => panic!("Unexpected event"),
6858 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6860 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6862 assert!(nodes[0].node.list_channels().is_empty());
6863 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6864 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6865 check_added_monitors!(nodes[0], 1);
6869 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6870 //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.
6872 let chanmon_cfgs = create_chanmon_cfgs(2);
6873 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6874 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6875 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6876 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6877 let logger = test_utils::TestLogger::new();
6879 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6880 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6881 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();
6882 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6883 check_added_monitors!(nodes[0], 1);
6885 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6886 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6889 check_added_monitors!(nodes[1], 0);
6890 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6892 let events = nodes[1].node.get_and_clear_pending_msg_events();
6894 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6896 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, .. } } => {
6897 assert!(update_add_htlcs.is_empty());
6898 assert!(update_fulfill_htlcs.is_empty());
6899 assert!(update_fail_htlcs.is_empty());
6900 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6901 assert!(update_fee.is_none());
6902 update_fail_malformed_htlcs[0].clone()
6904 _ => panic!("Unexpected event"),
6907 update_msg.failure_code &= !0x8000;
6908 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6910 assert!(nodes[0].node.list_channels().is_empty());
6911 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6912 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6913 check_added_monitors!(nodes[0], 1);
6917 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6918 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6919 // * 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.
6921 let chanmon_cfgs = create_chanmon_cfgs(3);
6922 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6923 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6924 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6925 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6926 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6927 let logger = test_utils::TestLogger::new();
6929 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6932 let mut payment_event = {
6933 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6934 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();
6935 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6936 check_added_monitors!(nodes[0], 1);
6937 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6938 assert_eq!(events.len(), 1);
6939 SendEvent::from_event(events.remove(0))
6941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6942 check_added_monitors!(nodes[1], 0);
6943 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6944 expect_pending_htlcs_forwardable!(nodes[1]);
6945 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6946 assert_eq!(events_2.len(), 1);
6947 check_added_monitors!(nodes[1], 1);
6948 payment_event = SendEvent::from_event(events_2.remove(0));
6949 assert_eq!(payment_event.msgs.len(), 1);
6952 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6953 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6954 check_added_monitors!(nodes[2], 0);
6955 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6957 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6958 assert_eq!(events_3.len(), 1);
6959 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6961 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6962 assert!(update_add_htlcs.is_empty());
6963 assert!(update_fulfill_htlcs.is_empty());
6964 assert!(update_fail_htlcs.is_empty());
6965 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6966 assert!(update_fee.is_none());
6967 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6969 _ => panic!("Unexpected event"),
6973 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6975 check_added_monitors!(nodes[1], 0);
6976 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6977 expect_pending_htlcs_forwardable!(nodes[1]);
6978 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6979 assert_eq!(events_4.len(), 1);
6981 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6983 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, .. } } => {
6984 assert!(update_add_htlcs.is_empty());
6985 assert!(update_fulfill_htlcs.is_empty());
6986 assert_eq!(update_fail_htlcs.len(), 1);
6987 assert!(update_fail_malformed_htlcs.is_empty());
6988 assert!(update_fee.is_none());
6990 _ => panic!("Unexpected event"),
6993 check_added_monitors!(nodes[1], 1);
6996 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6997 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6998 // 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
6999 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7001 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7002 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7003 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7004 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7005 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7006 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7008 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7010 // We route 2 dust-HTLCs between A and B
7011 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7012 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7013 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7015 // Cache one local commitment tx as previous
7016 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7018 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7019 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7020 check_added_monitors!(nodes[1], 0);
7021 expect_pending_htlcs_forwardable!(nodes[1]);
7022 check_added_monitors!(nodes[1], 1);
7024 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7025 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7026 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7027 check_added_monitors!(nodes[0], 1);
7029 // Cache one local commitment tx as lastest
7030 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7032 let events = nodes[0].node.get_and_clear_pending_msg_events();
7034 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7035 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7037 _ => panic!("Unexpected event"),
7040 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7041 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7043 _ => panic!("Unexpected event"),
7046 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7047 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7048 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7050 if announce_latest {
7051 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7053 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7056 check_closed_broadcast!(nodes[0], false);
7057 check_added_monitors!(nodes[0], 1);
7059 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7060 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7061 let events = nodes[0].node.get_and_clear_pending_events();
7062 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7063 assert_eq!(events.len(), 2);
7064 let mut first_failed = false;
7065 for event in events {
7067 Event::PaymentFailed { payment_hash, .. } => {
7068 if payment_hash == payment_hash_1 {
7069 assert!(!first_failed);
7070 first_failed = true;
7072 assert_eq!(payment_hash, payment_hash_2);
7075 _ => panic!("Unexpected event"),
7081 fn test_failure_delay_dust_htlc_local_commitment() {
7082 do_test_failure_delay_dust_htlc_local_commitment(true);
7083 do_test_failure_delay_dust_htlc_local_commitment(false);
7086 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7087 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7088 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7089 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7090 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7091 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7092 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7094 let chanmon_cfgs = create_chanmon_cfgs(3);
7095 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7096 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7097 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7098 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7100 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7102 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7103 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7105 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7106 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7108 // We revoked bs_commitment_tx
7110 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7111 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7114 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7115 let mut timeout_tx = Vec::new();
7117 // We fail dust-HTLC 1 by broadcast of local commitment tx
7118 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7119 check_closed_broadcast!(nodes[0], false);
7120 check_added_monitors!(nodes[0], 1);
7121 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7122 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7123 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7124 expect_payment_failed!(nodes[0], dust_hash, true);
7125 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7126 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7127 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7128 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7129 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7130 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7131 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7132 expect_payment_failed!(nodes[0], non_dust_hash, true);
7134 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7135 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7136 check_closed_broadcast!(nodes[0], false);
7137 check_added_monitors!(nodes[0], 1);
7138 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7139 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7140 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7141 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7143 expect_payment_failed!(nodes[0], dust_hash, true);
7144 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7145 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7146 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7147 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7148 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7149 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7150 expect_payment_failed!(nodes[0], non_dust_hash, true);
7152 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7154 let events = nodes[0].node.get_and_clear_pending_events();
7155 assert_eq!(events.len(), 2);
7158 Event::PaymentFailed { payment_hash, .. } => {
7159 if payment_hash == dust_hash { first = true; }
7160 else { first = false; }
7162 _ => panic!("Unexpected event"),
7165 Event::PaymentFailed { payment_hash, .. } => {
7166 if first { assert_eq!(payment_hash, non_dust_hash); }
7167 else { assert_eq!(payment_hash, dust_hash); }
7169 _ => panic!("Unexpected event"),
7176 fn test_sweep_outbound_htlc_failure_update() {
7177 do_test_sweep_outbound_htlc_failure_update(false, true);
7178 do_test_sweep_outbound_htlc_failure_update(false, false);
7179 do_test_sweep_outbound_htlc_failure_update(true, false);
7183 fn test_upfront_shutdown_script() {
7184 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7185 // enforce it at shutdown message
7187 let mut config = UserConfig::default();
7188 config.channel_options.announced_channel = true;
7189 config.peer_channel_config_limits.force_announced_channel_preference = false;
7190 config.channel_options.commit_upfront_shutdown_pubkey = false;
7191 let user_cfgs = [None, Some(config), None];
7192 let chanmon_cfgs = create_chanmon_cfgs(3);
7193 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7194 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7195 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7197 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7198 let flags = InitFeatures::known();
7199 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7200 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7201 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7202 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7203 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7204 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7205 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()));
7206 check_added_monitors!(nodes[2], 1);
7208 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7209 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7210 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7211 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7212 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7213 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7214 let events = nodes[2].node.get_and_clear_pending_msg_events();
7215 assert_eq!(events.len(), 1);
7217 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7218 _ => panic!("Unexpected event"),
7221 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7222 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7223 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7224 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7225 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7226 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7227 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &InitFeatures::known(), &node_1_shutdown);
7228 let events = nodes[1].node.get_and_clear_pending_msg_events();
7229 assert_eq!(events.len(), 1);
7231 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7232 _ => panic!("Unexpected event"),
7235 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7236 // channel smoothly, opt-out is from channel initiator here
7237 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7238 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7239 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7240 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7241 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7242 let events = nodes[0].node.get_and_clear_pending_msg_events();
7243 assert_eq!(events.len(), 1);
7245 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7246 _ => panic!("Unexpected event"),
7249 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7250 //// channel smoothly
7251 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7252 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7253 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7254 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7255 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7256 let events = nodes[0].node.get_and_clear_pending_msg_events();
7257 assert_eq!(events.len(), 2);
7259 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7260 _ => panic!("Unexpected event"),
7263 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7264 _ => panic!("Unexpected event"),
7269 fn test_upfront_shutdown_script_unsupport_segwit() {
7270 // We test that channel is closed early
7271 // if a segwit program is passed as upfront shutdown script,
7272 // but the peer does not support segwit.
7273 let chanmon_cfgs = create_chanmon_cfgs(2);
7274 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7275 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7276 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7278 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
7280 let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7281 open_channel.shutdown_scriptpubkey = Present(Builder::new().push_int(16)
7282 .push_slice(&[0, 0])
7285 let features = InitFeatures::known().clear_shutdown_anysegwit();
7286 nodes[0].node.handle_open_channel(&nodes[0].node.get_our_node_id(), features, &open_channel);
7288 let events = nodes[0].node.get_and_clear_pending_msg_events();
7289 assert_eq!(events.len(), 1);
7291 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7292 assert_eq!(node_id, nodes[0].node.get_our_node_id());
7293 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));
7295 _ => panic!("Unexpected event"),
7300 fn test_shutdown_script_any_segwit_allowed() {
7301 let mut config = UserConfig::default();
7302 config.channel_options.announced_channel = true;
7303 config.peer_channel_config_limits.force_announced_channel_preference = false;
7304 config.channel_options.commit_upfront_shutdown_pubkey = false;
7305 let user_cfgs = [None, Some(config), None];
7306 let chanmon_cfgs = create_chanmon_cfgs(3);
7307 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7308 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7309 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7311 //// We test if the remote peer accepts opt_shutdown_anysegwit, a witness program can be used on shutdown
7312 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7313 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7314 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7315 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7316 .push_slice(&[0, 0])
7318 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7319 let events = nodes[0].node.get_and_clear_pending_msg_events();
7320 assert_eq!(events.len(), 2);
7322 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7323 _ => panic!("Unexpected event"),
7326 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7327 _ => panic!("Unexpected event"),
7332 fn test_shutdown_script_any_segwit_not_allowed() {
7333 let mut config = UserConfig::default();
7334 config.channel_options.announced_channel = true;
7335 config.peer_channel_config_limits.force_announced_channel_preference = false;
7336 config.channel_options.commit_upfront_shutdown_pubkey = false;
7337 let user_cfgs = [None, Some(config), None];
7338 let chanmon_cfgs = create_chanmon_cfgs(3);
7339 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7340 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7341 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7343 //// We test that if the remote peer does not accept opt_shutdown_anysegwit, the witness program cannot be used on shutdown
7344 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7345 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7346 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7347 // Make an any segwit version script
7348 node_0_shutdown.scriptpubkey = Builder::new().push_int(16)
7349 .push_slice(&[0, 0])
7351 let flags_no = InitFeatures::known().clear_shutdown_anysegwit();
7352 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &flags_no, &node_0_shutdown);
7353 let events = nodes[0].node.get_and_clear_pending_msg_events();
7354 assert_eq!(events.len(), 2);
7356 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7357 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7358 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (60020000) from remote peer".to_owned())
7360 _ => panic!("Unexpected event"),
7362 check_added_monitors!(nodes[0], 1);
7366 fn test_shutdown_script_segwit_but_not_anysegwit() {
7367 let mut config = UserConfig::default();
7368 config.channel_options.announced_channel = true;
7369 config.peer_channel_config_limits.force_announced_channel_preference = false;
7370 config.channel_options.commit_upfront_shutdown_pubkey = false;
7371 let user_cfgs = [None, Some(config), None];
7372 let chanmon_cfgs = create_chanmon_cfgs(3);
7373 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7374 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7375 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7377 //// We test that if shutdown any segwit is supported and we send a witness script with 0 version, this is not accepted
7378 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7379 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7380 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7381 // Make a segwit script that is not a valid as any segwit
7382 node_0_shutdown.scriptpubkey = Builder::new().push_int(0)
7383 .push_slice(&[0, 0])
7385 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &InitFeatures::known(), &node_0_shutdown);
7386 let events = nodes[0].node.get_and_clear_pending_msg_events();
7387 assert_eq!(events.len(), 2);
7389 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
7390 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7391 assert_eq!(msg.data, "Got a nonstandard scriptpubkey (00020000) from remote peer".to_owned())
7393 _ => panic!("Unexpected event"),
7395 check_added_monitors!(nodes[0], 1);
7399 fn test_user_configurable_csv_delay() {
7400 // We test our channel constructors yield errors when we pass them absurd csv delay
7402 let mut low_our_to_self_config = UserConfig::default();
7403 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7404 let mut high_their_to_self_config = UserConfig::default();
7405 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7406 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7407 let chanmon_cfgs = create_chanmon_cfgs(2);
7408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7410 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7412 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7413 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) {
7415 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())); },
7416 _ => panic!("Unexpected event"),
7418 } else { assert!(false) }
7420 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7421 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7422 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7423 open_channel.to_self_delay = 200;
7424 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) {
7426 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())); },
7427 _ => panic!("Unexpected event"),
7429 } else { assert!(false); }
7431 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7432 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7433 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()));
7434 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7435 accept_channel.to_self_delay = 200;
7436 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7437 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7439 &ErrorAction::SendErrorMessage { ref msg } => {
7440 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()));
7442 _ => { assert!(false); }
7444 } else { assert!(false); }
7446 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7447 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7448 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7449 open_channel.to_self_delay = 200;
7450 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) {
7452 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())); },
7453 _ => panic!("Unexpected event"),
7455 } else { assert!(false); }
7459 fn test_data_loss_protect() {
7460 // We want to be sure that :
7461 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7462 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7463 // * we close channel in case of detecting other being fallen behind
7464 // * we are able to claim our own outputs thanks to to_remote being static
7465 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7471 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7472 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7473 // during signing due to revoked tx
7474 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7475 let keys_manager = &chanmon_cfgs[0].keys_manager;
7478 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7479 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7480 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7482 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7484 // Cache node A state before any channel update
7485 let previous_node_state = nodes[0].node.encode();
7486 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7487 nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7489 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7490 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7492 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7493 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7495 // Restore node A from previous state
7496 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7497 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7498 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7499 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7500 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7501 persister = test_utils::TestPersister::new();
7502 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7504 let mut channel_monitors = HashMap::new();
7505 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7506 <(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 {
7507 keys_manager: keys_manager,
7508 fee_estimator: &fee_estimator,
7509 chain_monitor: &monitor,
7511 tx_broadcaster: &tx_broadcaster,
7512 default_config: UserConfig::default(),
7516 nodes[0].node = &node_state_0;
7517 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7518 nodes[0].chain_monitor = &monitor;
7519 nodes[0].chain_source = &chain_source;
7521 check_added_monitors!(nodes[0], 1);
7523 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7524 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7526 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7528 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7529 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7530 check_added_monitors!(nodes[0], 1);
7533 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7534 assert_eq!(node_txn.len(), 0);
7537 let mut reestablish_1 = Vec::with_capacity(1);
7538 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7539 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7540 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7541 reestablish_1.push(msg.clone());
7542 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7543 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7545 &ErrorAction::SendErrorMessage { ref msg } => {
7546 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");
7548 _ => panic!("Unexpected event!"),
7551 panic!("Unexpected event")
7555 // Check we close channel detecting A is fallen-behind
7556 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7557 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7558 check_added_monitors!(nodes[1], 1);
7561 // Check A is able to claim to_remote output
7562 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7563 assert_eq!(node_txn.len(), 1);
7564 check_spends!(node_txn[0], chan.3);
7565 assert_eq!(node_txn[0].output.len(), 2);
7566 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7567 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7568 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7569 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7570 assert_eq!(spend_txn.len(), 1);
7571 check_spends!(spend_txn[0], node_txn[0]);
7575 fn test_check_htlc_underpaying() {
7576 // Send payment through A -> B but A is maliciously
7577 // sending a probe payment (i.e less than expected value0
7578 // to B, B should refuse payment.
7580 let chanmon_cfgs = create_chanmon_cfgs(2);
7581 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7582 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7583 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7585 // Create some initial channels
7586 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7588 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7590 // Node 3 is expecting payment of 100_000 but receive 10_000,
7591 // fail htlc like we didn't know the preimage.
7592 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7593 nodes[1].node.process_pending_htlc_forwards();
7595 let events = nodes[1].node.get_and_clear_pending_msg_events();
7596 assert_eq!(events.len(), 1);
7597 let (update_fail_htlc, commitment_signed) = match events[0] {
7598 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 } } => {
7599 assert!(update_add_htlcs.is_empty());
7600 assert!(update_fulfill_htlcs.is_empty());
7601 assert_eq!(update_fail_htlcs.len(), 1);
7602 assert!(update_fail_malformed_htlcs.is_empty());
7603 assert!(update_fee.is_none());
7604 (update_fail_htlcs[0].clone(), commitment_signed)
7606 _ => panic!("Unexpected event"),
7608 check_added_monitors!(nodes[1], 1);
7610 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7611 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7613 // 10_000 msat as u64, followed by a height of 99 as u32
7614 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7615 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7616 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7617 nodes[1].node.get_and_clear_pending_events();
7621 fn test_announce_disable_channels() {
7622 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7623 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7625 let chanmon_cfgs = create_chanmon_cfgs(2);
7626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7630 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7631 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7632 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7635 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7636 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7638 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7639 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7640 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7641 assert_eq!(msg_events.len(), 3);
7642 for e in msg_events {
7644 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7645 let short_id = msg.contents.short_channel_id;
7646 // Check generated channel_update match list in PendingChannelUpdate
7647 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7648 panic!("Generated ChannelUpdate for wrong chan!");
7651 _ => panic!("Unexpected event"),
7655 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7656 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7657 assert_eq!(reestablish_1.len(), 3);
7658 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7659 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7660 assert_eq!(reestablish_2.len(), 3);
7662 // Reestablish chan_1
7663 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
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[0]);
7666 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7667 // Reestablish chan_2
7668 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
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[1]);
7671 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7672 // Reestablish chan_3
7673 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7674 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7675 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7676 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7678 nodes[0].node.timer_chan_freshness_every_min();
7679 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7683 fn test_bump_penalty_txn_on_revoked_commitment() {
7684 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7685 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7687 let chanmon_cfgs = create_chanmon_cfgs(2);
7688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7690 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7692 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7693 let logger = test_utils::TestLogger::new();
7696 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7697 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7698 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();
7699 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7701 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7702 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7703 assert_eq!(revoked_txn[0].output.len(), 4);
7704 assert_eq!(revoked_txn[0].input.len(), 1);
7705 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7706 let revoked_txid = revoked_txn[0].txid();
7708 let mut penalty_sum = 0;
7709 for outp in revoked_txn[0].output.iter() {
7710 if outp.script_pubkey.is_v0_p2wsh() {
7711 penalty_sum += outp.value;
7715 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7716 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7718 // Actually revoke tx by claiming a HTLC
7719 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7720 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7721 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7722 check_added_monitors!(nodes[1], 1);
7724 // One or more justice tx should have been broadcast, check it
7728 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7729 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7730 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7731 assert_eq!(node_txn[0].output.len(), 1);
7732 check_spends!(node_txn[0], revoked_txn[0]);
7733 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7734 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7735 penalty_1 = node_txn[0].txid();
7739 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7740 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7741 let mut penalty_2 = penalty_1;
7742 let mut feerate_2 = 0;
7744 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7745 assert_eq!(node_txn.len(), 1);
7746 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7747 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7748 assert_eq!(node_txn[0].output.len(), 1);
7749 check_spends!(node_txn[0], revoked_txn[0]);
7750 penalty_2 = node_txn[0].txid();
7751 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7752 assert_ne!(penalty_2, penalty_1);
7753 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7754 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7755 // Verify 25% bump heuristic
7756 assert!(feerate_2 * 100 >= feerate_1 * 125);
7760 assert_ne!(feerate_2, 0);
7762 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7763 connect_blocks(&nodes[1], 3, 118, true, header);
7765 let mut feerate_3 = 0;
7767 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7768 assert_eq!(node_txn.len(), 1);
7769 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7770 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7771 assert_eq!(node_txn[0].output.len(), 1);
7772 check_spends!(node_txn[0], revoked_txn[0]);
7773 penalty_3 = node_txn[0].txid();
7774 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7775 assert_ne!(penalty_3, penalty_2);
7776 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7777 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7778 // Verify 25% bump heuristic
7779 assert!(feerate_3 * 100 >= feerate_2 * 125);
7783 assert_ne!(feerate_3, 0);
7785 nodes[1].node.get_and_clear_pending_events();
7786 nodes[1].node.get_and_clear_pending_msg_events();
7790 fn test_bump_penalty_txn_on_revoked_htlcs() {
7791 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7792 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7794 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7795 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7796 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7797 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7798 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7800 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7801 // Lock HTLC in both directions
7802 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7803 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7805 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7806 assert_eq!(revoked_local_txn[0].input.len(), 1);
7807 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7809 // Revoke local commitment tx
7810 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7812 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7813 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7814 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7815 check_closed_broadcast!(nodes[1], false);
7816 check_added_monitors!(nodes[1], 1);
7818 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7819 assert_eq!(revoked_htlc_txn.len(), 4);
7820 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7821 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7822 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7823 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7824 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7825 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7826 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7827 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7828 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7829 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7830 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7831 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7832 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7833 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7836 // Broadcast set of revoked txn on A
7837 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7838 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7839 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7840 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7841 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7846 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7847 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7848 // Verify claim tx are spending revoked HTLC txn
7850 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7851 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7852 // which are included in the same block (they are broadcasted because we scan the
7853 // transactions linearly and generate claims as we go, they likely should be removed in the
7855 assert_eq!(node_txn[0].input.len(), 1);
7856 check_spends!(node_txn[0], revoked_local_txn[0]);
7857 assert_eq!(node_txn[1].input.len(), 1);
7858 check_spends!(node_txn[1], revoked_local_txn[0]);
7859 assert_eq!(node_txn[2].input.len(), 1);
7860 check_spends!(node_txn[2], revoked_local_txn[0]);
7862 // Each of the three justice transactions claim a separate (single) output of the three
7863 // available, which we check here:
7864 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7865 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7866 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7868 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7869 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7871 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7872 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7873 // a remote commitment tx has already been confirmed).
7874 check_spends!(node_txn[3], chan.3);
7876 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7877 // output, checked above).
7878 assert_eq!(node_txn[4].input.len(), 2);
7879 assert_eq!(node_txn[4].output.len(), 1);
7880 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7882 first = node_txn[4].txid();
7883 // Store both feerates for later comparison
7884 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7885 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7886 penalty_txn = vec![node_txn[2].clone()];
7890 // Connect one more block to see if bumped penalty are issued for HTLC txn
7891 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7892 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7893 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7894 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7896 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7897 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7899 check_spends!(node_txn[0], revoked_local_txn[0]);
7900 check_spends!(node_txn[1], revoked_local_txn[0]);
7901 // Note that these are both bogus - they spend outputs already claimed in block 129:
7902 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7903 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7905 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7906 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7912 // Few more blocks to confirm penalty txn
7913 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7914 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7915 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7917 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7918 assert_eq!(node_txn.len(), 1);
7920 assert_eq!(node_txn[0].input.len(), 2);
7921 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7922 // Verify bumped tx is different and 25% bump heuristic
7923 assert_ne!(first, node_txn[0].txid());
7924 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7925 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7926 assert!(feerate_2 * 100 > feerate_1 * 125);
7927 let txn = vec![node_txn[0].clone()];
7931 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7932 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7933 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7934 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7936 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7937 // We verify than no new transaction has been broadcast because previously
7938 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7939 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7940 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7941 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7942 // up bumped justice generation.
7943 assert_eq!(node_txn.len(), 0);
7946 check_closed_broadcast!(nodes[0], false);
7947 check_added_monitors!(nodes[0], 1);
7951 fn test_bump_penalty_txn_on_remote_commitment() {
7952 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7953 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7956 // Provide preimage for one
7957 // Check aggregation
7959 let chanmon_cfgs = create_chanmon_cfgs(2);
7960 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7961 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7962 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7964 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7965 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7966 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7968 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7969 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7970 assert_eq!(remote_txn[0].output.len(), 4);
7971 assert_eq!(remote_txn[0].input.len(), 1);
7972 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7974 // Claim a HTLC without revocation (provide B monitor with preimage)
7975 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7976 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7977 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7978 check_added_monitors!(nodes[1], 2);
7980 // One or more claim tx should have been broadcast, check it
7983 let feerate_timeout;
7984 let feerate_preimage;
7986 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7987 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7988 assert_eq!(node_txn[0].input.len(), 1);
7989 assert_eq!(node_txn[1].input.len(), 1);
7990 check_spends!(node_txn[0], remote_txn[0]);
7991 check_spends!(node_txn[1], remote_txn[0]);
7992 check_spends!(node_txn[2], chan.3);
7993 check_spends!(node_txn[3], node_txn[2]);
7994 check_spends!(node_txn[4], node_txn[2]);
7995 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7996 timeout = node_txn[0].txid();
7997 let index = node_txn[0].input[0].previous_output.vout;
7998 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7999 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
8001 preimage = 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_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
8006 timeout = node_txn[1].txid();
8007 let index = node_txn[1].input[0].previous_output.vout;
8008 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8009 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8011 preimage = node_txn[0].txid();
8012 let index = node_txn[0].input[0].previous_output.vout;
8013 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8014 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8018 assert_ne!(feerate_timeout, 0);
8019 assert_ne!(feerate_preimage, 0);
8021 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8022 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
8024 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8025 assert_eq!(node_txn.len(), 2);
8026 assert_eq!(node_txn[0].input.len(), 1);
8027 assert_eq!(node_txn[1].input.len(), 1);
8028 check_spends!(node_txn[0], remote_txn[0]);
8029 check_spends!(node_txn[1], remote_txn[0]);
8030 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8031 let index = node_txn[0].input[0].previous_output.vout;
8032 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8033 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8034 assert!(new_feerate * 100 > feerate_timeout * 125);
8035 assert_ne!(timeout, node_txn[0].txid());
8037 let index = node_txn[1].input[0].previous_output.vout;
8038 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8039 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8040 assert!(new_feerate * 100 > feerate_preimage * 125);
8041 assert_ne!(preimage, node_txn[1].txid());
8043 let index = node_txn[1].input[0].previous_output.vout;
8044 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8045 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8046 assert!(new_feerate * 100 > feerate_timeout * 125);
8047 assert_ne!(timeout, node_txn[1].txid());
8049 let index = node_txn[0].input[0].previous_output.vout;
8050 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8051 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8052 assert!(new_feerate * 100 > feerate_preimage * 125);
8053 assert_ne!(preimage, node_txn[0].txid());
8058 nodes[1].node.get_and_clear_pending_events();
8059 nodes[1].node.get_and_clear_pending_msg_events();
8063 fn test_set_outpoints_partial_claiming() {
8064 // - remote party claim tx, new bump tx
8065 // - disconnect remote claiming tx, new bump
8066 // - disconnect tx, see no tx anymore
8067 let chanmon_cfgs = create_chanmon_cfgs(2);
8068 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8069 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8070 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8072 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8073 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8074 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8076 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8077 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8078 assert_eq!(remote_txn.len(), 3);
8079 assert_eq!(remote_txn[0].output.len(), 4);
8080 assert_eq!(remote_txn[0].input.len(), 1);
8081 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8082 check_spends!(remote_txn[1], remote_txn[0]);
8083 check_spends!(remote_txn[2], remote_txn[0]);
8085 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8086 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8087 // Provide node A with both preimage
8088 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8089 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8090 check_added_monitors!(nodes[0], 2);
8091 nodes[0].node.get_and_clear_pending_events();
8092 nodes[0].node.get_and_clear_pending_msg_events();
8094 // Connect blocks on node A commitment transaction
8095 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8096 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8097 check_closed_broadcast!(nodes[0], false);
8098 check_added_monitors!(nodes[0], 1);
8099 // Verify node A broadcast tx claiming both HTLCs
8101 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8102 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8103 assert_eq!(node_txn.len(), 4);
8104 check_spends!(node_txn[0], remote_txn[0]);
8105 check_spends!(node_txn[1], chan.3);
8106 check_spends!(node_txn[2], node_txn[1]);
8107 check_spends!(node_txn[3], node_txn[1]);
8108 assert_eq!(node_txn[0].input.len(), 2);
8112 // Connect blocks on node B
8113 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8114 check_closed_broadcast!(nodes[1], false);
8115 check_added_monitors!(nodes[1], 1);
8116 // Verify node B broadcast 2 HTLC-timeout txn
8117 let partial_claim_tx = {
8118 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8119 assert_eq!(node_txn.len(), 3);
8120 check_spends!(node_txn[1], node_txn[0]);
8121 check_spends!(node_txn[2], node_txn[0]);
8122 assert_eq!(node_txn[1].input.len(), 1);
8123 assert_eq!(node_txn[2].input.len(), 1);
8127 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8128 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8129 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8131 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8132 assert_eq!(node_txn.len(), 1);
8133 check_spends!(node_txn[0], remote_txn[0]);
8134 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8137 nodes[0].node.get_and_clear_pending_msg_events();
8139 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8140 disconnect_block(&nodes[0], &header, 102);
8142 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8143 assert_eq!(node_txn.len(), 1);
8144 check_spends!(node_txn[0], remote_txn[0]);
8145 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8149 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8150 disconnect_block(&nodes[0], &header, 101);
8151 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8153 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8154 assert_eq!(node_txn.len(), 0);
8160 fn test_counterparty_raa_skip_no_crash() {
8161 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8162 // commitment transaction, we would have happily carried on and provided them the next
8163 // commitment transaction based on one RAA forward. This would probably eventually have led to
8164 // channel closure, but it would not have resulted in funds loss. Still, our
8165 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8166 // check simply that the channel is closed in response to such an RAA, but don't check whether
8167 // we decide to punish our counterparty for revoking their funds (as we don't currently
8169 let chanmon_cfgs = create_chanmon_cfgs(2);
8170 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8171 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8172 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8173 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8175 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8176 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8177 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8178 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8179 // Must revoke without gaps
8180 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8181 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8182 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8184 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8185 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8186 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8187 check_added_monitors!(nodes[1], 1);
8191 fn test_bump_txn_sanitize_tracking_maps() {
8192 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8193 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8195 let chanmon_cfgs = create_chanmon_cfgs(2);
8196 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8197 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8198 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8200 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8201 // Lock HTLC in both directions
8202 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8203 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8205 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8206 assert_eq!(revoked_local_txn[0].input.len(), 1);
8207 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8209 // Revoke local commitment tx
8210 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8212 // Broadcast set of revoked txn on A
8213 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8214 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8216 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8217 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8218 check_closed_broadcast!(nodes[0], false);
8219 check_added_monitors!(nodes[0], 1);
8221 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8222 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8223 check_spends!(node_txn[0], revoked_local_txn[0]);
8224 check_spends!(node_txn[1], revoked_local_txn[0]);
8225 check_spends!(node_txn[2], revoked_local_txn[0]);
8226 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8230 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8231 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8232 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8234 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8235 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8236 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
8237 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
8243 fn test_override_channel_config() {
8244 let chanmon_cfgs = create_chanmon_cfgs(2);
8245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8249 // Node0 initiates a channel to node1 using the override config.
8250 let mut override_config = UserConfig::default();
8251 override_config.own_channel_config.our_to_self_delay = 200;
8253 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8255 // Assert the channel created by node0 is using the override config.
8256 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8257 assert_eq!(res.channel_flags, 0);
8258 assert_eq!(res.to_self_delay, 200);
8262 fn test_override_0msat_htlc_minimum() {
8263 let mut zero_config = UserConfig::default();
8264 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8265 let chanmon_cfgs = create_chanmon_cfgs(2);
8266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8271 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8272 assert_eq!(res.htlc_minimum_msat, 1);
8274 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8275 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8276 assert_eq!(res.htlc_minimum_msat, 1);
8280 fn test_simple_payment_secret() {
8281 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8282 // features, however.
8283 let chanmon_cfgs = create_chanmon_cfgs(3);
8284 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8285 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8286 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8288 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8289 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8290 let logger = test_utils::TestLogger::new();
8292 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8293 let payment_secret = PaymentSecret([0xdb; 32]);
8294 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8295 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();
8296 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8297 // Claiming with all the correct values but the wrong secret should result in nothing...
8298 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8299 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8300 // ...but with the right secret we should be able to claim all the way back
8301 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8305 fn test_simple_mpp() {
8306 // Simple test of sending a multi-path payment.
8307 let chanmon_cfgs = create_chanmon_cfgs(4);
8308 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8309 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8310 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8312 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8313 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8314 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8315 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8316 let logger = test_utils::TestLogger::new();
8318 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8319 let payment_secret = PaymentSecret([0xdb; 32]);
8320 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8321 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();
8322 let path = route.paths[0].clone();
8323 route.paths.push(path);
8324 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8325 route.paths[0][0].short_channel_id = chan_1_id;
8326 route.paths[0][1].short_channel_id = chan_3_id;
8327 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8328 route.paths[1][0].short_channel_id = chan_2_id;
8329 route.paths[1][1].short_channel_id = chan_4_id;
8330 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8331 // Claiming with all the correct values but the wrong secret should result in nothing...
8332 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8333 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8334 // ...but with the right secret we should be able to claim all the way back
8335 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8339 fn test_update_err_monitor_lockdown() {
8340 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8341 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8342 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8344 // This scenario may happen in a watchtower setup, where watchtower process a block height
8345 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8346 // commitment at same time.
8348 let chanmon_cfgs = create_chanmon_cfgs(2);
8349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8353 // Create some initial channel
8354 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8355 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8357 // Rebalance the network to generate htlc in the two directions
8358 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8360 // Route a HTLC from node 0 to node 1 (but don't settle)
8361 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8363 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8364 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8365 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8366 let persister = test_utils::TestPersister::new();
8368 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8369 let monitor = monitors.get(&outpoint).unwrap();
8370 let mut w = test_utils::TestVecWriter(Vec::new());
8371 monitor.write(&mut w).unwrap();
8372 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8373 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8374 assert!(new_monitor == *monitor);
8375 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);
8376 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8379 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8380 watchtower.chain_monitor.block_connected(&header, &[], 200);
8382 // Try to update ChannelMonitor
8383 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8384 check_added_monitors!(nodes[1], 1);
8385 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8386 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8387 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8388 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8389 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8390 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8391 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8392 } else { assert!(false); }
8393 } else { assert!(false); };
8394 // Our local monitor is in-sync and hasn't processed yet timeout
8395 check_added_monitors!(nodes[0], 1);
8396 let events = nodes[0].node.get_and_clear_pending_events();
8397 assert_eq!(events.len(), 1);
8401 fn test_concurrent_monitor_claim() {
8402 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8403 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8404 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8405 // state N+1 confirms. Alice claims output from state N+1.
8407 let chanmon_cfgs = create_chanmon_cfgs(2);
8408 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8409 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8410 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8412 // Create some initial channel
8413 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8414 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8416 // Rebalance the network to generate htlc in the two directions
8417 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8419 // Route a HTLC from node 0 to node 1 (but don't settle)
8420 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8422 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8423 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8424 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8425 let persister = test_utils::TestPersister::new();
8426 let watchtower_alice = {
8427 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8428 let monitor = monitors.get(&outpoint).unwrap();
8429 let mut w = test_utils::TestVecWriter(Vec::new());
8430 monitor.write(&mut w).unwrap();
8431 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8432 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8433 assert!(new_monitor == *monitor);
8434 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);
8435 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8438 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8439 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8441 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8443 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8444 assert_eq!(txn.len(), 2);
8448 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8449 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8450 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8451 let persister = test_utils::TestPersister::new();
8452 let watchtower_bob = {
8453 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.read().unwrap();
8454 let monitor = monitors.get(&outpoint).unwrap();
8455 let mut w = test_utils::TestVecWriter(Vec::new());
8456 monitor.write(&mut w).unwrap();
8457 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8458 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8459 assert!(new_monitor == *monitor);
8460 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);
8461 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8464 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8465 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8467 // Route another payment to generate another update with still previous HTLC pending
8468 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8470 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8471 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();
8472 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8474 check_added_monitors!(nodes[1], 1);
8476 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8477 assert_eq!(updates.update_add_htlcs.len(), 1);
8478 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8479 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8480 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8481 // Watchtower Alice should already have seen the block and reject the update
8482 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8483 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8484 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8485 } else { assert!(false); }
8486 } else { assert!(false); };
8487 // Our local monitor is in-sync and hasn't processed yet timeout
8488 check_added_monitors!(nodes[0], 1);
8490 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8491 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8493 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8496 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8497 assert_eq!(txn.len(), 2);
8498 bob_state_y = txn[0].clone();
8502 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8503 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8505 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8506 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8507 // the onchain detection of the HTLC output
8508 assert_eq!(htlc_txn.len(), 2);
8509 check_spends!(htlc_txn[0], bob_state_y);
8510 check_spends!(htlc_txn[1], bob_state_y);
8515 fn test_pre_lockin_no_chan_closed_update() {
8516 // Test that if a peer closes a channel in response to a funding_created message we don't
8517 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8520 // Doing so would imply a channel monitor update before the initial channel monitor
8521 // registration, violating our API guarantees.
8523 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8524 // then opening a second channel with the same funding output as the first (which is not
8525 // rejected because the first channel does not exist in the ChannelManager) and closing it
8526 // before receiving funding_signed.
8527 let chanmon_cfgs = create_chanmon_cfgs(2);
8528 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8529 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8530 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8532 // Create an initial channel
8533 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8534 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8535 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8536 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8537 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8539 // Move the first channel through the funding flow...
8540 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8542 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8543 check_added_monitors!(nodes[0], 0);
8545 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8546 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8547 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8548 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8552 fn test_htlc_no_detection() {
8553 // This test is a mutation to underscore the detection logic bug we had
8554 // before #653. HTLC value routed is above the remaining balance, thus
8555 // inverting HTLC and `to_remote` output. HTLC will come second and
8556 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8557 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8558 // outputs order detection for correct spending children filtring.
8560 let chanmon_cfgs = create_chanmon_cfgs(2);
8561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8563 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8565 // Create some initial channels
8566 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8568 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8569 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8570 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8571 assert_eq!(local_txn[0].input.len(), 1);
8572 assert_eq!(local_txn[0].output.len(), 3);
8573 check_spends!(local_txn[0], chan_1.3);
8575 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8576 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8577 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8578 // We deliberately connect the local tx twice as this should provoke a failure calling
8579 // this test before #653 fix.
8580 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8581 check_closed_broadcast!(nodes[0], false);
8582 check_added_monitors!(nodes[0], 1);
8584 let htlc_timeout = {
8585 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8586 assert_eq!(node_txn[0].input.len(), 1);
8587 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8588 check_spends!(node_txn[0], local_txn[0]);
8592 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8593 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8594 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8595 expect_payment_failed!(nodes[0], our_payment_hash, true);
8598 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8599 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8600 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8601 // Carol, Alice would be the upstream node, and Carol the downstream.)
8603 // Steps of the test:
8604 // 1) Alice sends a HTLC to Carol through Bob.
8605 // 2) Carol doesn't settle the HTLC.
8606 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8607 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8608 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8609 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8610 // 5) Carol release the preimage to Bob off-chain.
8611 // 6) Bob claims the offered output on the broadcasted commitment.
8612 let chanmon_cfgs = create_chanmon_cfgs(3);
8613 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8614 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8615 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8617 // Create some initial channels
8618 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8619 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8621 // Steps (1) and (2):
8622 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8623 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8625 // Check that Alice's commitment transaction now contains an output for this HTLC.
8626 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8627 check_spends!(alice_txn[0], chan_ab.3);
8628 assert_eq!(alice_txn[0].output.len(), 2);
8629 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8630 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8631 assert_eq!(alice_txn.len(), 2);
8633 // Steps (3) and (4):
8634 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8635 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8636 let mut force_closing_node = 0; // Alice force-closes
8637 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8638 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8639 check_closed_broadcast!(nodes[force_closing_node], false);
8640 check_added_monitors!(nodes[force_closing_node], 1);
8641 if go_onchain_before_fulfill {
8642 let txn_to_broadcast = match broadcast_alice {
8643 true => alice_txn.clone(),
8644 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8646 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8647 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8648 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8649 if broadcast_alice {
8650 check_closed_broadcast!(nodes[1], false);
8651 check_added_monitors!(nodes[1], 1);
8653 assert_eq!(bob_txn.len(), 1);
8654 check_spends!(bob_txn[0], chan_ab.3);
8658 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8659 // process of removing the HTLC from their commitment transactions.
8660 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8661 check_added_monitors!(nodes[2], 1);
8662 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8663 assert!(carol_updates.update_add_htlcs.is_empty());
8664 assert!(carol_updates.update_fail_htlcs.is_empty());
8665 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8666 assert!(carol_updates.update_fee.is_none());
8667 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8669 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8670 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8671 if !go_onchain_before_fulfill && broadcast_alice {
8672 let events = nodes[1].node.get_and_clear_pending_msg_events();
8673 assert_eq!(events.len(), 1);
8675 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8676 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8678 _ => panic!("Unexpected event"),
8681 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8682 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8683 // Carol<->Bob's updated commitment transaction info.
8684 check_added_monitors!(nodes[1], 2);
8686 let events = nodes[1].node.get_and_clear_pending_msg_events();
8687 assert_eq!(events.len(), 2);
8688 let bob_revocation = match events[0] {
8689 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8690 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8693 _ => panic!("Unexpected event"),
8695 let bob_updates = match events[1] {
8696 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8697 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8700 _ => panic!("Unexpected event"),
8703 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8704 check_added_monitors!(nodes[2], 1);
8705 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8706 check_added_monitors!(nodes[2], 1);
8708 let events = nodes[2].node.get_and_clear_pending_msg_events();
8709 assert_eq!(events.len(), 1);
8710 let carol_revocation = match events[0] {
8711 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8712 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8715 _ => panic!("Unexpected event"),
8717 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8718 check_added_monitors!(nodes[1], 1);
8720 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8721 // here's where we put said channel's commitment tx on-chain.
8722 let mut txn_to_broadcast = alice_txn.clone();
8723 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8724 if !go_onchain_before_fulfill {
8725 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8726 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8727 // If Bob was the one to force-close, he will have already passed these checks earlier.
8728 if broadcast_alice {
8729 check_closed_broadcast!(nodes[1], false);
8730 check_added_monitors!(nodes[1], 1);
8732 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8733 if broadcast_alice {
8734 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8735 // new block being connected. The ChannelManager being notified triggers a monitor update,
8736 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8737 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8739 assert_eq!(bob_txn.len(), 3);
8740 check_spends!(bob_txn[1], chan_ab.3);
8742 assert_eq!(bob_txn.len(), 2);
8743 check_spends!(bob_txn[0], chan_ab.3);
8748 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8749 // broadcasted commitment transaction.
8751 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8752 if go_onchain_before_fulfill {
8753 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8754 assert_eq!(bob_txn.len(), 2);
8756 let script_weight = match broadcast_alice {
8757 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8758 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8760 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8761 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8762 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8763 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8764 if broadcast_alice && !go_onchain_before_fulfill {
8765 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8766 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8768 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8769 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8775 fn test_onchain_htlc_settlement_after_close() {
8776 do_test_onchain_htlc_settlement_after_close(true, true);
8777 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8778 do_test_onchain_htlc_settlement_after_close(true, false);
8779 do_test_onchain_htlc_settlement_after_close(false, false);
8783 fn test_duplicate_chan_id() {
8784 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8785 // already open we reject it and keep the old channel.
8787 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8788 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8789 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8790 // updating logic for the existing channel.
8791 let chanmon_cfgs = create_chanmon_cfgs(2);
8792 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8793 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8794 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8796 // Create an initial channel
8797 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8798 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8799 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8800 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()));
8802 // Try to create a second channel with the same temporary_channel_id as the first and check
8803 // that it is rejected.
8804 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8806 let events = nodes[1].node.get_and_clear_pending_msg_events();
8807 assert_eq!(events.len(), 1);
8809 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8810 // Technically, at this point, nodes[1] would be justified in thinking both the
8811 // first (valid) and second (invalid) channels are closed, given they both have
8812 // the same non-temporary channel_id. However, currently we do not, so we just
8813 // move forward with it.
8814 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8815 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8817 _ => panic!("Unexpected event"),
8821 // Move the first channel through the funding flow...
8822 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8824 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8825 check_added_monitors!(nodes[0], 0);
8827 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8828 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8830 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8831 assert_eq!(added_monitors.len(), 1);
8832 assert_eq!(added_monitors[0].0, funding_output);
8833 added_monitors.clear();
8835 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8837 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8838 let channel_id = funding_outpoint.to_channel_id();
8840 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8843 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8844 // Technically this is allowed by the spec, but we don't support it and there's little reason
8845 // to. Still, it shouldn't cause any other issues.
8846 open_chan_msg.temporary_channel_id = channel_id;
8847 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8849 let events = nodes[1].node.get_and_clear_pending_msg_events();
8850 assert_eq!(events.len(), 1);
8852 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8853 // Technically, at this point, nodes[1] would be justified in thinking both
8854 // channels are closed, but currently we do not, so we just move forward with it.
8855 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8856 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8858 _ => panic!("Unexpected event"),
8862 // Now try to create a second channel which has a duplicate funding output.
8863 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8864 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8865 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8866 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()));
8867 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8869 let funding_created = {
8870 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8871 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8872 let logger = test_utils::TestLogger::new();
8873 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8875 check_added_monitors!(nodes[0], 0);
8876 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8877 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8878 // still needs to be cleared here.
8879 check_added_monitors!(nodes[1], 1);
8881 // ...still, nodes[1] will reject the duplicate channel.
8883 let events = nodes[1].node.get_and_clear_pending_msg_events();
8884 assert_eq!(events.len(), 1);
8886 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8887 // Technically, at this point, nodes[1] would be justified in thinking both
8888 // channels are closed, but currently we do not, so we just move forward with it.
8889 assert_eq!(msg.channel_id, channel_id);
8890 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8892 _ => panic!("Unexpected event"),
8896 // finally, finish creating the original channel and send a payment over it to make sure
8897 // everything is functional.
8898 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8900 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8901 assert_eq!(added_monitors.len(), 1);
8902 assert_eq!(added_monitors[0].0, funding_output);
8903 added_monitors.clear();
8906 let events_4 = nodes[0].node.get_and_clear_pending_events();
8907 assert_eq!(events_4.len(), 1);
8909 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8910 assert_eq!(user_channel_id, 42);
8911 assert_eq!(*funding_txo, funding_output);
8913 _ => panic!("Unexpected event"),
8916 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8917 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8918 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8919 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8923 fn test_error_chans_closed() {
8924 // Test that we properly handle error messages, closing appropriate channels.
8926 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8927 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8928 // we can test various edge cases around it to ensure we don't regress.
8929 let chanmon_cfgs = create_chanmon_cfgs(3);
8930 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8931 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8932 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8934 // Create some initial channels
8935 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8936 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8937 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8939 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8940 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8941 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8943 // Closing a channel from a different peer has no effect
8944 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8945 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8947 // Closing one channel doesn't impact others
8948 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8949 check_added_monitors!(nodes[0], 1);
8950 check_closed_broadcast!(nodes[0], false);
8951 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8952 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);
8953 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);
8955 // A null channel ID should close all channels
8956 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8957 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8958 check_added_monitors!(nodes[0], 2);
8959 let events = nodes[0].node.get_and_clear_pending_msg_events();
8960 assert_eq!(events.len(), 2);
8962 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8963 assert_eq!(msg.contents.flags & 2, 2);
8965 _ => panic!("Unexpected event"),
8968 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8969 assert_eq!(msg.contents.flags & 2, 2);
8971 _ => panic!("Unexpected event"),
8973 // Note that at this point users of a standard PeerHandler will end up calling
8974 // peer_disconnected with no_connection_possible set to false, duplicating the
8975 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8976 // users with their own peer handling logic. We duplicate the call here, however.
8977 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8978 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8980 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8981 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8982 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);