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;
60 fn test_insane_channel_opens() {
61 // Stand up a network of 2 nodes
62 let chanmon_cfgs = create_chanmon_cfgs(2);
63 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
64 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
65 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
67 // Instantiate channel parameters where we push the maximum msats given our
69 let channel_value_sat = 31337; // same as funding satoshis
70 let channel_reserve_satoshis = Channel::<EnforcingSigner>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
71 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
73 // Have node0 initiate a channel to node1 with aforementioned parameters
74 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
76 // Extract the channel open message from node0 to node1
77 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
79 // Test helper that asserts we get the correct error string given a mutator
80 // that supposedly makes the channel open message insane
81 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
82 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
83 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
84 assert_eq!(msg_events.len(), 1);
85 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
86 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
88 &ErrorAction::SendErrorMessage { .. } => {
89 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
91 _ => panic!("unexpected event!"),
93 } else { assert!(false); }
96 use ln::channel::MAX_FUNDING_SATOSHIS;
97 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
99 // Test all mutations that would make the channel open message insane
100 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
102 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
104 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
106 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
108 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
110 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
112 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
114 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
116 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
120 fn test_async_inbound_update_fee() {
121 let chanmon_cfgs = create_chanmon_cfgs(2);
122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
124 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
125 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
126 let logger = test_utils::TestLogger::new();
127 let channel_id = chan.2;
130 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
134 // send (1) commitment_signed -.
135 // <- update_add_htlc/commitment_signed
136 // send (2) RAA (awaiting remote revoke) -.
137 // (1) commitment_signed is delivered ->
138 // .- send (3) RAA (awaiting remote revoke)
139 // (2) RAA is delivered ->
140 // .- send (4) commitment_signed
141 // <- (3) RAA is delivered
142 // send (5) commitment_signed -.
143 // <- (4) commitment_signed is delivered
145 // (5) commitment_signed is delivered ->
147 // (6) RAA is delivered ->
149 // First nodes[0] generates an update_fee
150 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
151 check_added_monitors!(nodes[0], 1);
153 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
154 assert_eq!(events_0.len(), 1);
155 let (update_msg, commitment_signed) = match events_0[0] { // (1)
156 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
157 (update_fee.as_ref(), commitment_signed)
159 _ => panic!("Unexpected event"),
162 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
164 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
165 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
166 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
167 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
168 check_added_monitors!(nodes[1], 1);
170 let payment_event = {
171 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
172 assert_eq!(events_1.len(), 1);
173 SendEvent::from_event(events_1.remove(0))
175 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
176 assert_eq!(payment_event.msgs.len(), 1);
178 // ...now when the messages get delivered everyone should be happy
179 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
180 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
181 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
182 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
183 check_added_monitors!(nodes[0], 1);
185 // deliver(1), generate (3):
186 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
187 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
188 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
189 check_added_monitors!(nodes[1], 1);
191 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
192 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
193 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
194 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
195 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
196 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
197 assert!(bs_update.update_fee.is_none()); // (4)
198 check_added_monitors!(nodes[1], 1);
200 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
201 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
202 assert!(as_update.update_add_htlcs.is_empty()); // (5)
203 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
204 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
205 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
206 assert!(as_update.update_fee.is_none()); // (5)
207 check_added_monitors!(nodes[0], 1);
209 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
210 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
211 // only (6) so get_event_msg's assert(len == 1) passes
212 check_added_monitors!(nodes[0], 1);
214 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
215 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
216 check_added_monitors!(nodes[1], 1);
218 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
219 check_added_monitors!(nodes[0], 1);
221 let events_2 = nodes[0].node.get_and_clear_pending_events();
222 assert_eq!(events_2.len(), 1);
224 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
225 _ => panic!("Unexpected event"),
228 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
229 check_added_monitors!(nodes[1], 1);
233 fn test_update_fee_unordered_raa() {
234 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
235 // crash in an earlier version of the update_fee patch)
236 let chanmon_cfgs = create_chanmon_cfgs(2);
237 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
238 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
239 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
240 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
241 let channel_id = chan.2;
242 let logger = test_utils::TestLogger::new();
245 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
247 // First nodes[0] generates an update_fee
248 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
249 check_added_monitors!(nodes[0], 1);
251 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
252 assert_eq!(events_0.len(), 1);
253 let update_msg = match events_0[0] { // (1)
254 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
257 _ => panic!("Unexpected event"),
260 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
262 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
263 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
264 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
265 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
266 check_added_monitors!(nodes[1], 1);
268 let payment_event = {
269 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
270 assert_eq!(events_1.len(), 1);
271 SendEvent::from_event(events_1.remove(0))
273 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
274 assert_eq!(payment_event.msgs.len(), 1);
276 // ...now when the messages get delivered everyone should be happy
277 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
278 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
279 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
280 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
281 check_added_monitors!(nodes[0], 1);
283 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
284 check_added_monitors!(nodes[1], 1);
286 // We can't continue, sadly, because our (1) now has a bogus signature
290 fn test_multi_flight_update_fee() {
291 let chanmon_cfgs = create_chanmon_cfgs(2);
292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
294 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
295 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
296 let channel_id = chan.2;
299 // update_fee/commitment_signed ->
300 // .- send (1) RAA and (2) commitment_signed
301 // update_fee (never committed) ->
303 // We have to manually generate the above update_fee, it is allowed by the protocol but we
304 // don't track which updates correspond to which revoke_and_ack responses so we're in
305 // AwaitingRAA mode and will not generate the update_fee yet.
306 // <- (1) RAA delivered
307 // (3) is generated and send (4) CS -.
308 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
309 // know the per_commitment_point to use for it.
310 // <- (2) commitment_signed delivered
312 // B should send no response here
313 // (4) commitment_signed delivered ->
314 // <- RAA/commitment_signed delivered
317 // First nodes[0] generates an update_fee
318 let initial_feerate = get_feerate!(nodes[0], channel_id);
319 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
320 check_added_monitors!(nodes[0], 1);
322 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
323 assert_eq!(events_0.len(), 1);
324 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
325 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
326 (update_fee.as_ref().unwrap(), commitment_signed)
328 _ => panic!("Unexpected event"),
331 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
332 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
333 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
334 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
335 check_added_monitors!(nodes[1], 1);
337 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
339 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
340 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
341 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
343 // Create the (3) update_fee message that nodes[0] will generate before it does...
344 let mut update_msg_2 = msgs::UpdateFee {
345 channel_id: update_msg_1.channel_id.clone(),
346 feerate_per_kw: (initial_feerate + 30) as u32,
349 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
353 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355 // Deliver (1), generating (3) and (4)
356 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
357 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
358 check_added_monitors!(nodes[0], 1);
359 assert!(as_second_update.update_add_htlcs.is_empty());
360 assert!(as_second_update.update_fulfill_htlcs.is_empty());
361 assert!(as_second_update.update_fail_htlcs.is_empty());
362 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
363 // Check that the update_fee newly generated matches what we delivered:
364 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
365 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
367 // Deliver (2) commitment_signed
368 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
369 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
370 check_added_monitors!(nodes[0], 1);
371 // No commitment_signed so get_event_msg's assert(len == 1) passes
373 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
374 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
375 check_added_monitors!(nodes[1], 1);
378 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
379 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
380 check_added_monitors!(nodes[1], 1);
382 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
383 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
384 check_added_monitors!(nodes[0], 1);
386 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
387 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
388 // No commitment_signed so get_event_msg's assert(len == 1) passes
389 check_added_monitors!(nodes[0], 1);
391 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
392 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
393 check_added_monitors!(nodes[1], 1);
397 fn test_1_conf_open() {
398 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
399 // tests that we properly send one in that case.
400 let mut alice_config = UserConfig::default();
401 alice_config.own_channel_config.minimum_depth = 1;
402 alice_config.channel_options.announced_channel = true;
403 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
404 let mut bob_config = UserConfig::default();
405 bob_config.own_channel_config.minimum_depth = 1;
406 bob_config.channel_options.announced_channel = true;
407 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
408 let chanmon_cfgs = create_chanmon_cfgs(2);
409 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
410 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
411 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
413 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
415 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
418 connect_block(&nodes[1], &block, 1);
419 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
421 connect_block(&nodes[0], &block, 1);
422 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
423 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
426 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
427 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
428 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
432 fn do_test_sanity_on_in_flight_opens(steps: u8) {
433 // Previously, we had issues deserializing channels when we hadn't connected the first block
434 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
435 // serialization round-trips and simply do steps towards opening a channel and then drop the
438 let chanmon_cfgs = create_chanmon_cfgs(2);
439 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
440 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
441 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
443 if steps & 0b1000_0000 != 0{
445 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
448 connect_block(&nodes[0], &block, 1);
449 connect_block(&nodes[1], &block, 1);
452 if steps & 0x0f == 0 { return; }
453 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
454 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
456 if steps & 0x0f == 1 { return; }
457 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
458 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
460 if steps & 0x0f == 2 { return; }
461 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
463 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
465 if steps & 0x0f == 3 { return; }
466 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
467 check_added_monitors!(nodes[0], 0);
468 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
470 if steps & 0x0f == 4 { return; }
471 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
473 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
474 assert_eq!(added_monitors.len(), 1);
475 assert_eq!(added_monitors[0].0, funding_output);
476 added_monitors.clear();
478 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
480 if steps & 0x0f == 5 { return; }
481 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
483 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
484 assert_eq!(added_monitors.len(), 1);
485 assert_eq!(added_monitors[0].0, funding_output);
486 added_monitors.clear();
489 let events_4 = nodes[0].node.get_and_clear_pending_events();
490 assert_eq!(events_4.len(), 1);
492 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
493 assert_eq!(user_channel_id, 42);
494 assert_eq!(*funding_txo, funding_output);
496 _ => panic!("Unexpected event"),
499 if steps & 0x0f == 6 { return; }
500 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
502 if steps & 0x0f == 7 { return; }
503 confirm_transaction(&nodes[0], &tx);
504 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
508 fn test_sanity_on_in_flight_opens() {
509 do_test_sanity_on_in_flight_opens(0);
510 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
511 do_test_sanity_on_in_flight_opens(1);
512 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
513 do_test_sanity_on_in_flight_opens(2);
514 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
515 do_test_sanity_on_in_flight_opens(3);
516 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
517 do_test_sanity_on_in_flight_opens(4);
518 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
519 do_test_sanity_on_in_flight_opens(5);
520 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
521 do_test_sanity_on_in_flight_opens(6);
522 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
523 do_test_sanity_on_in_flight_opens(7);
524 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
525 do_test_sanity_on_in_flight_opens(8);
526 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
530 fn test_update_fee_vanilla() {
531 let chanmon_cfgs = create_chanmon_cfgs(2);
532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
534 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
535 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
536 let channel_id = chan.2;
538 let feerate = get_feerate!(nodes[0], channel_id);
539 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
540 check_added_monitors!(nodes[0], 1);
542 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
543 assert_eq!(events_0.len(), 1);
544 let (update_msg, commitment_signed) = match events_0[0] {
545 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
546 (update_fee.as_ref(), commitment_signed)
548 _ => panic!("Unexpected event"),
550 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
552 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
553 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
554 check_added_monitors!(nodes[1], 1);
556 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
557 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
558 check_added_monitors!(nodes[0], 1);
560 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
561 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
562 // No commitment_signed so get_event_msg's assert(len == 1) passes
563 check_added_monitors!(nodes[0], 1);
565 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
566 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
567 check_added_monitors!(nodes[1], 1);
571 fn test_update_fee_that_funder_cannot_afford() {
572 let chanmon_cfgs = create_chanmon_cfgs(2);
573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
575 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
576 let channel_value = 1888;
577 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
578 let channel_id = chan.2;
581 nodes[0].node.update_fee(channel_id, feerate).unwrap();
582 check_added_monitors!(nodes[0], 1);
583 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
585 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
587 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
589 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
590 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
592 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
594 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
595 let num_htlcs = commitment_tx.output.len() - 2;
596 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
597 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
598 actual_fee = channel_value - actual_fee;
599 assert_eq!(total_fee, actual_fee);
602 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
603 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
604 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
605 check_added_monitors!(nodes[0], 1);
607 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
609 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
611 //While producing the commitment_signed response after handling a received update_fee request the
612 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
613 //Should produce and error.
614 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
615 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
616 check_added_monitors!(nodes[1], 1);
617 check_closed_broadcast!(nodes[1], true);
621 fn test_update_fee_with_fundee_update_add_htlc() {
622 let chanmon_cfgs = create_chanmon_cfgs(2);
623 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
624 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
625 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
626 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
627 let channel_id = chan.2;
628 let logger = test_utils::TestLogger::new();
631 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
633 let feerate = get_feerate!(nodes[0], channel_id);
634 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
635 check_added_monitors!(nodes[0], 1);
637 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
638 assert_eq!(events_0.len(), 1);
639 let (update_msg, commitment_signed) = match events_0[0] {
640 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
641 (update_fee.as_ref(), commitment_signed)
643 _ => panic!("Unexpected event"),
645 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
646 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
647 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
648 check_added_monitors!(nodes[1], 1);
650 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
651 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
652 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
654 // nothing happens since node[1] is in AwaitingRemoteRevoke
655 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
657 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
658 assert_eq!(added_monitors.len(), 0);
659 added_monitors.clear();
661 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
662 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
663 // node[1] has nothing to do
665 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
666 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
667 check_added_monitors!(nodes[0], 1);
669 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
670 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
671 // No commitment_signed so get_event_msg's assert(len == 1) passes
672 check_added_monitors!(nodes[0], 1);
673 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
674 check_added_monitors!(nodes[1], 1);
675 // AwaitingRemoteRevoke ends here
677 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
678 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
679 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
680 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
681 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
682 assert_eq!(commitment_update.update_fee.is_none(), true);
684 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
685 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
686 check_added_monitors!(nodes[0], 1);
687 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
689 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
690 check_added_monitors!(nodes[1], 1);
691 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
693 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
694 check_added_monitors!(nodes[1], 1);
695 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
696 // No commitment_signed so get_event_msg's assert(len == 1) passes
698 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
699 check_added_monitors!(nodes[0], 1);
700 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
702 expect_pending_htlcs_forwardable!(nodes[0]);
704 let events = nodes[0].node.get_and_clear_pending_events();
705 assert_eq!(events.len(), 1);
707 Event::PaymentReceived { .. } => { },
708 _ => panic!("Unexpected event"),
711 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
713 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
714 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
715 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
719 fn test_update_fee() {
720 let chanmon_cfgs = create_chanmon_cfgs(2);
721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
723 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
724 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
725 let channel_id = chan.2;
728 // (1) update_fee/commitment_signed ->
729 // <- (2) revoke_and_ack
730 // .- send (3) commitment_signed
731 // (4) update_fee/commitment_signed ->
732 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
733 // <- (3) commitment_signed delivered
734 // send (6) revoke_and_ack -.
735 // <- (5) deliver revoke_and_ack
736 // (6) deliver revoke_and_ack ->
737 // .- send (7) commitment_signed in response to (4)
738 // <- (7) deliver commitment_signed
741 // Create and deliver (1)...
742 let feerate = get_feerate!(nodes[0], channel_id);
743 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
744 check_added_monitors!(nodes[0], 1);
746 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
747 assert_eq!(events_0.len(), 1);
748 let (update_msg, commitment_signed) = match events_0[0] {
749 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
750 (update_fee.as_ref(), commitment_signed)
752 _ => panic!("Unexpected event"),
754 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
756 // Generate (2) and (3):
757 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
758 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
759 check_added_monitors!(nodes[1], 1);
762 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
763 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
764 check_added_monitors!(nodes[0], 1);
766 // Create and deliver (4)...
767 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
768 check_added_monitors!(nodes[0], 1);
769 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
770 assert_eq!(events_0.len(), 1);
771 let (update_msg, commitment_signed) = match events_0[0] {
772 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
773 (update_fee.as_ref(), commitment_signed)
775 _ => panic!("Unexpected event"),
778 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
779 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
780 check_added_monitors!(nodes[1], 1);
782 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
783 // No commitment_signed so get_event_msg's assert(len == 1) passes
785 // Handle (3), creating (6):
786 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
787 check_added_monitors!(nodes[0], 1);
788 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
789 // No commitment_signed so get_event_msg's assert(len == 1) passes
792 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
793 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
794 check_added_monitors!(nodes[0], 1);
796 // Deliver (6), creating (7):
797 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
798 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
799 assert!(commitment_update.update_add_htlcs.is_empty());
800 assert!(commitment_update.update_fulfill_htlcs.is_empty());
801 assert!(commitment_update.update_fail_htlcs.is_empty());
802 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
803 assert!(commitment_update.update_fee.is_none());
804 check_added_monitors!(nodes[1], 1);
807 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
808 check_added_monitors!(nodes[0], 1);
809 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
810 // No commitment_signed so get_event_msg's assert(len == 1) passes
812 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
813 check_added_monitors!(nodes[1], 1);
814 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
816 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
817 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
818 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
822 fn pre_funding_lock_shutdown_test() {
823 // Test sending a shutdown prior to funding_locked after funding generation
824 let chanmon_cfgs = create_chanmon_cfgs(2);
825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
827 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
828 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
829 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
830 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
831 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
833 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
834 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
835 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
836 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
837 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
839 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
840 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
841 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
842 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
843 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
844 assert!(node_0_none.is_none());
846 assert!(nodes[0].node.list_channels().is_empty());
847 assert!(nodes[1].node.list_channels().is_empty());
851 fn updates_shutdown_wait() {
852 // Test sending a shutdown with outstanding updates pending
853 let chanmon_cfgs = create_chanmon_cfgs(3);
854 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
855 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
856 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
857 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
858 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
859 let logger = test_utils::TestLogger::new();
861 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
863 nodes[0].node.close_channel(&chan_1.2).unwrap();
864 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
865 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
866 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
867 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
872 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
874 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
875 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
876 let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
877 let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
878 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
879 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
881 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
882 check_added_monitors!(nodes[2], 1);
883 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
884 assert!(updates.update_add_htlcs.is_empty());
885 assert!(updates.update_fail_htlcs.is_empty());
886 assert!(updates.update_fail_malformed_htlcs.is_empty());
887 assert!(updates.update_fee.is_none());
888 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
889 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
890 check_added_monitors!(nodes[1], 1);
891 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
892 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
894 assert!(updates_2.update_add_htlcs.is_empty());
895 assert!(updates_2.update_fail_htlcs.is_empty());
896 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
897 assert!(updates_2.update_fee.is_none());
898 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
899 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
900 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
902 let events = nodes[0].node.get_and_clear_pending_events();
903 assert_eq!(events.len(), 1);
905 Event::PaymentSent { ref payment_preimage } => {
906 assert_eq!(our_payment_preimage, *payment_preimage);
908 _ => panic!("Unexpected event"),
911 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
912 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
913 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
914 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
915 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
916 assert!(node_0_none.is_none());
918 assert!(nodes[0].node.list_channels().is_empty());
920 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
921 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
922 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
923 assert!(nodes[1].node.list_channels().is_empty());
924 assert!(nodes[2].node.list_channels().is_empty());
928 fn htlc_fail_async_shutdown() {
929 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
930 let chanmon_cfgs = create_chanmon_cfgs(3);
931 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
932 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
933 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
934 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
935 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
936 let logger = test_utils::TestLogger::new();
938 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
939 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
940 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
941 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
942 check_added_monitors!(nodes[0], 1);
943 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
944 assert_eq!(updates.update_add_htlcs.len(), 1);
945 assert!(updates.update_fulfill_htlcs.is_empty());
946 assert!(updates.update_fail_htlcs.is_empty());
947 assert!(updates.update_fail_malformed_htlcs.is_empty());
948 assert!(updates.update_fee.is_none());
950 nodes[1].node.close_channel(&chan_1.2).unwrap();
951 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
952 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
953 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
955 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
956 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
957 check_added_monitors!(nodes[1], 1);
958 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
959 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
961 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
962 assert!(updates_2.update_add_htlcs.is_empty());
963 assert!(updates_2.update_fulfill_htlcs.is_empty());
964 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
965 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
966 assert!(updates_2.update_fee.is_none());
968 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
969 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
971 expect_payment_failed!(nodes[0], our_payment_hash, false);
973 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
974 assert_eq!(msg_events.len(), 2);
975 let node_0_closing_signed = match msg_events[0] {
976 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
977 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
980 _ => panic!("Unexpected event"),
982 match msg_events[1] {
983 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
984 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
986 _ => panic!("Unexpected event"),
989 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
990 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
991 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
992 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
993 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
994 assert!(node_0_none.is_none());
996 assert!(nodes[0].node.list_channels().is_empty());
998 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
999 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1000 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1001 assert!(nodes[1].node.list_channels().is_empty());
1002 assert!(nodes[2].node.list_channels().is_empty());
1005 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1006 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1007 // messages delivered prior to disconnect
1008 let chanmon_cfgs = create_chanmon_cfgs(3);
1009 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1010 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1011 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1012 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1013 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1015 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1017 nodes[1].node.close_channel(&chan_1.2).unwrap();
1018 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1020 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1021 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1023 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1027 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1030 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1031 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1032 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1033 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1035 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1036 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1037 assert!(node_1_shutdown == node_1_2nd_shutdown);
1039 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1040 let node_0_2nd_shutdown = if recv_count > 0 {
1041 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1042 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1045 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1046 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1047 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1049 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1051 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1052 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1054 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1055 check_added_monitors!(nodes[2], 1);
1056 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1057 assert!(updates.update_add_htlcs.is_empty());
1058 assert!(updates.update_fail_htlcs.is_empty());
1059 assert!(updates.update_fail_malformed_htlcs.is_empty());
1060 assert!(updates.update_fee.is_none());
1061 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1062 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1063 check_added_monitors!(nodes[1], 1);
1064 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1065 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1067 assert!(updates_2.update_add_htlcs.is_empty());
1068 assert!(updates_2.update_fail_htlcs.is_empty());
1069 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1070 assert!(updates_2.update_fee.is_none());
1071 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1072 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1073 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1075 let events = nodes[0].node.get_and_clear_pending_events();
1076 assert_eq!(events.len(), 1);
1078 Event::PaymentSent { ref payment_preimage } => {
1079 assert_eq!(our_payment_preimage, *payment_preimage);
1081 _ => panic!("Unexpected event"),
1084 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1086 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1087 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1088 assert!(node_1_closing_signed.is_some());
1091 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1092 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1094 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1095 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1096 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1097 if recv_count == 0 {
1098 // If all closing_signeds weren't delivered we can just resume where we left off...
1099 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1101 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1102 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1103 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1105 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1106 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1107 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1109 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1110 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1112 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1113 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1114 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1116 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1117 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1118 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1119 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1120 assert!(node_0_none.is_none());
1122 // If one node, however, received + responded with an identical closing_signed we end
1123 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1124 // There isn't really anything better we can do simply, but in the future we might
1125 // explore storing a set of recently-closed channels that got disconnected during
1126 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1127 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1129 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1131 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1132 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1133 assert_eq!(msg_events.len(), 1);
1134 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1136 &ErrorAction::SendErrorMessage { ref msg } => {
1137 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1138 assert_eq!(msg.channel_id, chan_1.2);
1140 _ => panic!("Unexpected event!"),
1142 } else { panic!("Needed SendErrorMessage close"); }
1144 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1145 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1146 // closing_signed so we do it ourselves
1147 check_closed_broadcast!(nodes[0], false);
1148 check_added_monitors!(nodes[0], 1);
1151 assert!(nodes[0].node.list_channels().is_empty());
1153 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1154 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1155 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1156 assert!(nodes[1].node.list_channels().is_empty());
1157 assert!(nodes[2].node.list_channels().is_empty());
1161 fn test_shutdown_rebroadcast() {
1162 do_test_shutdown_rebroadcast(0);
1163 do_test_shutdown_rebroadcast(1);
1164 do_test_shutdown_rebroadcast(2);
1168 fn fake_network_test() {
1169 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1170 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1171 let chanmon_cfgs = create_chanmon_cfgs(4);
1172 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1173 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1174 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1176 // Create some initial channels
1177 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1178 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1179 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1181 // Rebalance the network a bit by relaying one payment through all the channels...
1182 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1183 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1184 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1185 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1187 // Send some more payments
1188 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1189 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1190 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1192 // Test failure packets
1193 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1194 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1196 // Add a new channel that skips 3
1197 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1199 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1200 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1201 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1203 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1204 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1205 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207 // Do some rebalance loop payments, simultaneously
1208 let mut hops = Vec::with_capacity(3);
1209 hops.push(RouteHop {
1210 pubkey: nodes[2].node.get_our_node_id(),
1211 node_features: NodeFeatures::empty(),
1212 short_channel_id: chan_2.0.contents.short_channel_id,
1213 channel_features: ChannelFeatures::empty(),
1215 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1217 hops.push(RouteHop {
1218 pubkey: nodes[3].node.get_our_node_id(),
1219 node_features: NodeFeatures::empty(),
1220 short_channel_id: chan_3.0.contents.short_channel_id,
1221 channel_features: ChannelFeatures::empty(),
1223 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1225 hops.push(RouteHop {
1226 pubkey: nodes[1].node.get_our_node_id(),
1227 node_features: NodeFeatures::empty(),
1228 short_channel_id: chan_4.0.contents.short_channel_id,
1229 channel_features: ChannelFeatures::empty(),
1231 cltv_expiry_delta: TEST_FINAL_CLTV,
1233 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1234 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1235 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1237 let mut hops = Vec::with_capacity(3);
1238 hops.push(RouteHop {
1239 pubkey: nodes[3].node.get_our_node_id(),
1240 node_features: NodeFeatures::empty(),
1241 short_channel_id: chan_4.0.contents.short_channel_id,
1242 channel_features: ChannelFeatures::empty(),
1244 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1246 hops.push(RouteHop {
1247 pubkey: nodes[2].node.get_our_node_id(),
1248 node_features: NodeFeatures::empty(),
1249 short_channel_id: chan_3.0.contents.short_channel_id,
1250 channel_features: ChannelFeatures::empty(),
1252 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1254 hops.push(RouteHop {
1255 pubkey: nodes[1].node.get_our_node_id(),
1256 node_features: NodeFeatures::empty(),
1257 short_channel_id: chan_2.0.contents.short_channel_id,
1258 channel_features: ChannelFeatures::empty(),
1260 cltv_expiry_delta: TEST_FINAL_CLTV,
1262 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1263 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1264 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1266 // Claim the rebalances...
1267 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1268 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1270 // Add a duplicate new channel from 2 to 4
1271 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1273 // Send some payments across both channels
1274 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1275 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1276 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1280 let events = nodes[0].node.get_and_clear_pending_msg_events();
1281 assert_eq!(events.len(), 0);
1282 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1284 //TODO: Test that routes work again here as we've been notified that the channel is full
1286 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1287 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1288 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1290 // Close down the channels...
1291 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1292 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1293 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1294 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1295 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1299 fn holding_cell_htlc_counting() {
1300 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1301 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1302 // commitment dance rounds.
1303 let chanmon_cfgs = create_chanmon_cfgs(3);
1304 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1305 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1306 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1307 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1308 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1309 let logger = test_utils::TestLogger::new();
1311 let mut payments = Vec::new();
1312 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1313 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1314 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1315 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1316 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1317 payments.push((payment_preimage, payment_hash));
1319 check_added_monitors!(nodes[1], 1);
1321 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1322 assert_eq!(events.len(), 1);
1323 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1324 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1326 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1327 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1329 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1331 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1332 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1333 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1334 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1335 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1336 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1339 // This should also be true if we try to forward a payment.
1340 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1342 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1343 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1344 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1345 check_added_monitors!(nodes[0], 1);
1348 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1349 assert_eq!(events.len(), 1);
1350 let payment_event = SendEvent::from_event(events.pop().unwrap());
1351 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1353 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1354 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1355 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1356 // fails), the second will process the resulting failure and fail the HTLC backward.
1357 expect_pending_htlcs_forwardable!(nodes[1]);
1358 expect_pending_htlcs_forwardable!(nodes[1]);
1359 check_added_monitors!(nodes[1], 1);
1361 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1362 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1363 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1365 let events = nodes[0].node.get_and_clear_pending_msg_events();
1366 assert_eq!(events.len(), 1);
1368 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1369 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1371 _ => panic!("Unexpected event"),
1374 expect_payment_failed!(nodes[0], payment_hash_2, false);
1376 // Now forward all the pending HTLCs and claim them back
1377 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1378 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1379 check_added_monitors!(nodes[2], 1);
1381 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1382 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1383 check_added_monitors!(nodes[1], 1);
1384 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1386 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1387 check_added_monitors!(nodes[1], 1);
1388 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1390 for ref update in as_updates.update_add_htlcs.iter() {
1391 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1393 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1394 check_added_monitors!(nodes[2], 1);
1395 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1396 check_added_monitors!(nodes[2], 1);
1397 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1399 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1400 check_added_monitors!(nodes[1], 1);
1401 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1402 check_added_monitors!(nodes[1], 1);
1403 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1405 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1406 check_added_monitors!(nodes[2], 1);
1408 expect_pending_htlcs_forwardable!(nodes[2]);
1410 let events = nodes[2].node.get_and_clear_pending_events();
1411 assert_eq!(events.len(), payments.len());
1412 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1414 &Event::PaymentReceived { ref payment_hash, .. } => {
1415 assert_eq!(*payment_hash, *hash);
1417 _ => panic!("Unexpected event"),
1421 for (preimage, _) in payments.drain(..) {
1422 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1425 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1429 fn duplicate_htlc_test() {
1430 // Test that we accept duplicate payment_hash HTLCs across the network and that
1431 // claiming/failing them are all separate and don't affect each other
1432 let chanmon_cfgs = create_chanmon_cfgs(6);
1433 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1434 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1435 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1437 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1438 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1439 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1440 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1441 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1442 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1444 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1446 *nodes[0].network_payment_count.borrow_mut() -= 1;
1447 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1449 *nodes[0].network_payment_count.borrow_mut() -= 1;
1450 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1452 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1453 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1454 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1458 fn test_duplicate_htlc_different_direction_onchain() {
1459 // Test that ChannelMonitor doesn't generate 2 preimage txn
1460 // when we have 2 HTLCs with same preimage that go across a node
1461 // in opposite directions.
1462 let chanmon_cfgs = create_chanmon_cfgs(2);
1463 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1464 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1465 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1467 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1468 let logger = test_utils::TestLogger::new();
1471 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1473 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1475 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1476 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1477 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1479 // Provide preimage to node 0 by claiming payment
1480 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1481 check_added_monitors!(nodes[0], 1);
1483 // Broadcast node 1 commitment txn
1484 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1486 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1487 let mut has_both_htlcs = 0; // check htlcs match ones committed
1488 for outp in remote_txn[0].output.iter() {
1489 if outp.value == 800_000 / 1000 {
1490 has_both_htlcs += 1;
1491 } else if outp.value == 900_000 / 1000 {
1492 has_both_htlcs += 1;
1495 assert_eq!(has_both_htlcs, 2);
1497 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1498 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1499 check_added_monitors!(nodes[0], 1);
1501 // Check we only broadcast 1 timeout tx
1502 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1503 let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1504 assert_eq!(claim_txn.len(), 5);
1505 check_spends!(claim_txn[2], chan_1.3);
1506 check_spends!(claim_txn[3], claim_txn[2]);
1507 assert_eq!(htlc_pair.0.input.len(), 1);
1508 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1509 check_spends!(htlc_pair.0, remote_txn[0]);
1510 assert_eq!(htlc_pair.1.input.len(), 1);
1511 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1512 check_spends!(htlc_pair.1, remote_txn[0]);
1514 let events = nodes[0].node.get_and_clear_pending_msg_events();
1515 assert_eq!(events.len(), 2);
1518 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1519 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1520 assert!(update_add_htlcs.is_empty());
1521 assert!(update_fail_htlcs.is_empty());
1522 assert_eq!(update_fulfill_htlcs.len(), 1);
1523 assert!(update_fail_malformed_htlcs.is_empty());
1524 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1526 _ => panic!("Unexpected event"),
1532 fn test_basic_channel_reserve() {
1533 let chanmon_cfgs = create_chanmon_cfgs(2);
1534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1536 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1537 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1538 let logger = test_utils::TestLogger::new();
1540 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1541 let channel_reserve = chan_stat.channel_reserve_msat;
1543 // The 2* and +1 are for the fee spike reserve.
1544 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1545 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1546 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1547 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1548 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1549 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1551 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1553 &APIError::ChannelUnavailable{ref err} =>
1554 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1555 _ => panic!("Unexpected error variant"),
1558 _ => panic!("Unexpected error variant"),
1560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1561 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1563 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1567 fn test_fee_spike_violation_fails_htlc() {
1568 let chanmon_cfgs = create_chanmon_cfgs(2);
1569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1572 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1573 let logger = test_utils::TestLogger::new();
1575 macro_rules! get_route_and_payment_hash {
1576 ($recv_value: expr) => {{
1577 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1578 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1579 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1580 (route, payment_hash, payment_preimage)
1584 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1585 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1586 let secp_ctx = Secp256k1::new();
1587 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1589 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1591 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1592 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1593 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1594 let msg = msgs::UpdateAddHTLC {
1597 amount_msat: htlc_msat,
1598 payment_hash: payment_hash,
1599 cltv_expiry: htlc_cltv,
1600 onion_routing_packet: onion_packet,
1603 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1605 // Now manually create the commitment_signed message corresponding to the update_add
1606 // nodes[0] just sent. In the code for construction of this message, "local" refers
1607 // to the sender of the message, and "remote" refers to the receiver.
1609 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1611 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1613 // Get the EnforcingSigner for each channel, which will be used to (1) get the keys
1614 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1615 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1616 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1617 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1618 let chan_signer = local_chan.get_signer();
1619 let pubkeys = chan_signer.pubkeys();
1620 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1621 chan_signer.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1622 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1624 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
1625 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1626 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1627 let chan_signer = remote_chan.get_signer();
1628 let pubkeys = chan_signer.pubkeys();
1629 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1630 chan_signer.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1633 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1634 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1635 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1637 // Build the remote commitment transaction so we can sign it, and then later use the
1638 // signature for the commitment_signed message.
1639 let local_chan_balance = 1313;
1641 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1643 amount_msat: 3460001,
1644 cltv_expiry: htlc_cltv,
1646 transaction_output_index: Some(1),
1649 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1652 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1653 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1654 let local_chan_signer = local_chan.get_signer();
1655 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1659 commit_tx_keys.clone(),
1661 &mut vec![(accepted_htlc_info, ())],
1662 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1664 local_chan_signer.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1667 let commit_signed_msg = msgs::CommitmentSigned {
1670 htlc_signatures: res.1
1673 // Send the commitment_signed message to the nodes[1].
1674 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1675 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1677 // Send the RAA to nodes[1].
1678 let raa_msg = msgs::RevokeAndACK {
1680 per_commitment_secret: local_secret,
1681 next_per_commitment_point: next_local_point
1683 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1685 let events = nodes[1].node.get_and_clear_pending_msg_events();
1686 assert_eq!(events.len(), 1);
1687 // Make sure the HTLC failed in the way we expect.
1689 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1690 assert_eq!(update_fail_htlcs.len(), 1);
1691 update_fail_htlcs[0].clone()
1693 _ => panic!("Unexpected event"),
1695 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1697 check_added_monitors!(nodes[1], 2);
1701 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1702 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1703 // Set the fee rate for the channel very high, to the point where the fundee
1704 // sending any above-dust amount would result in a channel reserve violation.
1705 // In this test we check that we would be prevented from sending an HTLC in
1707 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1708 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1711 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1712 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1713 let logger = test_utils::TestLogger::new();
1715 macro_rules! get_route_and_payment_hash {
1716 ($recv_value: expr) => {{
1717 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1718 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1719 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1720 (route, payment_hash, payment_preimage)
1724 let (route, our_payment_hash, _) = get_route_and_payment_hash!(4843000);
1725 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1726 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1727 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1728 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1732 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1733 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1734 // Set the fee rate for the channel very high, to the point where the funder
1735 // receiving 1 update_add_htlc would result in them closing the channel due
1736 // to channel reserve violation. This close could also happen if the fee went
1737 // up a more realistic amount, but many HTLCs were outstanding at the time of
1738 // the update_add_htlc.
1739 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1740 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1741 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1742 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1743 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1745 let logger = test_utils::TestLogger::new();
1747 macro_rules! get_route_and_payment_hash {
1748 ($recv_value: expr) => {{
1749 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1750 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1751 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1752 (route, payment_hash, payment_preimage)
1756 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1757 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1758 let secp_ctx = Secp256k1::new();
1759 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1760 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1761 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1762 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1763 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1764 let msg = msgs::UpdateAddHTLC {
1767 amount_msat: htlc_msat + 1,
1768 payment_hash: payment_hash,
1769 cltv_expiry: htlc_cltv,
1770 onion_routing_packet: onion_packet,
1773 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1774 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1775 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1776 assert_eq!(nodes[0].node.list_channels().len(), 0);
1777 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1778 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1779 check_added_monitors!(nodes[0], 1);
1783 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1784 // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1785 // calculating our commitment transaction fee (this was previously broken).
1786 let chanmon_cfgs = create_chanmon_cfgs(2);
1787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1789 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1791 // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1792 // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1793 // transaction fee with 0 HTLCs (183 sats)).
1794 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98817000, InitFeatures::known(), InitFeatures::known());
1796 let dust_amt = 546000; // Dust amount
1797 // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1798 // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1799 // commitment transaction fee.
1800 let (_, _) = route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1804 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1805 // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1806 // calculating our counterparty's commitment transaction fee (this was previously broken).
1807 let chanmon_cfgs = create_chanmon_cfgs(2);
1808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1810 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000, InitFeatures::known(), InitFeatures::known());
1813 let payment_amt = 46000; // Dust amount
1814 // In the previous code, these first four payments would succeed.
1815 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1816 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1817 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1818 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1820 // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1821 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1822 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1823 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1824 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1825 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1827 // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1828 // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1829 // transaction fee and therefore perceived this next payment as a channel reserve violation.
1830 let (_, _) = route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1834 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1835 let chanmon_cfgs = create_chanmon_cfgs(3);
1836 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1838 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1839 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1840 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1841 let logger = test_utils::TestLogger::new();
1843 macro_rules! get_route_and_payment_hash {
1844 ($recv_value: expr) => {{
1845 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1846 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1847 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1848 (route, payment_hash, payment_preimage)
1853 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1854 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1855 let feerate = get_feerate!(nodes[0], chan.2);
1857 // Add a 2* and +1 for the fee spike reserve.
1858 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1859 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1860 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1862 // Add a pending HTLC.
1863 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1864 let payment_event_1 = {
1865 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1866 check_added_monitors!(nodes[0], 1);
1868 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1869 assert_eq!(events.len(), 1);
1870 SendEvent::from_event(events.remove(0))
1872 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1874 // Attempt to trigger a channel reserve violation --> payment failure.
1875 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1876 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1877 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1878 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1880 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1881 let secp_ctx = Secp256k1::new();
1882 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1883 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1884 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1885 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1886 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1887 let msg = msgs::UpdateAddHTLC {
1890 amount_msat: htlc_msat + 1,
1891 payment_hash: our_payment_hash_1,
1892 cltv_expiry: htlc_cltv,
1893 onion_routing_packet: onion_packet,
1896 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1897 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1898 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1899 assert_eq!(nodes[1].node.list_channels().len(), 1);
1900 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1901 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1902 check_added_monitors!(nodes[1], 1);
1906 fn test_inbound_outbound_capacity_is_not_zero() {
1907 let chanmon_cfgs = create_chanmon_cfgs(2);
1908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1911 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1912 let channels0 = node_chanmgrs[0].list_channels();
1913 let channels1 = node_chanmgrs[1].list_channels();
1914 assert_eq!(channels0.len(), 1);
1915 assert_eq!(channels1.len(), 1);
1917 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1918 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1920 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1921 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1924 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1925 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1929 fn test_channel_reserve_holding_cell_htlcs() {
1930 let chanmon_cfgs = create_chanmon_cfgs(3);
1931 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1932 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1933 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1934 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1935 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1936 let logger = test_utils::TestLogger::new();
1938 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1939 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1941 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1942 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1944 macro_rules! get_route_and_payment_hash {
1945 ($recv_value: expr) => {{
1946 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1947 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1948 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1949 (route, payment_hash, payment_preimage)
1953 macro_rules! expect_forward {
1955 let mut events = $node.node.get_and_clear_pending_msg_events();
1956 assert_eq!(events.len(), 1);
1957 check_added_monitors!($node, 1);
1958 let payment_event = SendEvent::from_event(events.remove(0));
1963 let feemsat = 239; // somehow we know?
1964 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1965 let feerate = get_feerate!(nodes[0], chan_1.2);
1967 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1969 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1971 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1972 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1973 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1974 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)));
1975 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1976 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);
1979 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1980 // nodes[0]'s wealth
1982 let amt_msat = recv_value_0 + total_fee_msat;
1983 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1984 // Also, ensure that each payment has enough to be over the dust limit to
1985 // ensure it'll be included in each commit tx fee calculation.
1986 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1987 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1988 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1991 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1993 let (stat01_, stat11_, stat12_, stat22_) = (
1994 get_channel_value_stat!(nodes[0], chan_1.2),
1995 get_channel_value_stat!(nodes[1], chan_1.2),
1996 get_channel_value_stat!(nodes[1], chan_2.2),
1997 get_channel_value_stat!(nodes[2], chan_2.2),
2000 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
2001 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
2002 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
2003 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
2004 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2007 // adding pending output.
2008 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2009 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2010 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2011 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2012 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2013 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2014 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2015 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2016 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2018 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2019 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2020 let amt_msat_1 = recv_value_1 + total_fee_msat;
2022 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2023 let payment_event_1 = {
2024 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2025 check_added_monitors!(nodes[0], 1);
2027 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2028 assert_eq!(events.len(), 1);
2029 SendEvent::from_event(events.remove(0))
2031 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2033 // channel reserve test with htlc pending output > 0
2034 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2036 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2037 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2038 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2039 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2042 // split the rest to test holding cell
2043 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2044 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2045 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2046 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2048 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2049 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);
2052 // now see if they go through on both sides
2053 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2054 // but this will stuck in the holding cell
2055 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2056 check_added_monitors!(nodes[0], 0);
2057 let events = nodes[0].node.get_and_clear_pending_events();
2058 assert_eq!(events.len(), 0);
2060 // test with outbound holding cell amount > 0
2062 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2063 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2064 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2065 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2066 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);
2069 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2070 // this will also stuck in the holding cell
2071 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2072 check_added_monitors!(nodes[0], 0);
2073 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2074 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2076 // flush the pending htlc
2077 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2078 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2079 check_added_monitors!(nodes[1], 1);
2081 // the pending htlc should be promoted to committed
2082 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2083 check_added_monitors!(nodes[0], 1);
2084 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2086 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2087 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2088 // No commitment_signed so get_event_msg's assert(len == 1) passes
2089 check_added_monitors!(nodes[0], 1);
2091 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2092 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2093 check_added_monitors!(nodes[1], 1);
2095 expect_pending_htlcs_forwardable!(nodes[1]);
2097 let ref payment_event_11 = expect_forward!(nodes[1]);
2098 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2099 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2101 expect_pending_htlcs_forwardable!(nodes[2]);
2102 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2104 // flush the htlcs in the holding cell
2105 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2106 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2107 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2108 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2109 expect_pending_htlcs_forwardable!(nodes[1]);
2111 let ref payment_event_3 = expect_forward!(nodes[1]);
2112 assert_eq!(payment_event_3.msgs.len(), 2);
2113 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2114 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2116 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2117 expect_pending_htlcs_forwardable!(nodes[2]);
2119 let events = nodes[2].node.get_and_clear_pending_events();
2120 assert_eq!(events.len(), 2);
2122 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2123 assert_eq!(our_payment_hash_21, *payment_hash);
2124 assert_eq!(*payment_secret, None);
2125 assert_eq!(recv_value_21, amt);
2127 _ => panic!("Unexpected event"),
2130 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2131 assert_eq!(our_payment_hash_22, *payment_hash);
2132 assert_eq!(None, *payment_secret);
2133 assert_eq!(recv_value_22, amt);
2135 _ => panic!("Unexpected event"),
2138 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2139 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2140 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2142 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2143 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2144 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2146 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2147 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);
2148 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2149 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2150 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2152 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2153 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2157 fn channel_reserve_in_flight_removes() {
2158 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2159 // can send to its counterparty, but due to update ordering, the other side may not yet have
2160 // considered those HTLCs fully removed.
2161 // This tests that we don't count HTLCs which will not be included in the next remote
2162 // commitment transaction towards the reserve value (as it implies no commitment transaction
2163 // will be generated which violates the remote reserve value).
2164 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2166 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2167 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2168 // you only consider the value of the first HTLC, it may not),
2169 // * start routing a third HTLC from A to B,
2170 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2171 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2172 // * deliver the first fulfill from B
2173 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2175 // * deliver A's response CS and RAA.
2176 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2177 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2178 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2179 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2180 let chanmon_cfgs = create_chanmon_cfgs(2);
2181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2183 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2184 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2185 let logger = test_utils::TestLogger::new();
2187 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2188 // Route the first two HTLCs.
2189 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2190 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2192 // Start routing the third HTLC (this is just used to get everyone in the right state).
2193 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2195 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2196 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();
2197 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2198 check_added_monitors!(nodes[0], 1);
2199 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2200 assert_eq!(events.len(), 1);
2201 SendEvent::from_event(events.remove(0))
2204 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2205 // initial fulfill/CS.
2206 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2207 check_added_monitors!(nodes[1], 1);
2208 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2210 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2211 // remove the second HTLC when we send the HTLC back from B to A.
2212 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2213 check_added_monitors!(nodes[1], 1);
2214 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2216 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2217 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2218 check_added_monitors!(nodes[0], 1);
2219 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2220 expect_payment_sent!(nodes[0], payment_preimage_1);
2222 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2223 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2224 check_added_monitors!(nodes[1], 1);
2225 // B is already AwaitingRAA, so cant generate a CS here
2226 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2228 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2229 check_added_monitors!(nodes[1], 1);
2230 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2232 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2233 check_added_monitors!(nodes[0], 1);
2234 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2236 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2237 check_added_monitors!(nodes[1], 1);
2238 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2240 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2241 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2242 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2243 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2244 // on-chain as necessary).
2245 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2246 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2247 check_added_monitors!(nodes[0], 1);
2248 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2249 expect_payment_sent!(nodes[0], payment_preimage_2);
2251 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2252 check_added_monitors!(nodes[1], 1);
2253 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2255 expect_pending_htlcs_forwardable!(nodes[1]);
2256 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2258 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2259 // resolve the second HTLC from A's point of view.
2260 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2261 check_added_monitors!(nodes[0], 1);
2262 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2264 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2265 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2266 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2268 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2269 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();
2270 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2271 check_added_monitors!(nodes[1], 1);
2272 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2273 assert_eq!(events.len(), 1);
2274 SendEvent::from_event(events.remove(0))
2277 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2278 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2279 check_added_monitors!(nodes[0], 1);
2280 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2282 // Now just resolve all the outstanding messages/HTLCs for completeness...
2284 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2285 check_added_monitors!(nodes[1], 1);
2286 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2289 check_added_monitors!(nodes[1], 1);
2291 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2292 check_added_monitors!(nodes[0], 1);
2293 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2295 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2296 check_added_monitors!(nodes[1], 1);
2297 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2299 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2300 check_added_monitors!(nodes[0], 1);
2302 expect_pending_htlcs_forwardable!(nodes[0]);
2303 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2305 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2306 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2310 fn channel_monitor_network_test() {
2311 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2312 // tests that ChannelMonitor is able to recover from various states.
2313 let chanmon_cfgs = create_chanmon_cfgs(5);
2314 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2315 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2316 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2318 // Create some initial channels
2319 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2320 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2321 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2322 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2324 // Rebalance the network a bit by relaying one payment through all the channels...
2325 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2326 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2327 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2328 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2330 // Simple case with no pending HTLCs:
2331 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2332 check_added_monitors!(nodes[1], 1);
2334 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2335 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2336 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2337 check_added_monitors!(nodes[0], 1);
2338 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2340 get_announce_close_broadcast_events(&nodes, 0, 1);
2341 assert_eq!(nodes[0].node.list_channels().len(), 0);
2342 assert_eq!(nodes[1].node.list_channels().len(), 1);
2344 // One pending HTLC is discarded by the force-close:
2345 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2347 // Simple case of one pending HTLC to HTLC-Timeout
2348 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2349 check_added_monitors!(nodes[1], 1);
2351 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2352 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2353 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2354 check_added_monitors!(nodes[2], 1);
2355 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2357 get_announce_close_broadcast_events(&nodes, 1, 2);
2358 assert_eq!(nodes[1].node.list_channels().len(), 0);
2359 assert_eq!(nodes[2].node.list_channels().len(), 1);
2361 macro_rules! claim_funds {
2362 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2364 assert!($node.node.claim_funds($preimage, &None, $amount));
2365 check_added_monitors!($node, 1);
2367 let events = $node.node.get_and_clear_pending_msg_events();
2368 assert_eq!(events.len(), 1);
2370 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2371 assert!(update_add_htlcs.is_empty());
2372 assert!(update_fail_htlcs.is_empty());
2373 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2375 _ => panic!("Unexpected event"),
2381 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2382 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2383 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2384 check_added_monitors!(nodes[2], 1);
2385 let node2_commitment_txid;
2387 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2388 node2_commitment_txid = node_txn[0].txid();
2390 // Claim the payment on nodes[3], giving it knowledge of the preimage
2391 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2393 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2394 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2395 check_added_monitors!(nodes[3], 1);
2397 check_preimage_claim(&nodes[3], &node_txn);
2399 get_announce_close_broadcast_events(&nodes, 2, 3);
2400 assert_eq!(nodes[2].node.list_channels().len(), 0);
2401 assert_eq!(nodes[3].node.list_channels().len(), 1);
2403 { // Cheat and reset nodes[4]'s height to 1
2404 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2405 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2408 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2409 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2410 // One pending HTLC to time out:
2411 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2412 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2415 let (close_chan_update_1, close_chan_update_2) = {
2416 let mut block = Block {
2417 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2420 connect_block(&nodes[3], &block, 2);
2421 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2423 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2426 connect_block(&nodes[3], &block, i);
2428 let events = nodes[3].node.get_and_clear_pending_msg_events();
2429 assert_eq!(events.len(), 1);
2430 let close_chan_update_1 = match events[0] {
2431 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2434 _ => panic!("Unexpected event"),
2436 check_added_monitors!(nodes[3], 1);
2438 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2440 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2441 node_txn.retain(|tx| {
2442 if tx.input[0].previous_output.txid == node2_commitment_txid {
2448 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2450 // Claim the payment on nodes[4], giving it knowledge of the preimage
2451 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2454 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2458 connect_block(&nodes[4], &block, 2);
2459 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2461 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2464 connect_block(&nodes[4], &block, i);
2466 let events = nodes[4].node.get_and_clear_pending_msg_events();
2467 assert_eq!(events.len(), 1);
2468 let close_chan_update_2 = match events[0] {
2469 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2472 _ => panic!("Unexpected event"),
2474 check_added_monitors!(nodes[4], 1);
2475 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2478 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2479 txdata: vec![node_txn[0].clone()],
2481 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2483 check_preimage_claim(&nodes[4], &node_txn);
2484 (close_chan_update_1, close_chan_update_2)
2486 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2487 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2488 assert_eq!(nodes[3].node.list_channels().len(), 0);
2489 assert_eq!(nodes[4].node.list_channels().len(), 0);
2493 fn test_justice_tx() {
2494 // Test justice txn built on revoked HTLC-Success tx, against both sides
2495 let mut alice_config = UserConfig::default();
2496 alice_config.channel_options.announced_channel = true;
2497 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2498 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2499 let mut bob_config = UserConfig::default();
2500 bob_config.channel_options.announced_channel = true;
2501 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2502 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2503 let user_cfgs = [Some(alice_config), Some(bob_config)];
2504 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2505 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2506 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2507 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2508 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2509 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2510 // Create some new channels:
2511 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2513 // A pending HTLC which will be revoked:
2514 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2515 // Get the will-be-revoked local txn from nodes[0]
2516 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2517 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2518 assert_eq!(revoked_local_txn[0].input.len(), 1);
2519 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2520 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2521 assert_eq!(revoked_local_txn[1].input.len(), 1);
2522 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2523 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2524 // Revoke the old state
2525 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2528 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2529 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2531 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2532 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2533 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2535 check_spends!(node_txn[0], revoked_local_txn[0]);
2536 node_txn.swap_remove(0);
2537 node_txn.truncate(1);
2539 check_added_monitors!(nodes[1], 1);
2540 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2542 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2543 // Verify broadcast of revoked HTLC-timeout
2544 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2545 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2546 check_added_monitors!(nodes[0], 1);
2547 // Broadcast revoked HTLC-timeout on node 1
2548 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2549 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2551 get_announce_close_broadcast_events(&nodes, 0, 1);
2553 assert_eq!(nodes[0].node.list_channels().len(), 0);
2554 assert_eq!(nodes[1].node.list_channels().len(), 0);
2556 // We test justice_tx build by A on B's revoked HTLC-Success tx
2557 // Create some new channels:
2558 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2560 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2564 // A pending HTLC which will be revoked:
2565 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2566 // Get the will-be-revoked local txn from B
2567 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2568 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2569 assert_eq!(revoked_local_txn[0].input.len(), 1);
2570 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2571 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2572 // Revoke the old state
2573 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2575 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2576 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2578 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2579 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2580 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2582 check_spends!(node_txn[0], revoked_local_txn[0]);
2583 node_txn.swap_remove(0);
2585 check_added_monitors!(nodes[0], 1);
2586 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2588 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2589 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2590 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2591 check_added_monitors!(nodes[1], 1);
2592 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2593 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2595 get_announce_close_broadcast_events(&nodes, 0, 1);
2596 assert_eq!(nodes[0].node.list_channels().len(), 0);
2597 assert_eq!(nodes[1].node.list_channels().len(), 0);
2601 fn revoked_output_claim() {
2602 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2603 // transaction is broadcast by its counterparty
2604 let chanmon_cfgs = create_chanmon_cfgs(2);
2605 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2606 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2607 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2609 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2610 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2611 assert_eq!(revoked_local_txn.len(), 1);
2612 // Only output is the full channel value back to nodes[0]:
2613 assert_eq!(revoked_local_txn[0].output.len(), 1);
2614 // Send a payment through, updating everyone's latest commitment txn
2615 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2617 // Inform nodes[1] that nodes[0] broadcast a stale tx
2618 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2619 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2620 check_added_monitors!(nodes[1], 1);
2621 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2622 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2624 check_spends!(node_txn[0], revoked_local_txn[0]);
2625 check_spends!(node_txn[1], chan_1.3);
2627 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2628 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2629 get_announce_close_broadcast_events(&nodes, 0, 1);
2630 check_added_monitors!(nodes[0], 1)
2634 fn claim_htlc_outputs_shared_tx() {
2635 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2636 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2637 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2638 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2639 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2640 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2642 // Create some new channel:
2643 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2645 // Rebalance the network to generate htlc in the two directions
2646 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2647 // 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
2648 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2649 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2651 // Get the will-be-revoked local txn from node[0]
2652 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2653 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2654 assert_eq!(revoked_local_txn[0].input.len(), 1);
2655 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2656 assert_eq!(revoked_local_txn[1].input.len(), 1);
2657 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2658 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2659 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2661 //Revoke the old state
2662 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2665 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2666 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2667 check_added_monitors!(nodes[0], 1);
2668 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2669 check_added_monitors!(nodes[1], 1);
2670 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2671 expect_payment_failed!(nodes[1], payment_hash_2, true);
2673 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2674 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2676 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2677 check_spends!(node_txn[0], revoked_local_txn[0]);
2679 let mut witness_lens = BTreeSet::new();
2680 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2681 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2682 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2683 assert_eq!(witness_lens.len(), 3);
2684 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2685 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2686 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2688 // Next nodes[1] broadcasts its current local tx state:
2689 assert_eq!(node_txn[1].input.len(), 1);
2690 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2692 assert_eq!(node_txn[2].input.len(), 1);
2693 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2694 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2695 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2696 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2697 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2699 get_announce_close_broadcast_events(&nodes, 0, 1);
2700 assert_eq!(nodes[0].node.list_channels().len(), 0);
2701 assert_eq!(nodes[1].node.list_channels().len(), 0);
2705 fn claim_htlc_outputs_single_tx() {
2706 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2707 let mut chanmon_cfgs = create_chanmon_cfgs(2);
2708 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2711 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2713 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2715 // Rebalance the network to generate htlc in the two directions
2716 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2717 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2718 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2719 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2720 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2722 // Get the will-be-revoked local txn from node[0]
2723 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2725 //Revoke the old state
2726 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2729 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2730 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2731 check_added_monitors!(nodes[0], 1);
2732 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2733 check_added_monitors!(nodes[1], 1);
2734 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2736 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2737 expect_payment_failed!(nodes[1], payment_hash_2, true);
2739 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2740 assert_eq!(node_txn.len(), 9);
2741 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2742 // ChannelManager: local commmitment + local HTLC-timeout (2)
2743 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2744 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2746 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2747 assert_eq!(node_txn[2].input.len(), 1);
2748 check_spends!(node_txn[2], chan_1.3);
2749 assert_eq!(node_txn[3].input.len(), 1);
2750 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2751 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2752 check_spends!(node_txn[3], node_txn[2]);
2754 // Justice transactions are indices 1-2-4
2755 assert_eq!(node_txn[0].input.len(), 1);
2756 assert_eq!(node_txn[1].input.len(), 1);
2757 assert_eq!(node_txn[4].input.len(), 1);
2759 check_spends!(node_txn[0], revoked_local_txn[0]);
2760 check_spends!(node_txn[1], revoked_local_txn[0]);
2761 check_spends!(node_txn[4], revoked_local_txn[0]);
2763 let mut witness_lens = BTreeSet::new();
2764 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2765 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2766 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2767 assert_eq!(witness_lens.len(), 3);
2768 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2769 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2770 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2772 get_announce_close_broadcast_events(&nodes, 0, 1);
2773 assert_eq!(nodes[0].node.list_channels().len(), 0);
2774 assert_eq!(nodes[1].node.list_channels().len(), 0);
2778 fn test_htlc_on_chain_success() {
2779 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2780 // the preimage backward accordingly. So here we test that ChannelManager is
2781 // broadcasting the right event to other nodes in payment path.
2782 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2783 // A --------------------> B ----------------------> C (preimage)
2784 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2785 // commitment transaction was broadcast.
2786 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2788 // B should be able to claim via preimage if A then broadcasts its local tx.
2789 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2790 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2791 // PaymentSent event).
2793 let chanmon_cfgs = create_chanmon_cfgs(3);
2794 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2795 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2796 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2798 // Create some initial channels
2799 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2800 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2802 // Rebalance the network a bit by relaying one payment through all the channels...
2803 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2804 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2806 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2807 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2808 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2810 // Broadcast legit commitment tx from C on B's chain
2811 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2812 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2813 assert_eq!(commitment_tx.len(), 1);
2814 check_spends!(commitment_tx[0], chan_2.3);
2815 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2816 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2817 check_added_monitors!(nodes[2], 2);
2818 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2819 assert!(updates.update_add_htlcs.is_empty());
2820 assert!(updates.update_fail_htlcs.is_empty());
2821 assert!(updates.update_fail_malformed_htlcs.is_empty());
2822 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2824 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2825 check_closed_broadcast!(nodes[2], false);
2826 check_added_monitors!(nodes[2], 1);
2827 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2828 assert_eq!(node_txn.len(), 5);
2829 assert_eq!(node_txn[0], node_txn[3]);
2830 assert_eq!(node_txn[1], node_txn[4]);
2831 assert_eq!(node_txn[2], commitment_tx[0]);
2832 check_spends!(node_txn[0], commitment_tx[0]);
2833 check_spends!(node_txn[1], commitment_tx[0]);
2834 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2835 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2836 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2837 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2838 assert_eq!(node_txn[0].lock_time, 0);
2839 assert_eq!(node_txn[1].lock_time, 0);
2841 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2842 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2844 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2845 assert_eq!(added_monitors.len(), 1);
2846 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2847 added_monitors.clear();
2849 let events = nodes[1].node.get_and_clear_pending_msg_events();
2851 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2852 assert_eq!(added_monitors.len(), 2);
2853 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2854 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2855 added_monitors.clear();
2857 assert_eq!(events.len(), 2);
2859 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2860 _ => panic!("Unexpected event"),
2863 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2864 assert!(update_add_htlcs.is_empty());
2865 assert!(update_fail_htlcs.is_empty());
2866 assert_eq!(update_fulfill_htlcs.len(), 1);
2867 assert!(update_fail_malformed_htlcs.is_empty());
2868 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2870 _ => panic!("Unexpected event"),
2872 macro_rules! check_tx_local_broadcast {
2873 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2874 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2875 assert_eq!(node_txn.len(), 5);
2876 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2877 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2878 check_spends!(node_txn[0], $commitment_tx);
2879 check_spends!(node_txn[1], $commitment_tx);
2880 assert_ne!(node_txn[0].lock_time, 0);
2881 assert_ne!(node_txn[1].lock_time, 0);
2883 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2884 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2885 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2886 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2889 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2890 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2891 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2893 check_spends!(node_txn[2], $chan_tx);
2894 check_spends!(node_txn[3], node_txn[2]);
2895 check_spends!(node_txn[4], node_txn[2]);
2896 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2897 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2898 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2899 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2900 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2901 assert_ne!(node_txn[3].lock_time, 0);
2902 assert_ne!(node_txn[4].lock_time, 0);
2906 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2907 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2908 // timeout-claim of the output that nodes[2] just claimed via success.
2909 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2911 // Broadcast legit commitment tx from A on B's chain
2912 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2913 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2914 check_spends!(commitment_tx[0], chan_1.3);
2915 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2916 check_closed_broadcast!(nodes[1], false);
2917 check_added_monitors!(nodes[1], 1);
2918 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2919 assert_eq!(node_txn.len(), 4);
2920 check_spends!(node_txn[0], commitment_tx[0]);
2921 assert_eq!(node_txn[0].input.len(), 2);
2922 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2923 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2924 assert_eq!(node_txn[0].lock_time, 0);
2925 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2926 check_spends!(node_txn[1], chan_1.3);
2927 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2928 check_spends!(node_txn[2], node_txn[1]);
2929 check_spends!(node_txn[3], node_txn[1]);
2930 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2931 // we already checked the same situation with A.
2933 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2934 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2935 check_closed_broadcast!(nodes[0], false);
2936 check_added_monitors!(nodes[0], 1);
2937 let events = nodes[0].node.get_and_clear_pending_events();
2938 assert_eq!(events.len(), 2);
2939 let mut first_claimed = false;
2940 for event in events {
2942 Event::PaymentSent { payment_preimage } => {
2943 if payment_preimage == our_payment_preimage {
2944 assert!(!first_claimed);
2945 first_claimed = true;
2947 assert_eq!(payment_preimage, our_payment_preimage_2);
2950 _ => panic!("Unexpected event"),
2953 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2957 fn test_htlc_on_chain_timeout() {
2958 // Test that in case of a unilateral close onchain, we detect the state of output and
2959 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2960 // broadcasting the right event to other nodes in payment path.
2961 // A ------------------> B ----------------------> C (timeout)
2962 // B's commitment tx C's commitment tx
2964 // B's HTLC timeout tx B's timeout tx
2966 let chanmon_cfgs = create_chanmon_cfgs(3);
2967 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2968 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2969 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2971 // Create some intial channels
2972 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2973 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2975 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2976 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2977 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2979 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2980 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2982 // Broadcast legit commitment tx from C on B's chain
2983 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2984 check_spends!(commitment_tx[0], chan_2.3);
2985 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2986 check_added_monitors!(nodes[2], 0);
2987 expect_pending_htlcs_forwardable!(nodes[2]);
2988 check_added_monitors!(nodes[2], 1);
2990 let events = nodes[2].node.get_and_clear_pending_msg_events();
2991 assert_eq!(events.len(), 1);
2993 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, .. } } => {
2994 assert!(update_add_htlcs.is_empty());
2995 assert!(!update_fail_htlcs.is_empty());
2996 assert!(update_fulfill_htlcs.is_empty());
2997 assert!(update_fail_malformed_htlcs.is_empty());
2998 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3000 _ => panic!("Unexpected event"),
3002 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3003 check_closed_broadcast!(nodes[2], false);
3004 check_added_monitors!(nodes[2], 1);
3005 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3006 assert_eq!(node_txn.len(), 1);
3007 check_spends!(node_txn[0], chan_2.3);
3008 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3010 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3011 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3012 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3015 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3016 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3017 assert_eq!(node_txn[1], node_txn[3]);
3018 assert_eq!(node_txn[2], node_txn[4]);
3020 check_spends!(node_txn[0], commitment_tx[0]);
3021 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3023 check_spends!(node_txn[1], chan_2.3);
3024 check_spends!(node_txn[2], node_txn[1]);
3025 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3026 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3028 timeout_tx = node_txn[0].clone();
3032 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3033 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3034 check_added_monitors!(nodes[1], 1);
3035 check_closed_broadcast!(nodes[1], false);
3037 expect_pending_htlcs_forwardable!(nodes[1]);
3038 check_added_monitors!(nodes[1], 1);
3039 let events = nodes[1].node.get_and_clear_pending_msg_events();
3040 assert_eq!(events.len(), 1);
3042 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, .. } } => {
3043 assert!(update_add_htlcs.is_empty());
3044 assert!(!update_fail_htlcs.is_empty());
3045 assert!(update_fulfill_htlcs.is_empty());
3046 assert!(update_fail_malformed_htlcs.is_empty());
3047 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3049 _ => panic!("Unexpected event"),
3051 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
3052 assert_eq!(node_txn.len(), 0);
3054 // Broadcast legit commitment tx from B on A's chain
3055 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3056 check_spends!(commitment_tx[0], chan_1.3);
3058 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3059 check_closed_broadcast!(nodes[0], false);
3060 check_added_monitors!(nodes[0], 1);
3061 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3062 assert_eq!(node_txn.len(), 3);
3063 check_spends!(node_txn[0], commitment_tx[0]);
3064 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3065 check_spends!(node_txn[1], chan_1.3);
3066 check_spends!(node_txn[2], node_txn[1]);
3067 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3068 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3072 fn test_simple_commitment_revoked_fail_backward() {
3073 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3074 // and fail backward accordingly.
3076 let chanmon_cfgs = create_chanmon_cfgs(3);
3077 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3078 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3079 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3081 // Create some initial channels
3082 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3083 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3085 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3086 // Get the will-be-revoked local txn from nodes[2]
3087 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3088 // Revoke the old state
3089 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3091 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3093 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3094 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3095 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3096 check_added_monitors!(nodes[1], 1);
3097 check_closed_broadcast!(nodes[1], false);
3099 expect_pending_htlcs_forwardable!(nodes[1]);
3100 check_added_monitors!(nodes[1], 1);
3101 let events = nodes[1].node.get_and_clear_pending_msg_events();
3102 assert_eq!(events.len(), 1);
3104 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, .. } } => {
3105 assert!(update_add_htlcs.is_empty());
3106 assert_eq!(update_fail_htlcs.len(), 1);
3107 assert!(update_fulfill_htlcs.is_empty());
3108 assert!(update_fail_malformed_htlcs.is_empty());
3109 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3111 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3112 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3114 let events = nodes[0].node.get_and_clear_pending_msg_events();
3115 assert_eq!(events.len(), 1);
3117 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3118 _ => panic!("Unexpected event"),
3120 expect_payment_failed!(nodes[0], payment_hash, false);
3122 _ => panic!("Unexpected event"),
3126 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3127 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3128 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3129 // commitment transaction anymore.
3130 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3131 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3132 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3133 // technically disallowed and we should probably handle it reasonably.
3134 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3135 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3137 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3138 // commitment_signed (implying it will be in the latest remote commitment transaction).
3139 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3140 // and once they revoke the previous commitment transaction (allowing us to send a new
3141 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3142 let chanmon_cfgs = create_chanmon_cfgs(3);
3143 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3144 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3145 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3147 // Create some initial channels
3148 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3149 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3151 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3152 // Get the will-be-revoked local txn from nodes[2]
3153 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3154 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3155 // Revoke the old state
3156 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3158 let value = if use_dust {
3159 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3160 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3161 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3164 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3165 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3166 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3168 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3169 expect_pending_htlcs_forwardable!(nodes[2]);
3170 check_added_monitors!(nodes[2], 1);
3171 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3172 assert!(updates.update_add_htlcs.is_empty());
3173 assert!(updates.update_fulfill_htlcs.is_empty());
3174 assert!(updates.update_fail_malformed_htlcs.is_empty());
3175 assert_eq!(updates.update_fail_htlcs.len(), 1);
3176 assert!(updates.update_fee.is_none());
3177 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3178 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3179 // Drop the last RAA from 3 -> 2
3181 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3182 expect_pending_htlcs_forwardable!(nodes[2]);
3183 check_added_monitors!(nodes[2], 1);
3184 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3185 assert!(updates.update_add_htlcs.is_empty());
3186 assert!(updates.update_fulfill_htlcs.is_empty());
3187 assert!(updates.update_fail_malformed_htlcs.is_empty());
3188 assert_eq!(updates.update_fail_htlcs.len(), 1);
3189 assert!(updates.update_fee.is_none());
3190 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3191 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3192 check_added_monitors!(nodes[1], 1);
3193 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3194 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3195 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3196 check_added_monitors!(nodes[2], 1);
3198 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3199 expect_pending_htlcs_forwardable!(nodes[2]);
3200 check_added_monitors!(nodes[2], 1);
3201 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3202 assert!(updates.update_add_htlcs.is_empty());
3203 assert!(updates.update_fulfill_htlcs.is_empty());
3204 assert!(updates.update_fail_malformed_htlcs.is_empty());
3205 assert_eq!(updates.update_fail_htlcs.len(), 1);
3206 assert!(updates.update_fee.is_none());
3207 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3208 // At this point first_payment_hash has dropped out of the latest two commitment
3209 // transactions that nodes[1] is tracking...
3210 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3211 check_added_monitors!(nodes[1], 1);
3212 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3213 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3214 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3215 check_added_monitors!(nodes[2], 1);
3217 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3218 // on nodes[2]'s RAA.
3219 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3220 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3221 let logger = test_utils::TestLogger::new();
3222 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();
3223 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3224 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3225 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3226 check_added_monitors!(nodes[1], 0);
3229 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3230 // One monitor for the new revocation preimage, no second on as we won't generate a new
3231 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3232 check_added_monitors!(nodes[1], 1);
3233 let events = nodes[1].node.get_and_clear_pending_events();
3234 assert_eq!(events.len(), 1);
3236 Event::PendingHTLCsForwardable { .. } => { },
3237 _ => panic!("Unexpected event"),
3239 // Deliberately don't process the pending fail-back so they all fail back at once after
3240 // block connection just like the !deliver_bs_raa case
3243 let mut failed_htlcs = HashSet::new();
3244 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3246 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3247 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3248 check_added_monitors!(nodes[1], 1);
3249 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3251 let events = nodes[1].node.get_and_clear_pending_events();
3252 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3254 Event::PaymentFailed { ref payment_hash, .. } => {
3255 assert_eq!(*payment_hash, fourth_payment_hash);
3257 _ => panic!("Unexpected event"),
3259 if !deliver_bs_raa {
3261 Event::PendingHTLCsForwardable { .. } => { },
3262 _ => panic!("Unexpected event"),
3265 nodes[1].node.process_pending_htlc_forwards();
3266 check_added_monitors!(nodes[1], 1);
3268 let events = nodes[1].node.get_and_clear_pending_msg_events();
3269 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3270 match events[if deliver_bs_raa { 1 } else { 0 }] {
3271 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3272 _ => panic!("Unexpected event"),
3276 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, .. } } => {
3277 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3278 assert_eq!(update_add_htlcs.len(), 1);
3279 assert!(update_fulfill_htlcs.is_empty());
3280 assert!(update_fail_htlcs.is_empty());
3281 assert!(update_fail_malformed_htlcs.is_empty());
3283 _ => panic!("Unexpected event"),
3286 match events[if deliver_bs_raa { 2 } else { 1 }] {
3287 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, .. } } => {
3288 assert!(update_add_htlcs.is_empty());
3289 assert_eq!(update_fail_htlcs.len(), 3);
3290 assert!(update_fulfill_htlcs.is_empty());
3291 assert!(update_fail_malformed_htlcs.is_empty());
3292 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3294 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3295 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3296 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3298 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3300 let events = nodes[0].node.get_and_clear_pending_msg_events();
3301 // If we delivered B's RAA we got an unknown preimage error, not something
3302 // that we should update our routing table for.
3303 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3304 for event in events {
3306 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3307 _ => panic!("Unexpected event"),
3310 let events = nodes[0].node.get_and_clear_pending_events();
3311 assert_eq!(events.len(), 3);
3313 Event::PaymentFailed { ref payment_hash, .. } => {
3314 assert!(failed_htlcs.insert(payment_hash.0));
3316 _ => panic!("Unexpected event"),
3319 Event::PaymentFailed { ref payment_hash, .. } => {
3320 assert!(failed_htlcs.insert(payment_hash.0));
3322 _ => panic!("Unexpected event"),
3325 Event::PaymentFailed { ref payment_hash, .. } => {
3326 assert!(failed_htlcs.insert(payment_hash.0));
3328 _ => panic!("Unexpected event"),
3331 _ => panic!("Unexpected event"),
3334 assert!(failed_htlcs.contains(&first_payment_hash.0));
3335 assert!(failed_htlcs.contains(&second_payment_hash.0));
3336 assert!(failed_htlcs.contains(&third_payment_hash.0));
3340 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3341 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3342 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3343 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3344 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3348 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3349 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3350 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3351 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3352 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3356 fn fail_backward_pending_htlc_upon_channel_failure() {
3357 let chanmon_cfgs = create_chanmon_cfgs(2);
3358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3360 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3361 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3362 let logger = test_utils::TestLogger::new();
3364 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3366 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3367 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3368 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();
3369 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3370 check_added_monitors!(nodes[0], 1);
3372 let payment_event = {
3373 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3374 assert_eq!(events.len(), 1);
3375 SendEvent::from_event(events.remove(0))
3377 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3378 assert_eq!(payment_event.msgs.len(), 1);
3381 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3382 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3384 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3385 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();
3386 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3387 check_added_monitors!(nodes[0], 0);
3389 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3392 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3394 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3396 let secp_ctx = Secp256k1::new();
3397 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3398 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3399 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3400 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();
3401 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3402 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3403 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3405 // Send a 0-msat update_add_htlc to fail the channel.
3406 let update_add_htlc = msgs::UpdateAddHTLC {
3412 onion_routing_packet,
3414 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3417 // Check that Alice fails backward the pending HTLC from the second payment.
3418 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3419 check_closed_broadcast!(nodes[0], true);
3420 check_added_monitors!(nodes[0], 1);
3424 fn test_htlc_ignore_latest_remote_commitment() {
3425 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3426 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3427 let chanmon_cfgs = create_chanmon_cfgs(2);
3428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3431 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3433 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3434 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id).unwrap();
3435 check_closed_broadcast!(nodes[0], false);
3436 check_added_monitors!(nodes[0], 1);
3438 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3439 assert_eq!(node_txn.len(), 2);
3441 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3442 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3443 check_closed_broadcast!(nodes[1], false);
3444 check_added_monitors!(nodes[1], 1);
3446 // Duplicate the connect_block call since this may happen due to other listeners
3447 // registering new transactions
3448 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3452 fn test_force_close_fail_back() {
3453 // Check which HTLCs are failed-backwards on channel force-closure
3454 let chanmon_cfgs = create_chanmon_cfgs(3);
3455 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3456 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3457 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3458 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3459 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3460 let logger = test_utils::TestLogger::new();
3462 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3464 let mut payment_event = {
3465 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3466 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();
3467 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3468 check_added_monitors!(nodes[0], 1);
3470 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3471 assert_eq!(events.len(), 1);
3472 SendEvent::from_event(events.remove(0))
3475 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3476 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3478 expect_pending_htlcs_forwardable!(nodes[1]);
3480 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3481 assert_eq!(events_2.len(), 1);
3482 payment_event = SendEvent::from_event(events_2.remove(0));
3483 assert_eq!(payment_event.msgs.len(), 1);
3485 check_added_monitors!(nodes[1], 1);
3486 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3487 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3488 check_added_monitors!(nodes[2], 1);
3489 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3491 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3492 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3493 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3495 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id).unwrap();
3496 check_closed_broadcast!(nodes[2], false);
3497 check_added_monitors!(nodes[2], 1);
3499 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3500 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3501 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3502 // back to nodes[1] upon timeout otherwise.
3503 assert_eq!(node_txn.len(), 1);
3508 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3509 txdata: vec![tx.clone()],
3511 connect_block(&nodes[1], &block, 1);
3513 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3514 check_closed_broadcast!(nodes[1], false);
3515 check_added_monitors!(nodes[1], 1);
3517 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3519 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3520 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3521 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3523 connect_block(&nodes[2], &block, 1);
3524 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3525 assert_eq!(node_txn.len(), 1);
3526 assert_eq!(node_txn[0].input.len(), 1);
3527 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3528 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3529 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3531 check_spends!(node_txn[0], tx);
3535 fn test_unconf_chan() {
3536 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3537 let chanmon_cfgs = create_chanmon_cfgs(2);
3538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3540 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3541 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3543 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3544 assert_eq!(channel_state.by_id.len(), 1);
3545 assert_eq!(channel_state.short_to_id.len(), 1);
3546 mem::drop(channel_state);
3548 let mut headers = Vec::new();
3549 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3550 headers.push(header.clone());
3552 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3553 headers.push(header.clone());
3555 while !headers.is_empty() {
3556 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3558 check_closed_broadcast!(nodes[0], false);
3559 check_added_monitors!(nodes[0], 1);
3560 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3561 assert_eq!(channel_state.by_id.len(), 0);
3562 assert_eq!(channel_state.short_to_id.len(), 0);
3566 fn test_simple_peer_disconnect() {
3567 // Test that we can reconnect when there are no lost messages
3568 let chanmon_cfgs = create_chanmon_cfgs(3);
3569 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3570 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3571 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3572 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3573 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3575 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3576 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3577 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3579 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3580 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3581 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3582 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3584 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3585 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3586 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3588 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3589 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3590 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3591 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3593 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3594 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3596 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3597 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3599 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3601 let events = nodes[0].node.get_and_clear_pending_events();
3602 assert_eq!(events.len(), 2);
3604 Event::PaymentSent { payment_preimage } => {
3605 assert_eq!(payment_preimage, payment_preimage_3);
3607 _ => panic!("Unexpected event"),
3610 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3611 assert_eq!(payment_hash, payment_hash_5);
3612 assert!(rejected_by_dest);
3614 _ => panic!("Unexpected event"),
3618 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3619 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3622 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3623 // Test that we can reconnect when in-flight HTLC updates get dropped
3624 let chanmon_cfgs = create_chanmon_cfgs(2);
3625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3627 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3628 if messages_delivered == 0 {
3629 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3630 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3632 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3635 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3637 let logger = test_utils::TestLogger::new();
3638 let payment_event = {
3639 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3640 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3641 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3642 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3643 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3644 check_added_monitors!(nodes[0], 1);
3646 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3647 assert_eq!(events.len(), 1);
3648 SendEvent::from_event(events.remove(0))
3650 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3652 if messages_delivered < 2 {
3653 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3655 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3656 if messages_delivered >= 3 {
3657 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3658 check_added_monitors!(nodes[1], 1);
3659 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3661 if messages_delivered >= 4 {
3662 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3663 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3664 check_added_monitors!(nodes[0], 1);
3666 if messages_delivered >= 5 {
3667 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3668 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3669 // No commitment_signed so get_event_msg's assert(len == 1) passes
3670 check_added_monitors!(nodes[0], 1);
3672 if messages_delivered >= 6 {
3673 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3674 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3675 check_added_monitors!(nodes[1], 1);
3682 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3683 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3684 if messages_delivered < 3 {
3685 // Even if the funding_locked messages get exchanged, as long as nothing further was
3686 // received on either side, both sides will need to resend them.
3687 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3688 } else if messages_delivered == 3 {
3689 // nodes[0] still wants its RAA + commitment_signed
3690 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3691 } else if messages_delivered == 4 {
3692 // nodes[0] still wants its commitment_signed
3693 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3694 } else if messages_delivered == 5 {
3695 // nodes[1] still wants its final RAA
3696 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3697 } else if messages_delivered == 6 {
3698 // Everything was delivered...
3699 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3702 let events_1 = nodes[1].node.get_and_clear_pending_events();
3703 assert_eq!(events_1.len(), 1);
3705 Event::PendingHTLCsForwardable { .. } => { },
3706 _ => panic!("Unexpected event"),
3709 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3710 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3711 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3713 nodes[1].node.process_pending_htlc_forwards();
3715 let events_2 = nodes[1].node.get_and_clear_pending_events();
3716 assert_eq!(events_2.len(), 1);
3718 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3719 assert_eq!(payment_hash_1, *payment_hash);
3720 assert_eq!(*payment_secret, None);
3721 assert_eq!(amt, 1000000);
3723 _ => panic!("Unexpected event"),
3726 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3727 check_added_monitors!(nodes[1], 1);
3729 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3730 assert_eq!(events_3.len(), 1);
3731 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3732 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3733 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3734 assert!(updates.update_add_htlcs.is_empty());
3735 assert!(updates.update_fail_htlcs.is_empty());
3736 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3737 assert!(updates.update_fail_malformed_htlcs.is_empty());
3738 assert!(updates.update_fee.is_none());
3739 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3741 _ => panic!("Unexpected event"),
3744 if messages_delivered >= 1 {
3745 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3747 let events_4 = nodes[0].node.get_and_clear_pending_events();
3748 assert_eq!(events_4.len(), 1);
3750 Event::PaymentSent { ref payment_preimage } => {
3751 assert_eq!(payment_preimage_1, *payment_preimage);
3753 _ => panic!("Unexpected event"),
3756 if messages_delivered >= 2 {
3757 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3758 check_added_monitors!(nodes[0], 1);
3759 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3761 if messages_delivered >= 3 {
3762 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3763 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3764 check_added_monitors!(nodes[1], 1);
3766 if messages_delivered >= 4 {
3767 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3768 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3769 // No commitment_signed so get_event_msg's assert(len == 1) passes
3770 check_added_monitors!(nodes[1], 1);
3772 if messages_delivered >= 5 {
3773 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3774 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3775 check_added_monitors!(nodes[0], 1);
3782 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3783 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3784 if messages_delivered < 2 {
3785 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3786 //TODO: Deduplicate PaymentSent events, then enable this if:
3787 //if messages_delivered < 1 {
3788 let events_4 = nodes[0].node.get_and_clear_pending_events();
3789 assert_eq!(events_4.len(), 1);
3791 Event::PaymentSent { ref payment_preimage } => {
3792 assert_eq!(payment_preimage_1, *payment_preimage);
3794 _ => panic!("Unexpected event"),
3797 } else if messages_delivered == 2 {
3798 // nodes[0] still wants its RAA + commitment_signed
3799 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3800 } else if messages_delivered == 3 {
3801 // nodes[0] still wants its commitment_signed
3802 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3803 } else if messages_delivered == 4 {
3804 // nodes[1] still wants its final RAA
3805 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3806 } else if messages_delivered == 5 {
3807 // Everything was delivered...
3808 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3811 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3812 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3815 // Channel should still work fine...
3816 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3817 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3818 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3819 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3820 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3821 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3825 fn test_drop_messages_peer_disconnect_a() {
3826 do_test_drop_messages_peer_disconnect(0);
3827 do_test_drop_messages_peer_disconnect(1);
3828 do_test_drop_messages_peer_disconnect(2);
3829 do_test_drop_messages_peer_disconnect(3);
3833 fn test_drop_messages_peer_disconnect_b() {
3834 do_test_drop_messages_peer_disconnect(4);
3835 do_test_drop_messages_peer_disconnect(5);
3836 do_test_drop_messages_peer_disconnect(6);
3840 fn test_funding_peer_disconnect() {
3841 // Test that we can lock in our funding tx while disconnected
3842 let chanmon_cfgs = create_chanmon_cfgs(2);
3843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3846 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3848 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3849 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3851 confirm_transaction(&nodes[0], &tx);
3852 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3853 assert_eq!(events_1.len(), 1);
3855 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3856 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3858 _ => panic!("Unexpected event"),
3861 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3863 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3864 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3866 confirm_transaction(&nodes[1], &tx);
3867 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3868 assert_eq!(events_2.len(), 2);
3869 let funding_locked = match events_2[0] {
3870 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3871 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3874 _ => panic!("Unexpected event"),
3876 let bs_announcement_sigs = match events_2[1] {
3877 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3878 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3881 _ => panic!("Unexpected event"),
3884 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3886 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3887 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3888 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3889 assert_eq!(events_3.len(), 2);
3890 let as_announcement_sigs = match events_3[0] {
3891 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3892 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3895 _ => panic!("Unexpected event"),
3897 let (as_announcement, as_update) = match events_3[1] {
3898 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3899 (msg.clone(), update_msg.clone())
3901 _ => panic!("Unexpected event"),
3904 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3905 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3906 assert_eq!(events_4.len(), 1);
3907 let (_, bs_update) = match events_4[0] {
3908 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3909 (msg.clone(), update_msg.clone())
3911 _ => panic!("Unexpected event"),
3914 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3915 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3916 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3918 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3919 let logger = test_utils::TestLogger::new();
3920 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3921 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3922 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3926 fn test_drop_messages_peer_disconnect_dual_htlc() {
3927 // Test that we can handle reconnecting when both sides of a channel have pending
3928 // commitment_updates when we disconnect.
3929 let chanmon_cfgs = create_chanmon_cfgs(2);
3930 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3931 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3932 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3933 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3934 let logger = test_utils::TestLogger::new();
3936 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3938 // Now try to send a second payment which will fail to send
3939 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3940 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3941 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();
3942 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3943 check_added_monitors!(nodes[0], 1);
3945 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3946 assert_eq!(events_1.len(), 1);
3948 MessageSendEvent::UpdateHTLCs { .. } => {},
3949 _ => panic!("Unexpected event"),
3952 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3953 check_added_monitors!(nodes[1], 1);
3955 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3956 assert_eq!(events_2.len(), 1);
3958 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 } } => {
3959 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3960 assert!(update_add_htlcs.is_empty());
3961 assert_eq!(update_fulfill_htlcs.len(), 1);
3962 assert!(update_fail_htlcs.is_empty());
3963 assert!(update_fail_malformed_htlcs.is_empty());
3964 assert!(update_fee.is_none());
3966 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3967 let events_3 = nodes[0].node.get_and_clear_pending_events();
3968 assert_eq!(events_3.len(), 1);
3970 Event::PaymentSent { ref payment_preimage } => {
3971 assert_eq!(*payment_preimage, payment_preimage_1);
3973 _ => panic!("Unexpected event"),
3976 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3977 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3978 // No commitment_signed so get_event_msg's assert(len == 1) passes
3979 check_added_monitors!(nodes[0], 1);
3981 _ => panic!("Unexpected event"),
3984 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3985 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3987 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3988 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3989 assert_eq!(reestablish_1.len(), 1);
3990 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3991 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3992 assert_eq!(reestablish_2.len(), 1);
3994 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3995 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3996 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3997 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3999 assert!(as_resp.0.is_none());
4000 assert!(bs_resp.0.is_none());
4002 assert!(bs_resp.1.is_none());
4003 assert!(bs_resp.2.is_none());
4005 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4007 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4008 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4009 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4010 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4011 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4012 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4013 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4014 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4015 // No commitment_signed so get_event_msg's assert(len == 1) passes
4016 check_added_monitors!(nodes[1], 1);
4018 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4019 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4020 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4021 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4022 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4023 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4024 assert!(bs_second_commitment_signed.update_fee.is_none());
4025 check_added_monitors!(nodes[1], 1);
4027 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4028 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4029 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4030 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4031 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4032 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4033 assert!(as_commitment_signed.update_fee.is_none());
4034 check_added_monitors!(nodes[0], 1);
4036 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4037 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4038 // No commitment_signed so get_event_msg's assert(len == 1) passes
4039 check_added_monitors!(nodes[0], 1);
4041 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4042 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4043 // No commitment_signed so get_event_msg's assert(len == 1) passes
4044 check_added_monitors!(nodes[1], 1);
4046 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4047 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4048 check_added_monitors!(nodes[1], 1);
4050 expect_pending_htlcs_forwardable!(nodes[1]);
4052 let events_5 = nodes[1].node.get_and_clear_pending_events();
4053 assert_eq!(events_5.len(), 1);
4055 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4056 assert_eq!(payment_hash_2, *payment_hash);
4057 assert_eq!(*payment_secret, None);
4059 _ => panic!("Unexpected event"),
4062 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4063 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4064 check_added_monitors!(nodes[0], 1);
4066 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4069 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4070 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4071 // to avoid our counterparty failing the channel.
4072 let chanmon_cfgs = create_chanmon_cfgs(2);
4073 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4074 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4075 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4077 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4078 let logger = test_utils::TestLogger::new();
4080 let our_payment_hash = if send_partial_mpp {
4081 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4082 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();
4083 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4084 let payment_secret = PaymentSecret([0xdb; 32]);
4085 // Use the utility function send_payment_along_path to send the payment with MPP data which
4086 // indicates there are more HTLCs coming.
4087 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4088 check_added_monitors!(nodes[0], 1);
4089 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4090 assert_eq!(events.len(), 1);
4091 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4092 // hop should *not* yet generate any PaymentReceived event(s).
4093 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4096 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4099 let mut block = Block {
4100 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4103 connect_block(&nodes[0], &block, 101);
4104 connect_block(&nodes[1], &block, 101);
4105 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4106 block.header.prev_blockhash = block.block_hash();
4107 connect_block(&nodes[0], &block, i);
4108 connect_block(&nodes[1], &block, i);
4111 expect_pending_htlcs_forwardable!(nodes[1]);
4113 check_added_monitors!(nodes[1], 1);
4114 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4115 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4116 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4117 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4118 assert!(htlc_timeout_updates.update_fee.is_none());
4120 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4121 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4122 // 100_000 msat as u64, followed by a height of 123 as u32
4123 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4124 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4125 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4129 fn test_htlc_timeout() {
4130 do_test_htlc_timeout(true);
4131 do_test_htlc_timeout(false);
4134 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4135 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4136 let chanmon_cfgs = create_chanmon_cfgs(3);
4137 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4138 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4139 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4140 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4141 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4142 let logger = test_utils::TestLogger::new();
4144 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4145 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4147 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4148 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();
4149 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4151 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4152 check_added_monitors!(nodes[1], 1);
4154 // Now attempt to route a second payment, which should be placed in the holding cell
4155 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4157 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4158 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();
4159 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4160 check_added_monitors!(nodes[0], 1);
4161 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4162 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4163 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4164 expect_pending_htlcs_forwardable!(nodes[1]);
4165 check_added_monitors!(nodes[1], 0);
4167 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4168 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();
4169 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4170 check_added_monitors!(nodes[1], 0);
4173 let mut block = Block {
4174 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4177 connect_block(&nodes[1], &block, 101);
4178 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4179 block.header.prev_blockhash = block.block_hash();
4180 connect_block(&nodes[1], &block, i);
4183 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4184 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4186 block.header.prev_blockhash = block.block_hash();
4187 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4190 expect_pending_htlcs_forwardable!(nodes[1]);
4191 check_added_monitors!(nodes[1], 1);
4192 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4193 assert_eq!(fail_commit.len(), 1);
4194 match fail_commit[0] {
4195 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4196 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4197 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4199 _ => unreachable!(),
4201 expect_payment_failed!(nodes[0], second_payment_hash, false);
4202 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4204 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4205 _ => panic!("Unexpected event"),
4208 panic!("Unexpected event");
4211 expect_payment_failed!(nodes[1], second_payment_hash, true);
4216 fn test_holding_cell_htlc_add_timeouts() {
4217 do_test_holding_cell_htlc_add_timeouts(false);
4218 do_test_holding_cell_htlc_add_timeouts(true);
4222 fn test_invalid_channel_announcement() {
4223 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4224 let secp_ctx = Secp256k1::new();
4225 let chanmon_cfgs = create_chanmon_cfgs(2);
4226 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4227 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4228 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4230 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4232 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4233 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4234 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4235 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4237 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 } );
4239 let as_bitcoin_key = as_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4240 let bs_bitcoin_key = bs_chan.get_signer().inner.holder_channel_pubkeys.funding_pubkey;
4242 let as_network_key = nodes[0].node.get_our_node_id();
4243 let bs_network_key = nodes[1].node.get_our_node_id();
4245 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4247 let mut chan_announcement;
4249 macro_rules! dummy_unsigned_msg {
4251 msgs::UnsignedChannelAnnouncement {
4252 features: ChannelFeatures::known(),
4253 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4254 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4255 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4256 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4257 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4258 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4259 excess_data: Vec::new(),
4264 macro_rules! sign_msg {
4265 ($unsigned_msg: expr) => {
4266 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4267 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_signer().inner.funding_key);
4268 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_signer().inner.funding_key);
4269 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4270 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4271 chan_announcement = msgs::ChannelAnnouncement {
4272 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4273 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4274 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4275 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4276 contents: $unsigned_msg
4281 let unsigned_msg = dummy_unsigned_msg!();
4282 sign_msg!(unsigned_msg);
4283 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4284 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 } );
4286 // Configured with Network::Testnet
4287 let mut unsigned_msg = dummy_unsigned_msg!();
4288 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4289 sign_msg!(unsigned_msg);
4290 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4292 let mut unsigned_msg = dummy_unsigned_msg!();
4293 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4294 sign_msg!(unsigned_msg);
4295 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4299 fn test_no_txn_manager_serialize_deserialize() {
4300 let chanmon_cfgs = create_chanmon_cfgs(2);
4301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4303 let logger: test_utils::TestLogger;
4304 let fee_estimator: test_utils::TestFeeEstimator;
4305 let persister: test_utils::TestPersister;
4306 let new_chain_monitor: test_utils::TestChainMonitor;
4307 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4308 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4310 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4312 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4314 let nodes_0_serialized = nodes[0].node.encode();
4315 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4316 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4318 logger = test_utils::TestLogger::new();
4319 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4320 persister = test_utils::TestPersister::new();
4321 let keys_manager = &chanmon_cfgs[0].keys_manager;
4322 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4323 nodes[0].chain_monitor = &new_chain_monitor;
4324 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4325 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4326 &mut chan_0_monitor_read, keys_manager).unwrap();
4327 assert!(chan_0_monitor_read.is_empty());
4329 let mut nodes_0_read = &nodes_0_serialized[..];
4330 let config = UserConfig::default();
4331 let (_, nodes_0_deserialized_tmp) = {
4332 let mut channel_monitors = HashMap::new();
4333 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4334 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4335 default_config: config,
4337 fee_estimator: &fee_estimator,
4338 chain_monitor: nodes[0].chain_monitor,
4339 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4344 nodes_0_deserialized = nodes_0_deserialized_tmp;
4345 assert!(nodes_0_read.is_empty());
4347 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4348 nodes[0].node = &nodes_0_deserialized;
4349 assert_eq!(nodes[0].node.list_channels().len(), 1);
4350 check_added_monitors!(nodes[0], 1);
4352 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4353 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4354 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4355 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4357 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4358 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4359 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4360 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4362 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4363 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4364 for node in nodes.iter() {
4365 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4366 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4367 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4370 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4374 fn test_manager_serialize_deserialize_events() {
4375 // This test makes sure the events field in ChannelManager survives de/serialization
4376 let chanmon_cfgs = create_chanmon_cfgs(2);
4377 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4378 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4379 let fee_estimator: test_utils::TestFeeEstimator;
4380 let persister: test_utils::TestPersister;
4381 let logger: test_utils::TestLogger;
4382 let new_chain_monitor: test_utils::TestChainMonitor;
4383 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4384 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4386 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4387 let channel_value = 100000;
4388 let push_msat = 10001;
4389 let a_flags = InitFeatures::known();
4390 let b_flags = InitFeatures::known();
4391 let node_a = nodes.remove(0);
4392 let node_b = nodes.remove(0);
4393 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4394 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()));
4395 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()));
4397 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4399 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4400 check_added_monitors!(node_a, 0);
4402 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()));
4404 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4405 assert_eq!(added_monitors.len(), 1);
4406 assert_eq!(added_monitors[0].0, funding_output);
4407 added_monitors.clear();
4410 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()));
4412 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4413 assert_eq!(added_monitors.len(), 1);
4414 assert_eq!(added_monitors[0].0, funding_output);
4415 added_monitors.clear();
4417 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4422 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4423 let nodes_0_serialized = nodes[0].node.encode();
4424 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4425 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4427 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4428 logger = test_utils::TestLogger::new();
4429 persister = test_utils::TestPersister::new();
4430 let keys_manager = &chanmon_cfgs[0].keys_manager;
4431 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4432 nodes[0].chain_monitor = &new_chain_monitor;
4433 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4434 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4435 &mut chan_0_monitor_read, keys_manager).unwrap();
4436 assert!(chan_0_monitor_read.is_empty());
4438 let mut nodes_0_read = &nodes_0_serialized[..];
4439 let config = UserConfig::default();
4440 let (_, nodes_0_deserialized_tmp) = {
4441 let mut channel_monitors = HashMap::new();
4442 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4443 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4444 default_config: config,
4446 fee_estimator: &fee_estimator,
4447 chain_monitor: nodes[0].chain_monitor,
4448 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4453 nodes_0_deserialized = nodes_0_deserialized_tmp;
4454 assert!(nodes_0_read.is_empty());
4456 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4458 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4459 nodes[0].node = &nodes_0_deserialized;
4461 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4462 let events_4 = nodes[0].node.get_and_clear_pending_events();
4463 assert_eq!(events_4.len(), 1);
4465 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4466 assert_eq!(user_channel_id, 42);
4467 assert_eq!(*funding_txo, funding_output);
4469 _ => panic!("Unexpected event"),
4472 // Make sure the channel is functioning as though the de/serialization never happened
4473 assert_eq!(nodes[0].node.list_channels().len(), 1);
4474 check_added_monitors!(nodes[0], 1);
4476 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4477 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4478 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4479 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4481 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4482 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4483 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4484 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4486 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4487 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4488 for node in nodes.iter() {
4489 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4490 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4491 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4494 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4498 fn test_simple_manager_serialize_deserialize() {
4499 let chanmon_cfgs = create_chanmon_cfgs(2);
4500 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4501 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4502 let logger: test_utils::TestLogger;
4503 let fee_estimator: test_utils::TestFeeEstimator;
4504 let persister: test_utils::TestPersister;
4505 let new_chain_monitor: test_utils::TestChainMonitor;
4506 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4507 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4508 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4510 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4511 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4513 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4515 let nodes_0_serialized = nodes[0].node.encode();
4516 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4517 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4519 logger = test_utils::TestLogger::new();
4520 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4521 persister = test_utils::TestPersister::new();
4522 let keys_manager = &chanmon_cfgs[0].keys_manager;
4523 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4524 nodes[0].chain_monitor = &new_chain_monitor;
4525 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4526 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
4527 &mut chan_0_monitor_read, keys_manager).unwrap();
4528 assert!(chan_0_monitor_read.is_empty());
4530 let mut nodes_0_read = &nodes_0_serialized[..];
4531 let (_, nodes_0_deserialized_tmp) = {
4532 let mut channel_monitors = HashMap::new();
4533 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4534 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4535 default_config: UserConfig::default(),
4537 fee_estimator: &fee_estimator,
4538 chain_monitor: nodes[0].chain_monitor,
4539 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4544 nodes_0_deserialized = nodes_0_deserialized_tmp;
4545 assert!(nodes_0_read.is_empty());
4547 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4548 nodes[0].node = &nodes_0_deserialized;
4549 check_added_monitors!(nodes[0], 1);
4551 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4553 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4554 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4558 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4559 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4560 let chanmon_cfgs = create_chanmon_cfgs(4);
4561 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4562 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4563 let logger: test_utils::TestLogger;
4564 let fee_estimator: test_utils::TestFeeEstimator;
4565 let persister: test_utils::TestPersister;
4566 let new_chain_monitor: test_utils::TestChainMonitor;
4567 let nodes_0_deserialized: ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4568 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4569 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4570 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4571 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4573 let mut node_0_stale_monitors_serialized = Vec::new();
4574 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4575 let mut writer = test_utils::TestVecWriter(Vec::new());
4576 monitor.1.write(&mut writer).unwrap();
4577 node_0_stale_monitors_serialized.push(writer.0);
4580 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4582 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4583 let nodes_0_serialized = nodes[0].node.encode();
4585 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4586 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4587 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4588 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4590 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4592 let mut node_0_monitors_serialized = Vec::new();
4593 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4594 let mut writer = test_utils::TestVecWriter(Vec::new());
4595 monitor.1.write(&mut writer).unwrap();
4596 node_0_monitors_serialized.push(writer.0);
4599 logger = test_utils::TestLogger::new();
4600 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4601 persister = test_utils::TestPersister::new();
4602 let keys_manager = &chanmon_cfgs[0].keys_manager;
4603 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4604 nodes[0].chain_monitor = &new_chain_monitor;
4607 let mut node_0_stale_monitors = Vec::new();
4608 for serialized in node_0_stale_monitors_serialized.iter() {
4609 let mut read = &serialized[..];
4610 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4611 assert!(read.is_empty());
4612 node_0_stale_monitors.push(monitor);
4615 let mut node_0_monitors = Vec::new();
4616 for serialized in node_0_monitors_serialized.iter() {
4617 let mut read = &serialized[..];
4618 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut read, keys_manager).unwrap();
4619 assert!(read.is_empty());
4620 node_0_monitors.push(monitor);
4623 let mut nodes_0_read = &nodes_0_serialized[..];
4624 if let Err(msgs::DecodeError::InvalidValue) =
4625 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4626 default_config: UserConfig::default(),
4628 fee_estimator: &fee_estimator,
4629 chain_monitor: nodes[0].chain_monitor,
4630 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4632 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4634 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4637 let mut nodes_0_read = &nodes_0_serialized[..];
4638 let (_, nodes_0_deserialized_tmp) =
4639 <(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4640 default_config: UserConfig::default(),
4642 fee_estimator: &fee_estimator,
4643 chain_monitor: nodes[0].chain_monitor,
4644 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4646 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4648 nodes_0_deserialized = nodes_0_deserialized_tmp;
4649 assert!(nodes_0_read.is_empty());
4651 { // Channel close should result in a commitment tx and an HTLC tx
4652 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4653 assert_eq!(txn.len(), 2);
4654 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4655 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4658 for monitor in node_0_monitors.drain(..) {
4659 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4660 check_added_monitors!(nodes[0], 1);
4662 nodes[0].node = &nodes_0_deserialized;
4664 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4665 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4666 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4667 //... and we can even still claim the payment!
4668 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4670 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4671 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4672 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4673 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4674 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4675 assert_eq!(msg_events.len(), 1);
4676 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4678 &ErrorAction::SendErrorMessage { ref msg } => {
4679 assert_eq!(msg.channel_id, channel_id);
4681 _ => panic!("Unexpected event!"),
4686 macro_rules! check_spendable_outputs {
4687 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4689 let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4690 let mut txn = Vec::new();
4691 let mut all_outputs = Vec::new();
4692 let secp_ctx = Secp256k1::new();
4693 for event in events.drain(..) {
4695 Event::SpendableOutputs { mut outputs } => {
4696 for outp in outputs.drain(..) {
4697 txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, &secp_ctx).unwrap());
4698 all_outputs.push(outp);
4701 _ => panic!("Unexpected event"),
4704 if all_outputs.len() > 1 {
4705 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) {
4715 fn test_claim_sizeable_push_msat() {
4716 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4717 let chanmon_cfgs = create_chanmon_cfgs(2);
4718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4722 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4723 nodes[1].node.force_close_channel(&chan.2).unwrap();
4724 check_closed_broadcast!(nodes[1], false);
4725 check_added_monitors!(nodes[1], 1);
4726 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4727 assert_eq!(node_txn.len(), 1);
4728 check_spends!(node_txn[0], chan.3);
4729 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
4731 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4732 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4733 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4735 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4736 assert_eq!(spend_txn.len(), 1);
4737 check_spends!(spend_txn[0], node_txn[0]);
4741 fn test_claim_on_remote_sizeable_push_msat() {
4742 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4743 // to_remote output is encumbered by a P2WPKH
4744 let chanmon_cfgs = create_chanmon_cfgs(2);
4745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4747 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4749 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4750 nodes[0].node.force_close_channel(&chan.2).unwrap();
4751 check_closed_broadcast!(nodes[0], false);
4752 check_added_monitors!(nodes[0], 1);
4754 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4755 assert_eq!(node_txn.len(), 1);
4756 check_spends!(node_txn[0], chan.3);
4757 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
4759 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4760 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4761 check_closed_broadcast!(nodes[1], false);
4762 check_added_monitors!(nodes[1], 1);
4763 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4765 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4766 assert_eq!(spend_txn.len(), 1);
4767 check_spends!(spend_txn[0], node_txn[0]);
4771 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4772 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4773 // to_remote output is encumbered by a P2WPKH
4775 let chanmon_cfgs = create_chanmon_cfgs(2);
4776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4778 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4780 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4781 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4782 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4783 assert_eq!(revoked_local_txn[0].input.len(), 1);
4784 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4786 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4787 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4788 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4789 check_closed_broadcast!(nodes[1], false);
4790 check_added_monitors!(nodes[1], 1);
4792 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4793 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4794 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4795 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4797 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4798 assert_eq!(spend_txn.len(), 3);
4799 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4800 check_spends!(spend_txn[1], node_txn[0]);
4801 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4805 fn test_static_spendable_outputs_preimage_tx() {
4806 let chanmon_cfgs = create_chanmon_cfgs(2);
4807 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4808 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4809 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4811 // Create some initial channels
4812 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4814 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4816 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4817 assert_eq!(commitment_tx[0].input.len(), 1);
4818 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4820 // Settle A's commitment tx on B's chain
4821 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4822 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4823 check_added_monitors!(nodes[1], 1);
4824 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4825 check_added_monitors!(nodes[1], 1);
4826 let events = nodes[1].node.get_and_clear_pending_msg_events();
4828 MessageSendEvent::UpdateHTLCs { .. } => {},
4829 _ => panic!("Unexpected event"),
4832 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4833 _ => panic!("Unexepected event"),
4836 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4837 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4838 assert_eq!(node_txn.len(), 3);
4839 check_spends!(node_txn[0], commitment_tx[0]);
4840 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4841 check_spends!(node_txn[1], chan_1.3);
4842 check_spends!(node_txn[2], node_txn[1]);
4844 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4845 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4846 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4848 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4849 assert_eq!(spend_txn.len(), 1);
4850 check_spends!(spend_txn[0], node_txn[0]);
4854 fn test_static_spendable_outputs_timeout_tx() {
4855 let chanmon_cfgs = create_chanmon_cfgs(2);
4856 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4857 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4858 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4860 // Create some initial channels
4861 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4863 // Rebalance the network a bit by relaying one payment through all the channels ...
4864 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4866 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4868 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4869 assert_eq!(commitment_tx[0].input.len(), 1);
4870 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4872 // Settle A's commitment tx on B' chain
4873 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4874 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4875 check_added_monitors!(nodes[1], 1);
4876 let events = nodes[1].node.get_and_clear_pending_msg_events();
4878 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4879 _ => panic!("Unexpected event"),
4882 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4883 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4884 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4885 check_spends!(node_txn[0], commitment_tx[0].clone());
4886 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4887 check_spends!(node_txn[1], chan_1.3.clone());
4888 check_spends!(node_txn[2], node_txn[1]);
4890 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4891 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4892 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4893 expect_payment_failed!(nodes[1], our_payment_hash, true);
4895 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4896 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4897 check_spends!(spend_txn[0], commitment_tx[0]);
4898 check_spends!(spend_txn[1], node_txn[0]);
4899 check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4903 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4904 let chanmon_cfgs = create_chanmon_cfgs(2);
4905 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4906 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4907 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4909 // Create some initial channels
4910 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4912 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4913 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4914 assert_eq!(revoked_local_txn[0].input.len(), 1);
4915 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4917 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4919 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4920 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4921 check_closed_broadcast!(nodes[1], false);
4922 check_added_monitors!(nodes[1], 1);
4924 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4925 assert_eq!(node_txn.len(), 2);
4926 assert_eq!(node_txn[0].input.len(), 2);
4927 check_spends!(node_txn[0], revoked_local_txn[0]);
4929 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4930 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4931 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4933 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4934 assert_eq!(spend_txn.len(), 1);
4935 check_spends!(spend_txn[0], node_txn[0]);
4939 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4940 let mut chanmon_cfgs = create_chanmon_cfgs(2);
4941 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4944 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4946 // Create some initial channels
4947 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4949 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4950 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4951 assert_eq!(revoked_local_txn[0].input.len(), 1);
4952 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4954 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4956 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4957 // A will generate HTLC-Timeout from revoked commitment tx
4958 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4959 check_closed_broadcast!(nodes[0], false);
4960 check_added_monitors!(nodes[0], 1);
4962 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4963 assert_eq!(revoked_htlc_txn.len(), 2);
4964 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4965 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4966 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4967 check_spends!(revoked_htlc_txn[1], chan_1.3);
4969 // B will generate justice tx from A's revoked commitment/HTLC tx
4970 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4971 check_closed_broadcast!(nodes[1], false);
4972 check_added_monitors!(nodes[1], 1);
4974 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4975 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
4976 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4977 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4978 // transactions next...
4979 assert_eq!(node_txn[0].input.len(), 3);
4980 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4982 assert_eq!(node_txn[1].input.len(), 2);
4983 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4984 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4985 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4987 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4988 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4991 assert_eq!(node_txn[2].input.len(), 1);
4992 check_spends!(node_txn[2], chan_1.3);
4994 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4995 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
4996 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4998 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4999 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5000 assert_eq!(spend_txn.len(), 1);
5001 assert_eq!(spend_txn[0].input.len(), 1);
5002 check_spends!(spend_txn[0], node_txn[1]);
5006 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5007 let mut chanmon_cfgs = create_chanmon_cfgs(2);
5008 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
5009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5011 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5013 // Create some initial channels
5014 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5016 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5017 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5018 assert_eq!(revoked_local_txn[0].input.len(), 1);
5019 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5021 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5022 assert_eq!(revoked_local_txn[0].output.len(), 2);
5024 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5026 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5027 // B will generate HTLC-Success from revoked commitment tx
5028 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5029 check_closed_broadcast!(nodes[1], false);
5030 check_added_monitors!(nodes[1], 1);
5031 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5033 assert_eq!(revoked_htlc_txn.len(), 2);
5034 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5035 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5036 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5038 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5039 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5040 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5042 // A will generate justice tx from B's revoked commitment/HTLC tx
5043 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5044 check_closed_broadcast!(nodes[0], false);
5045 check_added_monitors!(nodes[0], 1);
5047 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5048 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5050 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5051 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5052 // transactions next...
5053 assert_eq!(node_txn[0].input.len(), 2);
5054 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5055 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5056 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5058 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5059 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5062 assert_eq!(node_txn[1].input.len(), 1);
5063 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5065 check_spends!(node_txn[2], chan_1.3);
5067 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5068 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5069 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5071 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5072 // didn't try to generate any new transactions.
5074 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5075 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5076 assert_eq!(spend_txn.len(), 3);
5077 assert_eq!(spend_txn[0].input.len(), 1);
5078 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5079 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5080 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5081 check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
5085 fn test_onchain_to_onchain_claim() {
5086 // Test that in case of channel closure, we detect the state of output and claim HTLC
5087 // on downstream peer's remote commitment tx.
5088 // First, have C claim an HTLC against its own latest commitment transaction.
5089 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5091 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5094 let chanmon_cfgs = create_chanmon_cfgs(3);
5095 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5096 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5097 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5099 // Create some initial channels
5100 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5101 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5103 // Rebalance the network a bit by relaying one payment through all the channels ...
5104 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5105 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5107 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5108 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5109 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5110 check_spends!(commitment_tx[0], chan_2.3);
5111 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5112 check_added_monitors!(nodes[2], 1);
5113 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5114 assert!(updates.update_add_htlcs.is_empty());
5115 assert!(updates.update_fail_htlcs.is_empty());
5116 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5117 assert!(updates.update_fail_malformed_htlcs.is_empty());
5119 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5120 check_closed_broadcast!(nodes[2], false);
5121 check_added_monitors!(nodes[2], 1);
5123 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5124 assert_eq!(c_txn.len(), 3);
5125 assert_eq!(c_txn[0], c_txn[2]);
5126 assert_eq!(commitment_tx[0], c_txn[1]);
5127 check_spends!(c_txn[1], chan_2.3);
5128 check_spends!(c_txn[2], c_txn[1]);
5129 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5130 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5131 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5132 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5134 // 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
5135 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5137 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5138 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5139 assert_eq!(b_txn.len(), 3);
5140 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5141 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5142 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5143 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5144 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5145 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5146 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5147 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5148 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5151 check_added_monitors!(nodes[1], 1);
5152 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5153 check_added_monitors!(nodes[1], 1);
5154 match msg_events[0] {
5155 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5156 _ => panic!("Unexpected event"),
5158 match msg_events[1] {
5159 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, .. } } => {
5160 assert!(update_add_htlcs.is_empty());
5161 assert!(update_fail_htlcs.is_empty());
5162 assert_eq!(update_fulfill_htlcs.len(), 1);
5163 assert!(update_fail_malformed_htlcs.is_empty());
5164 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5166 _ => panic!("Unexpected event"),
5168 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5169 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5170 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5171 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5172 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5173 assert_eq!(b_txn.len(), 3);
5174 check_spends!(b_txn[1], chan_1.3);
5175 check_spends!(b_txn[2], b_txn[1]);
5176 check_spends!(b_txn[0], commitment_tx[0]);
5177 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5178 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5179 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5181 check_closed_broadcast!(nodes[1], false);
5182 check_added_monitors!(nodes[1], 1);
5186 fn test_duplicate_payment_hash_one_failure_one_success() {
5187 // Topology : A --> B --> C
5188 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5189 let chanmon_cfgs = create_chanmon_cfgs(3);
5190 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5191 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5192 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5194 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5195 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5197 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5198 *nodes[0].network_payment_count.borrow_mut() -= 1;
5199 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5201 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5202 assert_eq!(commitment_txn[0].input.len(), 1);
5203 check_spends!(commitment_txn[0], chan_2.3);
5205 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5206 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5207 check_closed_broadcast!(nodes[1], false);
5208 check_added_monitors!(nodes[1], 1);
5210 let htlc_timeout_tx;
5211 { // Extract one of the two HTLC-Timeout transaction
5212 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5213 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5214 assert_eq!(node_txn.len(), 5);
5215 check_spends!(node_txn[0], commitment_txn[0]);
5216 assert_eq!(node_txn[0].input.len(), 1);
5217 check_spends!(node_txn[1], commitment_txn[0]);
5218 assert_eq!(node_txn[1].input.len(), 1);
5219 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5220 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5221 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5222 check_spends!(node_txn[2], chan_2.3);
5223 check_spends!(node_txn[3], node_txn[2]);
5224 check_spends!(node_txn[4], node_txn[2]);
5225 htlc_timeout_tx = node_txn[1].clone();
5228 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5229 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5230 check_added_monitors!(nodes[2], 3);
5231 let events = nodes[2].node.get_and_clear_pending_msg_events();
5233 MessageSendEvent::UpdateHTLCs { .. } => {},
5234 _ => panic!("Unexpected event"),
5237 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5238 _ => panic!("Unexepected event"),
5240 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5241 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)
5242 check_spends!(htlc_success_txn[2], chan_2.3);
5243 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5244 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5245 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5246 assert_eq!(htlc_success_txn[0].input.len(), 1);
5247 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5248 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5249 assert_eq!(htlc_success_txn[1].input.len(), 1);
5250 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5251 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5252 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5253 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5255 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5256 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5257 expect_pending_htlcs_forwardable!(nodes[1]);
5258 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5259 assert!(htlc_updates.update_add_htlcs.is_empty());
5260 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5261 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5262 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5263 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5264 check_added_monitors!(nodes[1], 1);
5266 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5267 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5269 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5270 let events = nodes[0].node.get_and_clear_pending_msg_events();
5271 assert_eq!(events.len(), 1);
5273 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5275 _ => { panic!("Unexpected event"); }
5278 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5280 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5281 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5282 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5283 assert!(updates.update_add_htlcs.is_empty());
5284 assert!(updates.update_fail_htlcs.is_empty());
5285 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5286 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5287 assert!(updates.update_fail_malformed_htlcs.is_empty());
5288 check_added_monitors!(nodes[1], 1);
5290 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5291 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5293 let events = nodes[0].node.get_and_clear_pending_events();
5295 Event::PaymentSent { ref payment_preimage } => {
5296 assert_eq!(*payment_preimage, our_payment_preimage);
5298 _ => panic!("Unexpected event"),
5303 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5304 let chanmon_cfgs = create_chanmon_cfgs(2);
5305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5307 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5309 // Create some initial channels
5310 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5312 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5313 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5314 assert_eq!(local_txn.len(), 1);
5315 assert_eq!(local_txn[0].input.len(), 1);
5316 check_spends!(local_txn[0], chan_1.3);
5318 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5319 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5320 check_added_monitors!(nodes[1], 1);
5321 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5322 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5323 check_added_monitors!(nodes[1], 1);
5324 let events = nodes[1].node.get_and_clear_pending_msg_events();
5326 MessageSendEvent::UpdateHTLCs { .. } => {},
5327 _ => panic!("Unexpected event"),
5330 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5331 _ => panic!("Unexepected event"),
5334 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5335 assert_eq!(node_txn.len(), 3);
5336 assert_eq!(node_txn[0], node_txn[2]);
5337 assert_eq!(node_txn[1], local_txn[0]);
5338 assert_eq!(node_txn[0].input.len(), 1);
5339 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5340 check_spends!(node_txn[0], local_txn[0]);
5341 vec![node_txn[0].clone()]
5344 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5345 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5346 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5348 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5349 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5350 assert_eq!(spend_txn.len(), 1);
5351 check_spends!(spend_txn[0], node_txn[0]);
5354 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5355 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5356 // unrevoked commitment transaction.
5357 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5358 // a remote RAA before they could be failed backwards (and combinations thereof).
5359 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5360 // use the same payment hashes.
5361 // Thus, we use a six-node network:
5366 // And test where C fails back to A/B when D announces its latest commitment transaction
5367 let chanmon_cfgs = create_chanmon_cfgs(6);
5368 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5369 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5370 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5371 let logger = test_utils::TestLogger::new();
5373 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5374 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5375 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5376 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5377 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5379 // Rebalance and check output sanity...
5380 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5381 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5382 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5384 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5386 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
5388 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
5389 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5390 let our_node_id = &nodes[1].node.get_our_node_id();
5391 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();
5393 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
5395 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
5397 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5399 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5400 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();
5402 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5404 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5407 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5409 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();
5410 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
5413 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
5415 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();
5416 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5418 // Double-check that six of the new HTLC were added
5419 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5420 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5421 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5422 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5424 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5425 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5426 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5427 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5428 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5429 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5430 check_added_monitors!(nodes[4], 0);
5431 expect_pending_htlcs_forwardable!(nodes[4]);
5432 check_added_monitors!(nodes[4], 1);
5434 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5435 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5436 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5437 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5438 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5439 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5441 // Fail 3rd below-dust and 7th above-dust HTLCs
5442 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5443 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5444 check_added_monitors!(nodes[5], 0);
5445 expect_pending_htlcs_forwardable!(nodes[5]);
5446 check_added_monitors!(nodes[5], 1);
5448 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5449 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5450 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5451 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5453 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5455 expect_pending_htlcs_forwardable!(nodes[3]);
5456 check_added_monitors!(nodes[3], 1);
5457 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5458 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5459 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5460 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5461 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5462 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5463 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5464 if deliver_last_raa {
5465 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5467 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5470 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5471 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5472 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5473 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5475 // We now broadcast the latest commitment transaction, which *should* result in failures for
5476 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5477 // the non-broadcast above-dust HTLCs.
5479 // Alternatively, we may broadcast the previous commitment transaction, which should only
5480 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5481 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5483 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5484 if announce_latest {
5485 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5487 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5489 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5490 check_closed_broadcast!(nodes[2], false);
5491 expect_pending_htlcs_forwardable!(nodes[2]);
5492 check_added_monitors!(nodes[2], 3);
5494 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5495 assert_eq!(cs_msgs.len(), 2);
5496 let mut a_done = false;
5497 for msg in cs_msgs {
5499 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5500 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5501 // should be failed-backwards here.
5502 let target = if *node_id == nodes[0].node.get_our_node_id() {
5503 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5504 for htlc in &updates.update_fail_htlcs {
5505 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 });
5507 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5512 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5513 for htlc in &updates.update_fail_htlcs {
5514 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5516 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5517 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5520 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5521 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5522 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5523 if announce_latest {
5524 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5525 if *node_id == nodes[0].node.get_our_node_id() {
5526 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5529 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5531 _ => panic!("Unexpected event"),
5535 let as_events = nodes[0].node.get_and_clear_pending_events();
5536 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5537 let mut as_failds = HashSet::new();
5538 for event in as_events.iter() {
5539 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5540 assert!(as_failds.insert(*payment_hash));
5541 if *payment_hash != payment_hash_2 {
5542 assert_eq!(*rejected_by_dest, deliver_last_raa);
5544 assert!(!rejected_by_dest);
5546 } else { panic!("Unexpected event"); }
5548 assert!(as_failds.contains(&payment_hash_1));
5549 assert!(as_failds.contains(&payment_hash_2));
5550 if announce_latest {
5551 assert!(as_failds.contains(&payment_hash_3));
5552 assert!(as_failds.contains(&payment_hash_5));
5554 assert!(as_failds.contains(&payment_hash_6));
5556 let bs_events = nodes[1].node.get_and_clear_pending_events();
5557 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5558 let mut bs_failds = HashSet::new();
5559 for event in bs_events.iter() {
5560 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5561 assert!(bs_failds.insert(*payment_hash));
5562 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5563 assert_eq!(*rejected_by_dest, deliver_last_raa);
5565 assert!(!rejected_by_dest);
5567 } else { panic!("Unexpected event"); }
5569 assert!(bs_failds.contains(&payment_hash_1));
5570 assert!(bs_failds.contains(&payment_hash_2));
5571 if announce_latest {
5572 assert!(bs_failds.contains(&payment_hash_4));
5574 assert!(bs_failds.contains(&payment_hash_5));
5576 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5577 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5578 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5579 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5580 // PaymentFailureNetworkUpdates.
5581 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5582 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5583 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5584 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5585 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5587 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5588 _ => panic!("Unexpected event"),
5594 fn test_fail_backwards_latest_remote_announce_a() {
5595 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5599 fn test_fail_backwards_latest_remote_announce_b() {
5600 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5604 fn test_fail_backwards_previous_remote_announce() {
5605 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5606 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5607 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5611 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5612 let chanmon_cfgs = create_chanmon_cfgs(2);
5613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5617 // Create some initial channels
5618 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5620 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5621 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5622 assert_eq!(local_txn[0].input.len(), 1);
5623 check_spends!(local_txn[0], chan_1.3);
5625 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5626 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5627 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5628 check_closed_broadcast!(nodes[0], false);
5629 check_added_monitors!(nodes[0], 1);
5631 let htlc_timeout = {
5632 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5633 assert_eq!(node_txn[0].input.len(), 1);
5634 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5635 check_spends!(node_txn[0], local_txn[0]);
5639 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5640 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5641 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5642 expect_payment_failed!(nodes[0], our_payment_hash, true);
5644 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5645 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5646 assert_eq!(spend_txn.len(), 3);
5647 check_spends!(spend_txn[0], local_txn[0]);
5648 check_spends!(spend_txn[1], htlc_timeout);
5649 check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5653 fn test_key_derivation_params() {
5654 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5655 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5656 // let us re-derive the channel key set to then derive a delayed_payment_key.
5658 let chanmon_cfgs = create_chanmon_cfgs(3);
5660 // We manually create the node configuration to backup the seed.
5661 let seed = [42; 32];
5662 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5663 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);
5664 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 };
5665 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5666 node_cfgs.remove(0);
5667 node_cfgs.insert(0, node);
5669 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5670 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5672 // Create some initial channels
5673 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5675 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5676 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5677 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5679 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5680 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5681 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5682 assert_eq!(local_txn_1[0].input.len(), 1);
5683 check_spends!(local_txn_1[0], chan_1.3);
5685 // We check funding pubkey are unique
5686 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]));
5687 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]));
5688 if from_0_funding_key_0 == from_1_funding_key_0
5689 || from_0_funding_key_0 == from_1_funding_key_1
5690 || from_0_funding_key_1 == from_1_funding_key_0
5691 || from_0_funding_key_1 == from_1_funding_key_1 {
5692 panic!("Funding pubkeys aren't unique");
5695 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5696 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5697 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5698 check_closed_broadcast!(nodes[0], false);
5699 check_added_monitors!(nodes[0], 1);
5701 let htlc_timeout = {
5702 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5703 assert_eq!(node_txn[0].input.len(), 1);
5704 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5705 check_spends!(node_txn[0], local_txn_1[0]);
5709 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5710 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5711 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5712 expect_payment_failed!(nodes[0], our_payment_hash, true);
5714 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5715 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5716 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5717 assert_eq!(spend_txn.len(), 3);
5718 check_spends!(spend_txn[0], local_txn_1[0]);
5719 check_spends!(spend_txn[1], htlc_timeout);
5720 check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5724 fn test_static_output_closing_tx() {
5725 let chanmon_cfgs = create_chanmon_cfgs(2);
5726 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5727 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5728 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5730 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5732 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5733 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5735 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5736 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5737 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5739 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5740 assert_eq!(spend_txn.len(), 1);
5741 check_spends!(spend_txn[0], closing_tx);
5743 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5744 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5746 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5747 assert_eq!(spend_txn.len(), 1);
5748 check_spends!(spend_txn[0], closing_tx);
5751 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5752 let chanmon_cfgs = create_chanmon_cfgs(2);
5753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5755 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5756 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5758 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5760 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5761 // present in B's local commitment transaction, but none of A's commitment transactions.
5762 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5763 check_added_monitors!(nodes[1], 1);
5765 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5766 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5767 let events = nodes[0].node.get_and_clear_pending_events();
5768 assert_eq!(events.len(), 1);
5770 Event::PaymentSent { payment_preimage } => {
5771 assert_eq!(payment_preimage, our_payment_preimage);
5773 _ => panic!("Unexpected event"),
5776 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5777 check_added_monitors!(nodes[0], 1);
5778 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5779 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5780 check_added_monitors!(nodes[1], 1);
5782 let mut block = Block {
5783 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5786 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5787 connect_block(&nodes[1], &block, i);
5788 block.header.prev_blockhash = block.block_hash();
5790 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5791 check_closed_broadcast!(nodes[1], false);
5792 check_added_monitors!(nodes[1], 1);
5795 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5796 let chanmon_cfgs = create_chanmon_cfgs(2);
5797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5800 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5801 let logger = test_utils::TestLogger::new();
5803 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5804 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5805 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();
5806 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5807 check_added_monitors!(nodes[0], 1);
5809 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5811 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5812 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5813 // to "time out" the HTLC.
5815 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5817 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5818 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5819 header.prev_blockhash = header.block_hash();
5821 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5822 check_closed_broadcast!(nodes[0], false);
5823 check_added_monitors!(nodes[0], 1);
5826 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5827 let chanmon_cfgs = create_chanmon_cfgs(3);
5828 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5829 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5830 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5831 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5833 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5834 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5835 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5836 // actually revoked.
5837 let htlc_value = if use_dust { 50000 } else { 3000000 };
5838 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5839 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5840 expect_pending_htlcs_forwardable!(nodes[1]);
5841 check_added_monitors!(nodes[1], 1);
5843 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5844 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5845 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5846 check_added_monitors!(nodes[0], 1);
5847 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5848 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5849 check_added_monitors!(nodes[1], 1);
5850 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5851 check_added_monitors!(nodes[1], 1);
5852 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5854 if check_revoke_no_close {
5855 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5856 check_added_monitors!(nodes[0], 1);
5859 let mut block = Block {
5860 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5863 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5864 connect_block(&nodes[0], &block, i);
5865 block.header.prev_blockhash = block.block_hash();
5867 if !check_revoke_no_close {
5868 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5869 check_closed_broadcast!(nodes[0], false);
5870 check_added_monitors!(nodes[0], 1);
5872 expect_payment_failed!(nodes[0], our_payment_hash, true);
5876 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5877 // There are only a few cases to test here:
5878 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5879 // broadcastable commitment transactions result in channel closure,
5880 // * its included in an unrevoked-but-previous remote commitment transaction,
5881 // * its included in the latest remote or local commitment transactions.
5882 // We test each of the three possible commitment transactions individually and use both dust and
5884 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5885 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5886 // tested for at least one of the cases in other tests.
5888 fn htlc_claim_single_commitment_only_a() {
5889 do_htlc_claim_local_commitment_only(true);
5890 do_htlc_claim_local_commitment_only(false);
5892 do_htlc_claim_current_remote_commitment_only(true);
5893 do_htlc_claim_current_remote_commitment_only(false);
5897 fn htlc_claim_single_commitment_only_b() {
5898 do_htlc_claim_previous_remote_commitment_only(true, false);
5899 do_htlc_claim_previous_remote_commitment_only(false, false);
5900 do_htlc_claim_previous_remote_commitment_only(true, true);
5901 do_htlc_claim_previous_remote_commitment_only(false, true);
5906 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5907 let chanmon_cfgs = create_chanmon_cfgs(2);
5908 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5909 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5910 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5911 //Force duplicate channel ids
5912 for node in nodes.iter() {
5913 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5916 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5917 let channel_value_satoshis=10000;
5918 let push_msat=10001;
5919 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5920 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5921 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5923 //Create a second channel with a channel_id collision
5924 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5928 fn bolt2_open_channel_sending_node_checks_part2() {
5929 let chanmon_cfgs = create_chanmon_cfgs(2);
5930 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5931 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5932 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5934 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5935 let channel_value_satoshis=2^24;
5936 let push_msat=10001;
5937 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5939 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5940 let channel_value_satoshis=10000;
5941 // Test when push_msat is equal to 1000 * funding_satoshis.
5942 let push_msat=1000*channel_value_satoshis+1;
5943 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5945 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5946 let channel_value_satoshis=10000;
5947 let push_msat=10001;
5948 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
5949 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5950 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5952 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5953 // 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
5954 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5956 // 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.
5957 assert!(BREAKDOWN_TIMEOUT>0);
5958 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5960 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5961 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5962 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5964 // 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.
5965 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5966 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5967 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5968 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5969 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5972 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5973 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5974 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5975 // is no longer affordable once it's freed.
5977 fn test_fail_holding_cell_htlc_upon_free() {
5978 let chanmon_cfgs = create_chanmon_cfgs(2);
5979 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5980 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5981 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5982 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5983 let logger = test_utils::TestLogger::new();
5985 // First nodes[0] generates an update_fee, setting the channel's
5986 // pending_update_fee.
5987 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
5988 check_added_monitors!(nodes[0], 1);
5990 let events = nodes[0].node.get_and_clear_pending_msg_events();
5991 assert_eq!(events.len(), 1);
5992 let (update_msg, commitment_signed) = match events[0] {
5993 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5994 (update_fee.as_ref(), commitment_signed)
5996 _ => panic!("Unexpected event"),
5999 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6001 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6002 let channel_reserve = chan_stat.channel_reserve_msat;
6003 let feerate = get_feerate!(nodes[0], chan.2);
6005 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6006 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6007 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6008 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6009 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();
6011 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6012 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6013 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6014 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6016 // Flush the pending fee update.
6017 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6018 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6019 check_added_monitors!(nodes[1], 1);
6020 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6021 check_added_monitors!(nodes[0], 1);
6023 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6024 // HTLC, but now that the fee has been raised the payment will now fail, causing
6025 // us to surface its failure to the user.
6026 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6027 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6028 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6029 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);
6030 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6032 // Check that the payment failed to be sent out.
6033 let events = nodes[0].node.get_and_clear_pending_events();
6034 assert_eq!(events.len(), 1);
6036 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6037 assert_eq!(our_payment_hash.clone(), *payment_hash);
6038 assert_eq!(*rejected_by_dest, false);
6039 assert_eq!(*error_code, None);
6040 assert_eq!(*error_data, None);
6042 _ => panic!("Unexpected event"),
6046 // Test that if multiple HTLCs are released from the holding cell and one is
6047 // valid but the other is no longer valid upon release, the valid HTLC can be
6048 // successfully completed while the other one fails as expected.
6050 fn test_free_and_fail_holding_cell_htlcs() {
6051 let chanmon_cfgs = create_chanmon_cfgs(2);
6052 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6053 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6054 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6055 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6056 let logger = test_utils::TestLogger::new();
6058 // First nodes[0] generates an update_fee, setting the channel's
6059 // pending_update_fee.
6060 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6061 check_added_monitors!(nodes[0], 1);
6063 let events = nodes[0].node.get_and_clear_pending_msg_events();
6064 assert_eq!(events.len(), 1);
6065 let (update_msg, commitment_signed) = match events[0] {
6066 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6067 (update_fee.as_ref(), commitment_signed)
6069 _ => panic!("Unexpected event"),
6072 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6074 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6075 let channel_reserve = chan_stat.channel_reserve_msat;
6076 let feerate = get_feerate!(nodes[0], chan.2);
6078 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6079 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6081 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6082 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6083 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6084 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();
6085 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();
6087 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6088 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6089 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6090 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6091 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6092 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6093 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6095 // Flush the pending fee update.
6096 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6097 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6098 check_added_monitors!(nodes[1], 1);
6099 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6100 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6101 check_added_monitors!(nodes[0], 2);
6103 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6104 // but now that the fee has been raised the second payment will now fail, causing us
6105 // to surface its failure to the user. The first payment should succeed.
6106 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6107 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6108 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6109 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);
6110 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6112 // Check that the second payment failed to be sent out.
6113 let events = nodes[0].node.get_and_clear_pending_events();
6114 assert_eq!(events.len(), 1);
6116 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6117 assert_eq!(payment_hash_2.clone(), *payment_hash);
6118 assert_eq!(*rejected_by_dest, false);
6119 assert_eq!(*error_code, None);
6120 assert_eq!(*error_data, None);
6122 _ => panic!("Unexpected event"),
6125 // Complete the first payment and the RAA from the fee update.
6126 let (payment_event, send_raa_event) = {
6127 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6128 assert_eq!(msgs.len(), 2);
6129 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6131 let raa = match send_raa_event {
6132 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6133 _ => panic!("Unexpected event"),
6135 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6136 check_added_monitors!(nodes[1], 1);
6137 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6138 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6139 let events = nodes[1].node.get_and_clear_pending_events();
6140 assert_eq!(events.len(), 1);
6142 Event::PendingHTLCsForwardable { .. } => {},
6143 _ => panic!("Unexpected event"),
6145 nodes[1].node.process_pending_htlc_forwards();
6146 let events = nodes[1].node.get_and_clear_pending_events();
6147 assert_eq!(events.len(), 1);
6149 Event::PaymentReceived { .. } => {},
6150 _ => panic!("Unexpected event"),
6152 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6153 check_added_monitors!(nodes[1], 1);
6154 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6155 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6156 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6157 let events = nodes[0].node.get_and_clear_pending_events();
6158 assert_eq!(events.len(), 1);
6160 Event::PaymentSent { ref payment_preimage } => {
6161 assert_eq!(*payment_preimage, payment_preimage_1);
6163 _ => panic!("Unexpected event"),
6167 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6168 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6169 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6172 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6173 let chanmon_cfgs = create_chanmon_cfgs(3);
6174 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6175 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6176 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6177 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6178 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6179 let logger = test_utils::TestLogger::new();
6181 // First nodes[1] generates an update_fee, setting the channel's
6182 // pending_update_fee.
6183 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6184 check_added_monitors!(nodes[1], 1);
6186 let events = nodes[1].node.get_and_clear_pending_msg_events();
6187 assert_eq!(events.len(), 1);
6188 let (update_msg, commitment_signed) = match events[0] {
6189 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6190 (update_fee.as_ref(), commitment_signed)
6192 _ => panic!("Unexpected event"),
6195 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6197 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6198 let channel_reserve = chan_stat.channel_reserve_msat;
6199 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6201 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6203 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6204 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6205 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6206 let payment_event = {
6207 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6208 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();
6209 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6210 check_added_monitors!(nodes[0], 1);
6212 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6213 assert_eq!(events.len(), 1);
6215 SendEvent::from_event(events.remove(0))
6217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6218 check_added_monitors!(nodes[1], 0);
6219 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6220 expect_pending_htlcs_forwardable!(nodes[1]);
6222 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6223 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6225 // Flush the pending fee update.
6226 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6227 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6228 check_added_monitors!(nodes[2], 1);
6229 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6230 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6231 check_added_monitors!(nodes[1], 2);
6233 // A final RAA message is generated to finalize the fee update.
6234 let events = nodes[1].node.get_and_clear_pending_msg_events();
6235 assert_eq!(events.len(), 1);
6237 let raa_msg = match &events[0] {
6238 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6241 _ => panic!("Unexpected event"),
6244 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6245 check_added_monitors!(nodes[2], 1);
6246 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6248 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6249 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6250 assert_eq!(process_htlc_forwards_event.len(), 1);
6251 match &process_htlc_forwards_event[0] {
6252 &Event::PendingHTLCsForwardable { .. } => {},
6253 _ => panic!("Unexpected event"),
6256 // In response, we call ChannelManager's process_pending_htlc_forwards
6257 nodes[1].node.process_pending_htlc_forwards();
6258 check_added_monitors!(nodes[1], 1);
6260 // This causes the HTLC to be failed backwards.
6261 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6262 assert_eq!(fail_event.len(), 1);
6263 let (fail_msg, commitment_signed) = match &fail_event[0] {
6264 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6265 assert_eq!(updates.update_add_htlcs.len(), 0);
6266 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6267 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6268 assert_eq!(updates.update_fail_htlcs.len(), 1);
6269 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6271 _ => panic!("Unexpected event"),
6274 // Pass the failure messages back to nodes[0].
6275 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6276 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6278 // Complete the HTLC failure+removal process.
6279 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6280 check_added_monitors!(nodes[0], 1);
6281 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6282 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6283 check_added_monitors!(nodes[1], 2);
6284 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6285 assert_eq!(final_raa_event.len(), 1);
6286 let raa = match &final_raa_event[0] {
6287 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6288 _ => panic!("Unexpected event"),
6290 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6291 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6292 assert_eq!(fail_msg_event.len(), 1);
6293 match &fail_msg_event[0] {
6294 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6295 _ => panic!("Unexpected event"),
6297 let failure_event = nodes[0].node.get_and_clear_pending_events();
6298 assert_eq!(failure_event.len(), 1);
6299 match &failure_event[0] {
6300 &Event::PaymentFailed { rejected_by_dest, .. } => {
6301 assert!(!rejected_by_dest);
6303 _ => panic!("Unexpected event"),
6305 check_added_monitors!(nodes[0], 1);
6308 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6309 // 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.
6310 //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.
6313 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6314 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6315 let chanmon_cfgs = create_chanmon_cfgs(2);
6316 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6317 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6318 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6319 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6321 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6322 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6323 let logger = test_utils::TestLogger::new();
6324 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();
6325 route.paths[0][0].fee_msat = 100;
6327 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6328 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6329 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6330 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6334 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6335 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6336 let chanmon_cfgs = create_chanmon_cfgs(2);
6337 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6338 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6339 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6340 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6341 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6343 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6344 let logger = test_utils::TestLogger::new();
6345 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();
6346 route.paths[0][0].fee_msat = 0;
6347 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6348 assert_eq!(err, "Cannot send 0-msat HTLC"));
6350 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6351 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6355 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6356 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6357 let chanmon_cfgs = create_chanmon_cfgs(2);
6358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6360 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6361 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6363 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6364 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6365 let logger = test_utils::TestLogger::new();
6366 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();
6367 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6368 check_added_monitors!(nodes[0], 1);
6369 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6370 updates.update_add_htlcs[0].amount_msat = 0;
6372 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6373 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6374 check_closed_broadcast!(nodes[1], true).unwrap();
6375 check_added_monitors!(nodes[1], 1);
6379 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6380 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6381 //It is enforced when constructing a route.
6382 let chanmon_cfgs = create_chanmon_cfgs(2);
6383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6385 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6386 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6387 let logger = test_utils::TestLogger::new();
6389 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6391 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6392 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();
6393 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6394 assert_eq!(err, &"Channel CLTV overflowed?"));
6398 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6399 //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.
6400 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6401 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6402 let chanmon_cfgs = create_chanmon_cfgs(2);
6403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6405 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6406 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6407 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6409 let logger = test_utils::TestLogger::new();
6410 for i in 0..max_accepted_htlcs {
6411 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6412 let payment_event = {
6413 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6414 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();
6415 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6416 check_added_monitors!(nodes[0], 1);
6418 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6419 assert_eq!(events.len(), 1);
6420 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6421 assert_eq!(htlcs[0].htlc_id, i);
6425 SendEvent::from_event(events.remove(0))
6427 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6428 check_added_monitors!(nodes[1], 0);
6429 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6431 expect_pending_htlcs_forwardable!(nodes[1]);
6432 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6434 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6435 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6436 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();
6437 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6438 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6440 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6441 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6445 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6446 //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.
6447 let chanmon_cfgs = create_chanmon_cfgs(2);
6448 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6449 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6450 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6451 let channel_value = 100000;
6452 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6453 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6455 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6457 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6458 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6459 let logger = test_utils::TestLogger::new();
6460 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6461 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6462 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)));
6464 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6465 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);
6467 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6470 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6472 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6473 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6474 let chanmon_cfgs = create_chanmon_cfgs(2);
6475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6478 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6479 let htlc_minimum_msat: u64;
6481 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6482 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6483 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6486 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6487 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6488 let logger = test_utils::TestLogger::new();
6489 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();
6490 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6491 check_added_monitors!(nodes[0], 1);
6492 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6493 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6494 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6495 assert!(nodes[1].node.list_channels().is_empty());
6496 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6497 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()));
6498 check_added_monitors!(nodes[1], 1);
6502 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6503 //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
6504 let chanmon_cfgs = create_chanmon_cfgs(2);
6505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6507 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6508 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6509 let logger = test_utils::TestLogger::new();
6511 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6512 let channel_reserve = chan_stat.channel_reserve_msat;
6513 let feerate = get_feerate!(nodes[0], chan.2);
6514 // The 2* and +1 are for the fee spike reserve.
6515 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6517 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6518 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6519 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6520 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();
6521 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6522 check_added_monitors!(nodes[0], 1);
6523 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6525 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6526 // at this time channel-initiatee receivers are not required to enforce that senders
6527 // respect the fee_spike_reserve.
6528 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6529 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6531 assert!(nodes[1].node.list_channels().is_empty());
6532 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6533 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6534 check_added_monitors!(nodes[1], 1);
6538 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6539 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6540 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6541 let chanmon_cfgs = create_chanmon_cfgs(2);
6542 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6543 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6544 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6545 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6546 let logger = test_utils::TestLogger::new();
6548 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6549 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6551 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6552 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();
6554 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6555 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6556 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6557 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6559 let mut msg = msgs::UpdateAddHTLC {
6563 payment_hash: our_payment_hash,
6564 cltv_expiry: htlc_cltv,
6565 onion_routing_packet: onion_packet.clone(),
6568 for i in 0..super::channel::OUR_MAX_HTLCS {
6569 msg.htlc_id = i as u64;
6570 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6572 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6573 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6575 assert!(nodes[1].node.list_channels().is_empty());
6576 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6577 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6578 check_added_monitors!(nodes[1], 1);
6582 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6583 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6584 let chanmon_cfgs = create_chanmon_cfgs(2);
6585 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6586 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6587 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6588 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6589 let logger = test_utils::TestLogger::new();
6591 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6592 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6593 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();
6594 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6595 check_added_monitors!(nodes[0], 1);
6596 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6597 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6598 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6600 assert!(nodes[1].node.list_channels().is_empty());
6601 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6602 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6603 check_added_monitors!(nodes[1], 1);
6607 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6608 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6609 let chanmon_cfgs = create_chanmon_cfgs(2);
6610 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6611 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6612 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6613 let logger = test_utils::TestLogger::new();
6615 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6616 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6617 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6618 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();
6619 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6620 check_added_monitors!(nodes[0], 1);
6621 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6622 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6625 assert!(nodes[1].node.list_channels().is_empty());
6626 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6627 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6628 check_added_monitors!(nodes[1], 1);
6632 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6633 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6634 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6635 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6636 let chanmon_cfgs = create_chanmon_cfgs(2);
6637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6640 let logger = test_utils::TestLogger::new();
6642 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6643 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6644 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6645 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();
6646 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6647 check_added_monitors!(nodes[0], 1);
6648 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6649 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6651 //Disconnect and Reconnect
6652 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6653 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6654 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6655 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6656 assert_eq!(reestablish_1.len(), 1);
6657 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6658 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6659 assert_eq!(reestablish_2.len(), 1);
6660 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6661 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6662 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6663 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6666 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6667 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6668 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6669 check_added_monitors!(nodes[1], 1);
6670 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6672 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6674 assert!(nodes[1].node.list_channels().is_empty());
6675 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6676 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6677 check_added_monitors!(nodes[1], 1);
6681 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6682 //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.
6684 let chanmon_cfgs = create_chanmon_cfgs(2);
6685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6687 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688 let logger = test_utils::TestLogger::new();
6689 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6690 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6691 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6692 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();
6693 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6695 check_added_monitors!(nodes[0], 1);
6696 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6697 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6699 let update_msg = msgs::UpdateFulfillHTLC{
6702 payment_preimage: our_payment_preimage,
6705 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6707 assert!(nodes[0].node.list_channels().is_empty());
6708 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6709 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()));
6710 check_added_monitors!(nodes[0], 1);
6714 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6715 //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.
6717 let chanmon_cfgs = create_chanmon_cfgs(2);
6718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6720 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6721 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6722 let logger = test_utils::TestLogger::new();
6724 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6725 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6726 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();
6727 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6728 check_added_monitors!(nodes[0], 1);
6729 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6730 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6732 let update_msg = msgs::UpdateFailHTLC{
6735 reason: msgs::OnionErrorPacket { data: Vec::new()},
6738 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6740 assert!(nodes[0].node.list_channels().is_empty());
6741 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6742 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()));
6743 check_added_monitors!(nodes[0], 1);
6747 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6748 //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.
6750 let chanmon_cfgs = create_chanmon_cfgs(2);
6751 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6752 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6753 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6754 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6755 let logger = test_utils::TestLogger::new();
6757 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6758 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6759 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();
6760 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6761 check_added_monitors!(nodes[0], 1);
6762 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6763 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6765 let update_msg = msgs::UpdateFailMalformedHTLC{
6768 sha256_of_onion: [1; 32],
6769 failure_code: 0x8000,
6772 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6774 assert!(nodes[0].node.list_channels().is_empty());
6775 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6776 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()));
6777 check_added_monitors!(nodes[0], 1);
6781 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6782 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6784 let chanmon_cfgs = create_chanmon_cfgs(2);
6785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6788 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6790 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6792 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6793 check_added_monitors!(nodes[1], 1);
6795 let events = nodes[1].node.get_and_clear_pending_msg_events();
6796 assert_eq!(events.len(), 1);
6797 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6799 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, .. } } => {
6800 assert!(update_add_htlcs.is_empty());
6801 assert_eq!(update_fulfill_htlcs.len(), 1);
6802 assert!(update_fail_htlcs.is_empty());
6803 assert!(update_fail_malformed_htlcs.is_empty());
6804 assert!(update_fee.is_none());
6805 update_fulfill_htlcs[0].clone()
6807 _ => panic!("Unexpected event"),
6811 update_fulfill_msg.htlc_id = 1;
6813 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6815 assert!(nodes[0].node.list_channels().is_empty());
6816 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6817 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6818 check_added_monitors!(nodes[0], 1);
6822 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6823 //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.
6825 let chanmon_cfgs = create_chanmon_cfgs(2);
6826 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6827 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6828 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6829 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6831 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6833 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6834 check_added_monitors!(nodes[1], 1);
6836 let events = nodes[1].node.get_and_clear_pending_msg_events();
6837 assert_eq!(events.len(), 1);
6838 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6840 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, .. } } => {
6841 assert!(update_add_htlcs.is_empty());
6842 assert_eq!(update_fulfill_htlcs.len(), 1);
6843 assert!(update_fail_htlcs.is_empty());
6844 assert!(update_fail_malformed_htlcs.is_empty());
6845 assert!(update_fee.is_none());
6846 update_fulfill_htlcs[0].clone()
6848 _ => panic!("Unexpected event"),
6852 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6854 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6856 assert!(nodes[0].node.list_channels().is_empty());
6857 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6858 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6859 check_added_monitors!(nodes[0], 1);
6863 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6864 //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.
6866 let chanmon_cfgs = create_chanmon_cfgs(2);
6867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6869 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6870 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6871 let logger = test_utils::TestLogger::new();
6873 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6874 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6875 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();
6876 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6877 check_added_monitors!(nodes[0], 1);
6879 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6880 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6882 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6883 check_added_monitors!(nodes[1], 0);
6884 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6886 let events = nodes[1].node.get_and_clear_pending_msg_events();
6888 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6890 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, .. } } => {
6891 assert!(update_add_htlcs.is_empty());
6892 assert!(update_fulfill_htlcs.is_empty());
6893 assert!(update_fail_htlcs.is_empty());
6894 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6895 assert!(update_fee.is_none());
6896 update_fail_malformed_htlcs[0].clone()
6898 _ => panic!("Unexpected event"),
6901 update_msg.failure_code &= !0x8000;
6902 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6904 assert!(nodes[0].node.list_channels().is_empty());
6905 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6906 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6907 check_added_monitors!(nodes[0], 1);
6911 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6912 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6913 // * 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.
6915 let chanmon_cfgs = create_chanmon_cfgs(3);
6916 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6917 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6918 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6919 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6920 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6921 let logger = test_utils::TestLogger::new();
6923 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6926 let mut payment_event = {
6927 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6928 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();
6929 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6930 check_added_monitors!(nodes[0], 1);
6931 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6932 assert_eq!(events.len(), 1);
6933 SendEvent::from_event(events.remove(0))
6935 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6936 check_added_monitors!(nodes[1], 0);
6937 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6938 expect_pending_htlcs_forwardable!(nodes[1]);
6939 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6940 assert_eq!(events_2.len(), 1);
6941 check_added_monitors!(nodes[1], 1);
6942 payment_event = SendEvent::from_event(events_2.remove(0));
6943 assert_eq!(payment_event.msgs.len(), 1);
6946 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6947 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6948 check_added_monitors!(nodes[2], 0);
6949 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6951 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6952 assert_eq!(events_3.len(), 1);
6953 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6955 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 } } => {
6956 assert!(update_add_htlcs.is_empty());
6957 assert!(update_fulfill_htlcs.is_empty());
6958 assert!(update_fail_htlcs.is_empty());
6959 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6960 assert!(update_fee.is_none());
6961 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6963 _ => panic!("Unexpected event"),
6967 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6969 check_added_monitors!(nodes[1], 0);
6970 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6971 expect_pending_htlcs_forwardable!(nodes[1]);
6972 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6973 assert_eq!(events_4.len(), 1);
6975 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6977 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, .. } } => {
6978 assert!(update_add_htlcs.is_empty());
6979 assert!(update_fulfill_htlcs.is_empty());
6980 assert_eq!(update_fail_htlcs.len(), 1);
6981 assert!(update_fail_malformed_htlcs.is_empty());
6982 assert!(update_fee.is_none());
6984 _ => panic!("Unexpected event"),
6987 check_added_monitors!(nodes[1], 1);
6990 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6991 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6992 // 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
6993 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6995 let mut chanmon_cfgs = create_chanmon_cfgs(2);
6996 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
6997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7000 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7002 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7004 // We route 2 dust-HTLCs between A and B
7005 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7006 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7007 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7009 // Cache one local commitment tx as previous
7010 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7012 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7013 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7014 check_added_monitors!(nodes[1], 0);
7015 expect_pending_htlcs_forwardable!(nodes[1]);
7016 check_added_monitors!(nodes[1], 1);
7018 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7019 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7020 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7021 check_added_monitors!(nodes[0], 1);
7023 // Cache one local commitment tx as lastest
7024 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7026 let events = nodes[0].node.get_and_clear_pending_msg_events();
7028 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7029 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7031 _ => panic!("Unexpected event"),
7034 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7035 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7037 _ => panic!("Unexpected event"),
7040 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7041 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7042 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7044 if announce_latest {
7045 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7047 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7050 check_closed_broadcast!(nodes[0], false);
7051 check_added_monitors!(nodes[0], 1);
7053 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7054 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7055 let events = nodes[0].node.get_and_clear_pending_events();
7056 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7057 assert_eq!(events.len(), 2);
7058 let mut first_failed = false;
7059 for event in events {
7061 Event::PaymentFailed { payment_hash, .. } => {
7062 if payment_hash == payment_hash_1 {
7063 assert!(!first_failed);
7064 first_failed = true;
7066 assert_eq!(payment_hash, payment_hash_2);
7069 _ => panic!("Unexpected event"),
7075 fn test_failure_delay_dust_htlc_local_commitment() {
7076 do_test_failure_delay_dust_htlc_local_commitment(true);
7077 do_test_failure_delay_dust_htlc_local_commitment(false);
7080 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7081 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7082 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7083 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7084 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7085 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7086 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7088 let chanmon_cfgs = create_chanmon_cfgs(3);
7089 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7090 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7091 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7092 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7094 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7096 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7097 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7099 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7100 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7102 // We revoked bs_commitment_tx
7104 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7105 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7108 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7109 let mut timeout_tx = Vec::new();
7111 // We fail dust-HTLC 1 by broadcast of local commitment tx
7112 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7113 check_closed_broadcast!(nodes[0], false);
7114 check_added_monitors!(nodes[0], 1);
7115 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7116 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7117 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7118 expect_payment_failed!(nodes[0], dust_hash, true);
7119 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7120 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7121 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7122 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7123 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7124 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7125 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7126 expect_payment_failed!(nodes[0], non_dust_hash, true);
7128 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7129 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7130 check_closed_broadcast!(nodes[0], false);
7131 check_added_monitors!(nodes[0], 1);
7132 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7133 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7134 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7135 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7137 expect_payment_failed!(nodes[0], dust_hash, true);
7138 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7139 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7140 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7141 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7142 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7143 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7144 expect_payment_failed!(nodes[0], non_dust_hash, true);
7146 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7148 let events = nodes[0].node.get_and_clear_pending_events();
7149 assert_eq!(events.len(), 2);
7152 Event::PaymentFailed { payment_hash, .. } => {
7153 if payment_hash == dust_hash { first = true; }
7154 else { first = false; }
7156 _ => panic!("Unexpected event"),
7159 Event::PaymentFailed { payment_hash, .. } => {
7160 if first { assert_eq!(payment_hash, non_dust_hash); }
7161 else { assert_eq!(payment_hash, dust_hash); }
7163 _ => panic!("Unexpected event"),
7170 fn test_sweep_outbound_htlc_failure_update() {
7171 do_test_sweep_outbound_htlc_failure_update(false, true);
7172 do_test_sweep_outbound_htlc_failure_update(false, false);
7173 do_test_sweep_outbound_htlc_failure_update(true, false);
7177 fn test_upfront_shutdown_script() {
7178 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7179 // enforce it at shutdown message
7181 let mut config = UserConfig::default();
7182 config.channel_options.announced_channel = true;
7183 config.peer_channel_config_limits.force_announced_channel_preference = false;
7184 config.channel_options.commit_upfront_shutdown_pubkey = false;
7185 let user_cfgs = [None, Some(config), None];
7186 let chanmon_cfgs = create_chanmon_cfgs(3);
7187 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7188 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7189 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7191 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7192 let flags = InitFeatures::known();
7193 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7194 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7195 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7196 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7197 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7198 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7199 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()));
7200 check_added_monitors!(nodes[2], 1);
7202 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7203 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7204 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7205 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7206 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7207 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7208 let events = nodes[2].node.get_and_clear_pending_msg_events();
7209 assert_eq!(events.len(), 1);
7211 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7212 _ => panic!("Unexpected event"),
7215 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7216 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7217 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7218 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7219 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7220 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7221 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7222 let events = nodes[1].node.get_and_clear_pending_msg_events();
7223 assert_eq!(events.len(), 1);
7225 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7226 _ => panic!("Unexpected event"),
7229 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7230 // channel smoothly, opt-out is from channel initiator here
7231 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7232 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7233 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7234 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7235 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7236 let events = nodes[0].node.get_and_clear_pending_msg_events();
7237 assert_eq!(events.len(), 1);
7239 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7240 _ => panic!("Unexpected event"),
7243 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7244 //// channel smoothly
7245 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7246 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7247 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7248 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7249 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7250 let events = nodes[0].node.get_and_clear_pending_msg_events();
7251 assert_eq!(events.len(), 2);
7253 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7254 _ => panic!("Unexpected event"),
7257 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7258 _ => panic!("Unexpected event"),
7263 fn test_user_configurable_csv_delay() {
7264 // We test our channel constructors yield errors when we pass them absurd csv delay
7266 let mut low_our_to_self_config = UserConfig::default();
7267 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7268 let mut high_their_to_self_config = UserConfig::default();
7269 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7270 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7271 let chanmon_cfgs = create_chanmon_cfgs(2);
7272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7274 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7276 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7277 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) {
7279 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())); },
7280 _ => panic!("Unexpected event"),
7282 } else { assert!(false) }
7284 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7285 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7286 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7287 open_channel.to_self_delay = 200;
7288 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) {
7290 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())); },
7291 _ => panic!("Unexpected event"),
7293 } else { assert!(false); }
7295 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7296 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7297 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()));
7298 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7299 accept_channel.to_self_delay = 200;
7300 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7301 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7303 &ErrorAction::SendErrorMessage { ref msg } => {
7304 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()));
7306 _ => { assert!(false); }
7308 } else { assert!(false); }
7310 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7311 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7312 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7313 open_channel.to_self_delay = 200;
7314 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) {
7316 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())); },
7317 _ => panic!("Unexpected event"),
7319 } else { assert!(false); }
7323 fn test_data_loss_protect() {
7324 // We want to be sure that :
7325 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7326 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7327 // * we close channel in case of detecting other being fallen behind
7328 // * we are able to claim our own outputs thanks to to_remote being static
7329 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7335 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7336 // We broadcast during Drop because chanmon is out of sync with chanmgr, which would cause a panic
7337 // during signing due to revoked tx
7338 chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7339 let keys_manager = &chanmon_cfgs[0].keys_manager;
7342 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7343 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7344 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7346 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7348 // Cache node A state before any channel update
7349 let previous_node_state = nodes[0].node.encode();
7350 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7351 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7353 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7354 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7356 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7357 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7359 // Restore node A from previous state
7360 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7361 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7362 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7363 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7364 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7365 persister = test_utils::TestPersister::new();
7366 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7368 let mut channel_monitors = HashMap::new();
7369 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7370 <(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 {
7371 keys_manager: keys_manager,
7372 fee_estimator: &fee_estimator,
7373 chain_monitor: &monitor,
7375 tx_broadcaster: &tx_broadcaster,
7376 default_config: UserConfig::default(),
7380 nodes[0].node = &node_state_0;
7381 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7382 nodes[0].chain_monitor = &monitor;
7383 nodes[0].chain_source = &chain_source;
7385 check_added_monitors!(nodes[0], 1);
7387 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7388 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7390 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7392 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7393 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7394 check_added_monitors!(nodes[0], 1);
7397 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7398 assert_eq!(node_txn.len(), 0);
7401 let mut reestablish_1 = Vec::with_capacity(1);
7402 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7403 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7404 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7405 reestablish_1.push(msg.clone());
7406 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7407 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7409 &ErrorAction::SendErrorMessage { ref msg } => {
7410 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");
7412 _ => panic!("Unexpected event!"),
7415 panic!("Unexpected event")
7419 // Check we close channel detecting A is fallen-behind
7420 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7421 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7422 check_added_monitors!(nodes[1], 1);
7425 // Check A is able to claim to_remote output
7426 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7427 assert_eq!(node_txn.len(), 1);
7428 check_spends!(node_txn[0], chan.3);
7429 assert_eq!(node_txn[0].output.len(), 2);
7430 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7431 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7432 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7433 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 1000000);
7434 assert_eq!(spend_txn.len(), 1);
7435 check_spends!(spend_txn[0], node_txn[0]);
7439 fn test_check_htlc_underpaying() {
7440 // Send payment through A -> B but A is maliciously
7441 // sending a probe payment (i.e less than expected value0
7442 // to B, B should refuse payment.
7444 let chanmon_cfgs = create_chanmon_cfgs(2);
7445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7447 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7449 // Create some initial channels
7450 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7452 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7454 // Node 3 is expecting payment of 100_000 but receive 10_000,
7455 // fail htlc like we didn't know the preimage.
7456 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7457 nodes[1].node.process_pending_htlc_forwards();
7459 let events = nodes[1].node.get_and_clear_pending_msg_events();
7460 assert_eq!(events.len(), 1);
7461 let (update_fail_htlc, commitment_signed) = match events[0] {
7462 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 } } => {
7463 assert!(update_add_htlcs.is_empty());
7464 assert!(update_fulfill_htlcs.is_empty());
7465 assert_eq!(update_fail_htlcs.len(), 1);
7466 assert!(update_fail_malformed_htlcs.is_empty());
7467 assert!(update_fee.is_none());
7468 (update_fail_htlcs[0].clone(), commitment_signed)
7470 _ => panic!("Unexpected event"),
7472 check_added_monitors!(nodes[1], 1);
7474 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7475 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7477 // 10_000 msat as u64, followed by a height of 99 as u32
7478 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7479 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7480 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7481 nodes[1].node.get_and_clear_pending_events();
7485 fn test_announce_disable_channels() {
7486 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7487 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7489 let chanmon_cfgs = create_chanmon_cfgs(2);
7490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7494 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7495 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7496 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7499 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7500 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7502 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7503 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7504 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7505 assert_eq!(msg_events.len(), 3);
7506 for e in msg_events {
7508 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7509 let short_id = msg.contents.short_channel_id;
7510 // Check generated channel_update match list in PendingChannelUpdate
7511 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7512 panic!("Generated ChannelUpdate for wrong chan!");
7515 _ => panic!("Unexpected event"),
7519 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7520 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7521 assert_eq!(reestablish_1.len(), 3);
7522 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7523 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7524 assert_eq!(reestablish_2.len(), 3);
7526 // Reestablish chan_1
7527 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7528 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7529 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7530 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7531 // Reestablish chan_2
7532 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7533 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7534 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7535 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7536 // Reestablish chan_3
7537 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7538 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7539 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7540 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7542 nodes[0].node.timer_chan_freshness_every_min();
7543 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7547 fn test_bump_penalty_txn_on_revoked_commitment() {
7548 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7549 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7551 let chanmon_cfgs = create_chanmon_cfgs(2);
7552 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7553 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7554 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7556 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7557 let logger = test_utils::TestLogger::new();
7560 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7561 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7562 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();
7563 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7565 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7566 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7567 assert_eq!(revoked_txn[0].output.len(), 4);
7568 assert_eq!(revoked_txn[0].input.len(), 1);
7569 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7570 let revoked_txid = revoked_txn[0].txid();
7572 let mut penalty_sum = 0;
7573 for outp in revoked_txn[0].output.iter() {
7574 if outp.script_pubkey.is_v0_p2wsh() {
7575 penalty_sum += outp.value;
7579 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7580 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7582 // Actually revoke tx by claiming a HTLC
7583 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7584 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7585 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7586 check_added_monitors!(nodes[1], 1);
7588 // One or more justice tx should have been broadcast, check it
7592 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7593 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7594 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7595 assert_eq!(node_txn[0].output.len(), 1);
7596 check_spends!(node_txn[0], revoked_txn[0]);
7597 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7598 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7599 penalty_1 = node_txn[0].txid();
7603 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7604 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7605 let mut penalty_2 = penalty_1;
7606 let mut feerate_2 = 0;
7608 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7609 assert_eq!(node_txn.len(), 1);
7610 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7611 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7612 assert_eq!(node_txn[0].output.len(), 1);
7613 check_spends!(node_txn[0], revoked_txn[0]);
7614 penalty_2 = node_txn[0].txid();
7615 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7616 assert_ne!(penalty_2, penalty_1);
7617 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7618 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7619 // Verify 25% bump heuristic
7620 assert!(feerate_2 * 100 >= feerate_1 * 125);
7624 assert_ne!(feerate_2, 0);
7626 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7627 connect_blocks(&nodes[1], 3, 118, true, header);
7629 let mut feerate_3 = 0;
7631 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7632 assert_eq!(node_txn.len(), 1);
7633 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7634 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7635 assert_eq!(node_txn[0].output.len(), 1);
7636 check_spends!(node_txn[0], revoked_txn[0]);
7637 penalty_3 = node_txn[0].txid();
7638 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7639 assert_ne!(penalty_3, penalty_2);
7640 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7641 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7642 // Verify 25% bump heuristic
7643 assert!(feerate_3 * 100 >= feerate_2 * 125);
7647 assert_ne!(feerate_3, 0);
7649 nodes[1].node.get_and_clear_pending_events();
7650 nodes[1].node.get_and_clear_pending_msg_events();
7654 fn test_bump_penalty_txn_on_revoked_htlcs() {
7655 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7656 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7658 let mut chanmon_cfgs = create_chanmon_cfgs(2);
7659 chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7660 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7661 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7662 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7664 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7665 // Lock HTLC in both directions
7666 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7667 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7669 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7670 assert_eq!(revoked_local_txn[0].input.len(), 1);
7671 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7673 // Revoke local commitment tx
7674 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7676 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7677 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7678 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7679 check_closed_broadcast!(nodes[1], false);
7680 check_added_monitors!(nodes[1], 1);
7682 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7683 assert_eq!(revoked_htlc_txn.len(), 4);
7684 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7685 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7686 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7687 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7688 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7689 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7690 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7691 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7692 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7693 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7694 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7695 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7696 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7697 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7700 // Broadcast set of revoked txn on A
7701 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7702 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7703 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7704 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7705 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7710 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7711 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7712 // Verify claim tx are spending revoked HTLC txn
7714 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7715 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7716 // which are included in the same block (they are broadcasted because we scan the
7717 // transactions linearly and generate claims as we go, they likely should be removed in the
7719 assert_eq!(node_txn[0].input.len(), 1);
7720 check_spends!(node_txn[0], revoked_local_txn[0]);
7721 assert_eq!(node_txn[1].input.len(), 1);
7722 check_spends!(node_txn[1], revoked_local_txn[0]);
7723 assert_eq!(node_txn[2].input.len(), 1);
7724 check_spends!(node_txn[2], revoked_local_txn[0]);
7726 // Each of the three justice transactions claim a separate (single) output of the three
7727 // available, which we check here:
7728 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7729 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7730 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7732 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7733 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7735 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7736 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7737 // a remote commitment tx has already been confirmed).
7738 check_spends!(node_txn[3], chan.3);
7740 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7741 // output, checked above).
7742 assert_eq!(node_txn[4].input.len(), 2);
7743 assert_eq!(node_txn[4].output.len(), 1);
7744 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7746 first = node_txn[4].txid();
7747 // Store both feerates for later comparison
7748 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7749 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7750 penalty_txn = vec![node_txn[2].clone()];
7754 // Connect one more block to see if bumped penalty are issued for HTLC txn
7755 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7756 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7757 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7758 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7760 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7761 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7763 check_spends!(node_txn[0], revoked_local_txn[0]);
7764 check_spends!(node_txn[1], revoked_local_txn[0]);
7765 // Note that these are both bogus - they spend outputs already claimed in block 129:
7766 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7767 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7769 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7770 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7776 // Few more blocks to confirm penalty txn
7777 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7778 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7779 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7781 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7782 assert_eq!(node_txn.len(), 1);
7784 assert_eq!(node_txn[0].input.len(), 2);
7785 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7786 // Verify bumped tx is different and 25% bump heuristic
7787 assert_ne!(first, node_txn[0].txid());
7788 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7789 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7790 assert!(feerate_2 * 100 > feerate_1 * 125);
7791 let txn = vec![node_txn[0].clone()];
7795 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7796 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7797 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7798 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7800 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7801 // We verify than no new transaction has been broadcast because previously
7802 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7803 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7804 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7805 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7806 // up bumped justice generation.
7807 assert_eq!(node_txn.len(), 0);
7810 check_closed_broadcast!(nodes[0], false);
7811 check_added_monitors!(nodes[0], 1);
7815 fn test_bump_penalty_txn_on_remote_commitment() {
7816 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7817 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7820 // Provide preimage for one
7821 // Check aggregation
7823 let chanmon_cfgs = create_chanmon_cfgs(2);
7824 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7825 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7826 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7828 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7829 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7830 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7832 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7833 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7834 assert_eq!(remote_txn[0].output.len(), 4);
7835 assert_eq!(remote_txn[0].input.len(), 1);
7836 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7838 // Claim a HTLC without revocation (provide B monitor with preimage)
7839 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7840 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7841 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7842 check_added_monitors!(nodes[1], 2);
7844 // One or more claim tx should have been broadcast, check it
7847 let feerate_timeout;
7848 let feerate_preimage;
7850 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7851 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7852 assert_eq!(node_txn[0].input.len(), 1);
7853 assert_eq!(node_txn[1].input.len(), 1);
7854 check_spends!(node_txn[0], remote_txn[0]);
7855 check_spends!(node_txn[1], remote_txn[0]);
7856 check_spends!(node_txn[2], chan.3);
7857 check_spends!(node_txn[3], node_txn[2]);
7858 check_spends!(node_txn[4], node_txn[2]);
7859 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7860 timeout = node_txn[0].txid();
7861 let index = node_txn[0].input[0].previous_output.vout;
7862 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7863 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7865 preimage = node_txn[1].txid();
7866 let index = node_txn[1].input[0].previous_output.vout;
7867 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7868 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7870 timeout = node_txn[1].txid();
7871 let index = node_txn[1].input[0].previous_output.vout;
7872 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7873 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7875 preimage = node_txn[0].txid();
7876 let index = node_txn[0].input[0].previous_output.vout;
7877 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7878 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7882 assert_ne!(feerate_timeout, 0);
7883 assert_ne!(feerate_preimage, 0);
7885 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7886 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
7888 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7889 assert_eq!(node_txn.len(), 2);
7890 assert_eq!(node_txn[0].input.len(), 1);
7891 assert_eq!(node_txn[1].input.len(), 1);
7892 check_spends!(node_txn[0], remote_txn[0]);
7893 check_spends!(node_txn[1], remote_txn[0]);
7894 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7895 let index = node_txn[0].input[0].previous_output.vout;
7896 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7897 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7898 assert!(new_feerate * 100 > feerate_timeout * 125);
7899 assert_ne!(timeout, node_txn[0].txid());
7901 let index = node_txn[1].input[0].previous_output.vout;
7902 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7903 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7904 assert!(new_feerate * 100 > feerate_preimage * 125);
7905 assert_ne!(preimage, node_txn[1].txid());
7907 let index = node_txn[1].input[0].previous_output.vout;
7908 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7909 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7910 assert!(new_feerate * 100 > feerate_timeout * 125);
7911 assert_ne!(timeout, node_txn[1].txid());
7913 let index = node_txn[0].input[0].previous_output.vout;
7914 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7915 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7916 assert!(new_feerate * 100 > feerate_preimage * 125);
7917 assert_ne!(preimage, node_txn[0].txid());
7922 nodes[1].node.get_and_clear_pending_events();
7923 nodes[1].node.get_and_clear_pending_msg_events();
7927 fn test_set_outpoints_partial_claiming() {
7928 // - remote party claim tx, new bump tx
7929 // - disconnect remote claiming tx, new bump
7930 // - disconnect tx, see no tx anymore
7931 let chanmon_cfgs = create_chanmon_cfgs(2);
7932 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7933 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7934 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7936 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7937 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7938 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7940 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7941 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7942 assert_eq!(remote_txn.len(), 3);
7943 assert_eq!(remote_txn[0].output.len(), 4);
7944 assert_eq!(remote_txn[0].input.len(), 1);
7945 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7946 check_spends!(remote_txn[1], remote_txn[0]);
7947 check_spends!(remote_txn[2], remote_txn[0]);
7949 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7950 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
7951 // Provide node A with both preimage
7952 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7953 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7954 check_added_monitors!(nodes[0], 2);
7955 nodes[0].node.get_and_clear_pending_events();
7956 nodes[0].node.get_and_clear_pending_msg_events();
7958 // Connect blocks on node A commitment transaction
7959 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7960 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7961 check_closed_broadcast!(nodes[0], false);
7962 check_added_monitors!(nodes[0], 1);
7963 // Verify node A broadcast tx claiming both HTLCs
7965 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7966 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7967 assert_eq!(node_txn.len(), 4);
7968 check_spends!(node_txn[0], remote_txn[0]);
7969 check_spends!(node_txn[1], chan.3);
7970 check_spends!(node_txn[2], node_txn[1]);
7971 check_spends!(node_txn[3], node_txn[1]);
7972 assert_eq!(node_txn[0].input.len(), 2);
7976 // Connect blocks on node B
7977 connect_blocks(&nodes[1], 135, 0, false, Default::default());
7978 check_closed_broadcast!(nodes[1], false);
7979 check_added_monitors!(nodes[1], 1);
7980 // Verify node B broadcast 2 HTLC-timeout txn
7981 let partial_claim_tx = {
7982 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7983 assert_eq!(node_txn.len(), 3);
7984 check_spends!(node_txn[1], node_txn[0]);
7985 check_spends!(node_txn[2], node_txn[0]);
7986 assert_eq!(node_txn[1].input.len(), 1);
7987 assert_eq!(node_txn[2].input.len(), 1);
7991 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7992 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7993 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7995 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7996 assert_eq!(node_txn.len(), 1);
7997 check_spends!(node_txn[0], remote_txn[0]);
7998 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8001 nodes[0].node.get_and_clear_pending_msg_events();
8003 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8004 disconnect_block(&nodes[0], &header, 102);
8006 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8007 assert_eq!(node_txn.len(), 1);
8008 check_spends!(node_txn[0], remote_txn[0]);
8009 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8013 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8014 disconnect_block(&nodes[0], &header, 101);
8015 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8017 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8018 assert_eq!(node_txn.len(), 0);
8024 fn test_counterparty_raa_skip_no_crash() {
8025 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8026 // commitment transaction, we would have happily carried on and provided them the next
8027 // commitment transaction based on one RAA forward. This would probably eventually have led to
8028 // channel closure, but it would not have resulted in funds loss. Still, our
8029 // EnforcingSigner would have paniced as it doesn't like jumps into the future. Here, we
8030 // check simply that the channel is closed in response to such an RAA, but don't check whether
8031 // we decide to punish our counterparty for revoking their funds (as we don't currently
8033 let chanmon_cfgs = create_chanmon_cfgs(2);
8034 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8035 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8036 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8037 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8039 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8040 let keys = &guard.by_id.get_mut(&channel_id).unwrap().get_signer();
8041 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8042 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8043 // Must revoke without gaps
8044 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8045 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8046 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8048 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8049 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8050 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8051 check_added_monitors!(nodes[1], 1);
8055 fn test_bump_txn_sanitize_tracking_maps() {
8056 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8057 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8059 let chanmon_cfgs = create_chanmon_cfgs(2);
8060 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8061 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8062 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8064 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8065 // Lock HTLC in both directions
8066 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8067 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8069 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8070 assert_eq!(revoked_local_txn[0].input.len(), 1);
8071 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8073 // Revoke local commitment tx
8074 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8076 // Broadcast set of revoked txn on A
8077 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8078 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8080 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8081 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8082 check_closed_broadcast!(nodes[0], false);
8083 check_added_monitors!(nodes[0], 1);
8085 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8086 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8087 check_spends!(node_txn[0], revoked_local_txn[0]);
8088 check_spends!(node_txn[1], revoked_local_txn[0]);
8089 check_spends!(node_txn[2], revoked_local_txn[0]);
8090 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8094 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8095 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8096 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8098 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8099 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8100 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8101 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8107 fn test_override_channel_config() {
8108 let chanmon_cfgs = create_chanmon_cfgs(2);
8109 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8110 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8111 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8113 // Node0 initiates a channel to node1 using the override config.
8114 let mut override_config = UserConfig::default();
8115 override_config.own_channel_config.our_to_self_delay = 200;
8117 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8119 // Assert the channel created by node0 is using the override config.
8120 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8121 assert_eq!(res.channel_flags, 0);
8122 assert_eq!(res.to_self_delay, 200);
8126 fn test_override_0msat_htlc_minimum() {
8127 let mut zero_config = UserConfig::default();
8128 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8129 let chanmon_cfgs = create_chanmon_cfgs(2);
8130 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8132 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8134 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8135 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8136 assert_eq!(res.htlc_minimum_msat, 1);
8138 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8139 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8140 assert_eq!(res.htlc_minimum_msat, 1);
8144 fn test_simple_payment_secret() {
8145 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8146 // features, however.
8147 let chanmon_cfgs = create_chanmon_cfgs(3);
8148 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8149 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8150 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8152 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8153 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8154 let logger = test_utils::TestLogger::new();
8156 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8157 let payment_secret = PaymentSecret([0xdb; 32]);
8158 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8159 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();
8160 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8161 // Claiming with all the correct values but the wrong secret should result in nothing...
8162 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8163 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8164 // ...but with the right secret we should be able to claim all the way back
8165 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8169 fn test_simple_mpp() {
8170 // Simple test of sending a multi-path payment.
8171 let chanmon_cfgs = create_chanmon_cfgs(4);
8172 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8173 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8174 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8176 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8177 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8178 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8179 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8180 let logger = test_utils::TestLogger::new();
8182 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8183 let payment_secret = PaymentSecret([0xdb; 32]);
8184 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8185 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();
8186 let path = route.paths[0].clone();
8187 route.paths.push(path);
8188 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8189 route.paths[0][0].short_channel_id = chan_1_id;
8190 route.paths[0][1].short_channel_id = chan_3_id;
8191 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8192 route.paths[1][0].short_channel_id = chan_2_id;
8193 route.paths[1][1].short_channel_id = chan_4_id;
8194 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8195 // Claiming with all the correct values but the wrong secret should result in nothing...
8196 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8197 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8198 // ...but with the right secret we should be able to claim all the way back
8199 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8203 fn test_update_err_monitor_lockdown() {
8204 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8205 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8206 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8208 // This scenario may happen in a watchtower setup, where watchtower process a block height
8209 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8210 // commitment at same time.
8212 let chanmon_cfgs = create_chanmon_cfgs(2);
8213 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8214 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8215 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8217 // Create some initial channel
8218 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8219 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8221 // Rebalance the network to generate htlc in the two directions
8222 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8224 // Route a HTLC from node 0 to node 1 (but don't settle)
8225 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8227 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8228 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8229 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8230 let persister = test_utils::TestPersister::new();
8232 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8233 let monitor = monitors.get(&outpoint).unwrap();
8234 let mut w = test_utils::TestVecWriter(Vec::new());
8235 monitor.write(&mut w).unwrap();
8236 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8237 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8238 assert!(new_monitor == *monitor);
8239 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);
8240 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8243 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8244 watchtower.chain_monitor.block_connected(&header, &[], 200);
8246 // Try to update ChannelMonitor
8247 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8248 check_added_monitors!(nodes[1], 1);
8249 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8250 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8251 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8252 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8253 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8254 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8255 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8256 } else { assert!(false); }
8257 } else { assert!(false); };
8258 // Our local monitor is in-sync and hasn't processed yet timeout
8259 check_added_monitors!(nodes[0], 1);
8260 let events = nodes[0].node.get_and_clear_pending_events();
8261 assert_eq!(events.len(), 1);
8265 fn test_concurrent_monitor_claim() {
8266 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8267 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8268 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8269 // state N+1 confirms. Alice claims output from state N+1.
8271 let chanmon_cfgs = create_chanmon_cfgs(2);
8272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8274 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8276 // Create some initial channel
8277 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8278 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8280 // Rebalance the network to generate htlc in the two directions
8281 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8283 // Route a HTLC from node 0 to node 1 (but don't settle)
8284 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8286 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8287 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8288 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8289 let persister = test_utils::TestPersister::new();
8290 let watchtower_alice = {
8291 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8292 let monitor = monitors.get(&outpoint).unwrap();
8293 let mut w = test_utils::TestVecWriter(Vec::new());
8294 monitor.write(&mut w).unwrap();
8295 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8296 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8297 assert!(new_monitor == *monitor);
8298 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);
8299 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8302 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8303 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8305 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8307 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8308 assert_eq!(txn.len(), 2);
8312 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8313 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8314 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8315 let persister = test_utils::TestPersister::new();
8316 let watchtower_bob = {
8317 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8318 let monitor = monitors.get(&outpoint).unwrap();
8319 let mut w = test_utils::TestVecWriter(Vec::new());
8320 monitor.write(&mut w).unwrap();
8321 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(
8322 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8323 assert!(new_monitor == *monitor);
8324 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);
8325 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8328 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8329 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8331 // Route another payment to generate another update with still previous HTLC pending
8332 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8334 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8335 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();
8336 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8338 check_added_monitors!(nodes[1], 1);
8340 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8341 assert_eq!(updates.update_add_htlcs.len(), 1);
8342 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8343 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8344 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8345 // Watchtower Alice should already have seen the block and reject the update
8346 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8347 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8348 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8349 } else { assert!(false); }
8350 } else { assert!(false); };
8351 // Our local monitor is in-sync and hasn't processed yet timeout
8352 check_added_monitors!(nodes[0], 1);
8354 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8355 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8357 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8360 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8361 assert_eq!(txn.len(), 2);
8362 bob_state_y = txn[0].clone();
8366 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8367 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8369 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8370 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8371 // the onchain detection of the HTLC output
8372 assert_eq!(htlc_txn.len(), 2);
8373 check_spends!(htlc_txn[0], bob_state_y);
8374 check_spends!(htlc_txn[1], bob_state_y);
8379 fn test_pre_lockin_no_chan_closed_update() {
8380 // Test that if a peer closes a channel in response to a funding_created message we don't
8381 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8384 // Doing so would imply a channel monitor update before the initial channel monitor
8385 // registration, violating our API guarantees.
8387 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8388 // then opening a second channel with the same funding output as the first (which is not
8389 // rejected because the first channel does not exist in the ChannelManager) and closing it
8390 // before receiving funding_signed.
8391 let chanmon_cfgs = create_chanmon_cfgs(2);
8392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8394 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8396 // Create an initial channel
8397 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8398 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8399 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8400 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8401 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8403 // Move the first channel through the funding flow...
8404 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8406 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8407 check_added_monitors!(nodes[0], 0);
8409 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8410 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8411 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8412 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8416 fn test_htlc_no_detection() {
8417 // This test is a mutation to underscore the detection logic bug we had
8418 // before #653. HTLC value routed is above the remaining balance, thus
8419 // inverting HTLC and `to_remote` output. HTLC will come second and
8420 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8421 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8422 // outputs order detection for correct spending children filtring.
8424 let chanmon_cfgs = create_chanmon_cfgs(2);
8425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8427 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8429 // Create some initial channels
8430 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8432 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8433 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8434 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8435 assert_eq!(local_txn[0].input.len(), 1);
8436 assert_eq!(local_txn[0].output.len(), 3);
8437 check_spends!(local_txn[0], chan_1.3);
8439 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8440 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8441 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8442 // We deliberately connect the local tx twice as this should provoke a failure calling
8443 // this test before #653 fix.
8444 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8445 check_closed_broadcast!(nodes[0], false);
8446 check_added_monitors!(nodes[0], 1);
8448 let htlc_timeout = {
8449 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8450 assert_eq!(node_txn[0].input.len(), 1);
8451 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8452 check_spends!(node_txn[0], local_txn[0]);
8456 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8457 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8458 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8459 expect_payment_failed!(nodes[0], our_payment_hash, true);
8462 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8463 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8464 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8465 // Carol, Alice would be the upstream node, and Carol the downstream.)
8467 // Steps of the test:
8468 // 1) Alice sends a HTLC to Carol through Bob.
8469 // 2) Carol doesn't settle the HTLC.
8470 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8471 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8472 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8473 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8474 // 5) Carol release the preimage to Bob off-chain.
8475 // 6) Bob claims the offered output on the broadcasted commitment.
8476 let chanmon_cfgs = create_chanmon_cfgs(3);
8477 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8478 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8479 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8481 // Create some initial channels
8482 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8483 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8485 // Steps (1) and (2):
8486 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8487 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8489 // Check that Alice's commitment transaction now contains an output for this HTLC.
8490 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8491 check_spends!(alice_txn[0], chan_ab.3);
8492 assert_eq!(alice_txn[0].output.len(), 2);
8493 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8494 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8495 assert_eq!(alice_txn.len(), 2);
8497 // Steps (3) and (4):
8498 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8499 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8500 let mut force_closing_node = 0; // Alice force-closes
8501 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8502 nodes[force_closing_node].node.force_close_channel(&chan_ab.2).unwrap();
8503 check_closed_broadcast!(nodes[force_closing_node], false);
8504 check_added_monitors!(nodes[force_closing_node], 1);
8505 if go_onchain_before_fulfill {
8506 let txn_to_broadcast = match broadcast_alice {
8507 true => alice_txn.clone(),
8508 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8510 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8511 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8512 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8513 if broadcast_alice {
8514 check_closed_broadcast!(nodes[1], false);
8515 check_added_monitors!(nodes[1], 1);
8517 assert_eq!(bob_txn.len(), 1);
8518 check_spends!(bob_txn[0], chan_ab.3);
8522 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8523 // process of removing the HTLC from their commitment transactions.
8524 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8525 check_added_monitors!(nodes[2], 1);
8526 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8527 assert!(carol_updates.update_add_htlcs.is_empty());
8528 assert!(carol_updates.update_fail_htlcs.is_empty());
8529 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8530 assert!(carol_updates.update_fee.is_none());
8531 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8533 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8534 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8535 if !go_onchain_before_fulfill && broadcast_alice {
8536 let events = nodes[1].node.get_and_clear_pending_msg_events();
8537 assert_eq!(events.len(), 1);
8539 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8540 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8542 _ => panic!("Unexpected event"),
8545 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8546 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8547 // Carol<->Bob's updated commitment transaction info.
8548 check_added_monitors!(nodes[1], 2);
8550 let events = nodes[1].node.get_and_clear_pending_msg_events();
8551 assert_eq!(events.len(), 2);
8552 let bob_revocation = match events[0] {
8553 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8554 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8557 _ => panic!("Unexpected event"),
8559 let bob_updates = match events[1] {
8560 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8561 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8564 _ => panic!("Unexpected event"),
8567 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8568 check_added_monitors!(nodes[2], 1);
8569 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8570 check_added_monitors!(nodes[2], 1);
8572 let events = nodes[2].node.get_and_clear_pending_msg_events();
8573 assert_eq!(events.len(), 1);
8574 let carol_revocation = match events[0] {
8575 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8576 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8579 _ => panic!("Unexpected event"),
8581 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8582 check_added_monitors!(nodes[1], 1);
8584 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8585 // here's where we put said channel's commitment tx on-chain.
8586 let mut txn_to_broadcast = alice_txn.clone();
8587 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8588 if !go_onchain_before_fulfill {
8589 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8590 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8591 // If Bob was the one to force-close, he will have already passed these checks earlier.
8592 if broadcast_alice {
8593 check_closed_broadcast!(nodes[1], false);
8594 check_added_monitors!(nodes[1], 1);
8596 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8597 if broadcast_alice {
8598 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8599 // new block being connected. The ChannelManager being notified triggers a monitor update,
8600 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8601 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8603 assert_eq!(bob_txn.len(), 3);
8604 check_spends!(bob_txn[1], chan_ab.3);
8606 assert_eq!(bob_txn.len(), 2);
8607 check_spends!(bob_txn[0], chan_ab.3);
8612 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8613 // broadcasted commitment transaction.
8615 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8616 if go_onchain_before_fulfill {
8617 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8618 assert_eq!(bob_txn.len(), 2);
8620 let script_weight = match broadcast_alice {
8621 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8622 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8624 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8625 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8626 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8627 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8628 if broadcast_alice && !go_onchain_before_fulfill {
8629 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8630 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8632 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8633 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8639 fn test_onchain_htlc_settlement_after_close() {
8640 do_test_onchain_htlc_settlement_after_close(true, true);
8641 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8642 do_test_onchain_htlc_settlement_after_close(true, false);
8643 do_test_onchain_htlc_settlement_after_close(false, false);
8647 fn test_duplicate_chan_id() {
8648 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8649 // already open we reject it and keep the old channel.
8651 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8652 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8653 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8654 // updating logic for the existing channel.
8655 let chanmon_cfgs = create_chanmon_cfgs(2);
8656 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8657 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8658 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8660 // Create an initial channel
8661 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8662 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8663 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8664 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()));
8666 // Try to create a second channel with the same temporary_channel_id as the first and check
8667 // that it is rejected.
8668 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8670 let events = nodes[1].node.get_and_clear_pending_msg_events();
8671 assert_eq!(events.len(), 1);
8673 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8674 // Technically, at this point, nodes[1] would be justified in thinking both the
8675 // first (valid) and second (invalid) channels are closed, given they both have
8676 // the same non-temporary channel_id. However, currently we do not, so we just
8677 // move forward with it.
8678 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8679 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8681 _ => panic!("Unexpected event"),
8685 // Move the first channel through the funding flow...
8686 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8688 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8689 check_added_monitors!(nodes[0], 0);
8691 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8692 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8694 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8695 assert_eq!(added_monitors.len(), 1);
8696 assert_eq!(added_monitors[0].0, funding_output);
8697 added_monitors.clear();
8699 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8701 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8702 let channel_id = funding_outpoint.to_channel_id();
8704 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8707 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8708 // Technically this is allowed by the spec, but we don't support it and there's little reason
8709 // to. Still, it shouldn't cause any other issues.
8710 open_chan_msg.temporary_channel_id = channel_id;
8711 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8713 let events = nodes[1].node.get_and_clear_pending_msg_events();
8714 assert_eq!(events.len(), 1);
8716 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8717 // Technically, at this point, nodes[1] would be justified in thinking both
8718 // channels are closed, but currently we do not, so we just move forward with it.
8719 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8720 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8722 _ => panic!("Unexpected event"),
8726 // Now try to create a second channel which has a duplicate funding output.
8727 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8728 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8729 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8730 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()));
8731 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8733 let funding_created = {
8734 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8735 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8736 let logger = test_utils::TestLogger::new();
8737 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8739 check_added_monitors!(nodes[0], 0);
8740 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8741 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8742 // still needs to be cleared here.
8743 check_added_monitors!(nodes[1], 1);
8745 // ...still, nodes[1] will reject the duplicate channel.
8747 let events = nodes[1].node.get_and_clear_pending_msg_events();
8748 assert_eq!(events.len(), 1);
8750 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8751 // Technically, at this point, nodes[1] would be justified in thinking both
8752 // channels are closed, but currently we do not, so we just move forward with it.
8753 assert_eq!(msg.channel_id, channel_id);
8754 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8756 _ => panic!("Unexpected event"),
8760 // finally, finish creating the original channel and send a payment over it to make sure
8761 // everything is functional.
8762 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8764 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8765 assert_eq!(added_monitors.len(), 1);
8766 assert_eq!(added_monitors[0].0, funding_output);
8767 added_monitors.clear();
8770 let events_4 = nodes[0].node.get_and_clear_pending_events();
8771 assert_eq!(events_4.len(), 1);
8773 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8774 assert_eq!(user_channel_id, 42);
8775 assert_eq!(*funding_txo, funding_output);
8777 _ => panic!("Unexpected event"),
8780 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8781 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8782 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8783 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);
8787 fn test_error_chans_closed() {
8788 // Test that we properly handle error messages, closing appropriate channels.
8790 // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
8791 // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
8792 // we can test various edge cases around it to ensure we don't regress.
8793 let chanmon_cfgs = create_chanmon_cfgs(3);
8794 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8795 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8796 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8798 // Create some initial channels
8799 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8800 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8801 let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8803 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8804 assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
8805 assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
8807 // Closing a channel from a different peer has no effect
8808 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
8809 assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
8811 // Closing one channel doesn't impact others
8812 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
8813 check_added_monitors!(nodes[0], 1);
8814 check_closed_broadcast!(nodes[0], false);
8815 assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
8816 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);
8817 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);
8819 // A null channel ID should close all channels
8820 let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8821 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: [0; 32], data: "ERR".to_owned() });
8822 check_added_monitors!(nodes[0], 2);
8823 let events = nodes[0].node.get_and_clear_pending_msg_events();
8824 assert_eq!(events.len(), 2);
8826 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8827 assert_eq!(msg.contents.flags & 2, 2);
8829 _ => panic!("Unexpected event"),
8832 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
8833 assert_eq!(msg.contents.flags & 2, 2);
8835 _ => panic!("Unexpected event"),
8837 // Note that at this point users of a standard PeerHandler will end up calling
8838 // peer_disconnected with no_connection_possible set to false, duplicating the
8839 // close-all-channels logic. That's OK, we don't want to end up not force-closing channels for
8840 // users with their own peer handling logic. We duplicate the call here, however.
8841 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8842 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
8844 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), true);
8845 assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
8846 assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);