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::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
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::EnforcingChannelKeys;
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, Readable};
32 use util::config::UserConfig;
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hashes::HashEngine;
36 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
37 use bitcoin::util::bip143;
38 use bitcoin::util::address::Address;
39 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
47 use bitcoin::hashes::sha256::Hash as Sha256;
48 use bitcoin::hashes::Hash;
50 use bitcoin::secp256k1::{Secp256k1, Message};
51 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
55 use std::collections::{BTreeSet, HashMap, HashSet};
56 use std::default::Default;
57 use std::sync::{Arc, Mutex};
58 use std::sync::atomic::Ordering;
61 use ln::functional_test_utils::*;
62 use ln::chan_utils::PreCalculatedTxCreationKeys;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 let chanmon_cfgs = create_chanmon_cfgs(2);
68 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
70 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72 // Instantiate channel parameters where we push the maximum msats given our
74 let channel_value_sat = 31337; // same as funding satoshis
75 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78 // Have node0 initiate a channel to node1 with aforementioned parameters
79 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81 // Extract the channel open message from node0 to node1
82 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84 // Test helper that asserts we get the correct error string given a mutator
85 // that supposedly makes the channel open message insane
86 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89 assert_eq!(msg_events.len(), 1);
90 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93 &ErrorAction::SendErrorMessage { .. } => {
94 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96 _ => panic!("unexpected event!"),
98 } else { assert!(false); }
101 use ln::channel::MAX_FUNDING_SATOSHIS;
102 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104 // Test all mutations that would make the channel open message insane
105 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 });
107 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109 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 });
111 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113 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 });
115 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 });
117 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 });
119 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 fn test_async_inbound_update_fee() {
126 let chanmon_cfgs = create_chanmon_cfgs(2);
127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
129 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
130 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
131 let logger = test_utils::TestLogger::new();
132 let channel_id = chan.2;
135 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
139 // send (1) commitment_signed -.
140 // <- update_add_htlc/commitment_signed
141 // send (2) RAA (awaiting remote revoke) -.
142 // (1) commitment_signed is delivered ->
143 // .- send (3) RAA (awaiting remote revoke)
144 // (2) RAA is delivered ->
145 // .- send (4) commitment_signed
146 // <- (3) RAA is delivered
147 // send (5) commitment_signed -.
148 // <- (4) commitment_signed is delivered
150 // (5) commitment_signed is delivered ->
152 // (6) RAA is delivered ->
154 // First nodes[0] generates an update_fee
155 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
156 check_added_monitors!(nodes[0], 1);
158 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events_0.len(), 1);
160 let (update_msg, commitment_signed) = match events_0[0] { // (1)
161 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162 (update_fee.as_ref(), commitment_signed)
164 _ => panic!("Unexpected event"),
167 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
171 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
172 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();
173 check_added_monitors!(nodes[1], 1);
175 let payment_event = {
176 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
177 assert_eq!(events_1.len(), 1);
178 SendEvent::from_event(events_1.remove(0))
180 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
181 assert_eq!(payment_event.msgs.len(), 1);
183 // ...now when the messages get delivered everyone should be happy
184 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
185 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
186 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
187 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
188 check_added_monitors!(nodes[0], 1);
190 // deliver(1), generate (3):
191 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
192 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
193 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
194 check_added_monitors!(nodes[1], 1);
196 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
197 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
198 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
199 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
202 assert!(bs_update.update_fee.is_none()); // (4)
203 check_added_monitors!(nodes[1], 1);
205 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
206 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
207 assert!(as_update.update_add_htlcs.is_empty()); // (5)
208 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
211 assert!(as_update.update_fee.is_none()); // (5)
212 check_added_monitors!(nodes[0], 1);
214 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
215 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
216 // only (6) so get_event_msg's assert(len == 1) passes
217 check_added_monitors!(nodes[0], 1);
219 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
220 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
221 check_added_monitors!(nodes[1], 1);
223 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
224 check_added_monitors!(nodes[0], 1);
226 let events_2 = nodes[0].node.get_and_clear_pending_events();
227 assert_eq!(events_2.len(), 1);
229 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
230 _ => panic!("Unexpected event"),
233 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
234 check_added_monitors!(nodes[1], 1);
238 fn test_update_fee_unordered_raa() {
239 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
240 // crash in an earlier version of the update_fee patch)
241 let chanmon_cfgs = create_chanmon_cfgs(2);
242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
244 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
245 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
246 let channel_id = chan.2;
247 let logger = test_utils::TestLogger::new();
250 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
252 // First nodes[0] generates an update_fee
253 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
254 check_added_monitors!(nodes[0], 1);
256 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257 assert_eq!(events_0.len(), 1);
258 let update_msg = match events_0[0] { // (1)
259 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
262 _ => panic!("Unexpected event"),
265 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
269 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
270 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();
271 check_added_monitors!(nodes[1], 1);
273 let payment_event = {
274 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275 assert_eq!(events_1.len(), 1);
276 SendEvent::from_event(events_1.remove(0))
278 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279 assert_eq!(payment_event.msgs.len(), 1);
281 // ...now when the messages get delivered everyone should be happy
282 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286 check_added_monitors!(nodes[0], 1);
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289 check_added_monitors!(nodes[1], 1);
291 // We can't continue, sadly, because our (1) now has a bogus signature
295 fn test_multi_flight_update_fee() {
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
301 let channel_id = chan.2;
304 // update_fee/commitment_signed ->
305 // .- send (1) RAA and (2) commitment_signed
306 // update_fee (never committed) ->
308 // We have to manually generate the above update_fee, it is allowed by the protocol but we
309 // don't track which updates correspond to which revoke_and_ack responses so we're in
310 // AwaitingRAA mode and will not generate the update_fee yet.
311 // <- (1) RAA delivered
312 // (3) is generated and send (4) CS -.
313 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
314 // know the per_commitment_point to use for it.
315 // <- (2) commitment_signed delivered
317 // B should send no response here
318 // (4) commitment_signed delivered ->
319 // <- RAA/commitment_signed delivered
322 // First nodes[0] generates an update_fee
323 let initial_feerate = get_feerate!(nodes[0], channel_id);
324 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
325 check_added_monitors!(nodes[0], 1);
327 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
328 assert_eq!(events_0.len(), 1);
329 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
330 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
331 (update_fee.as_ref().unwrap(), commitment_signed)
333 _ => panic!("Unexpected event"),
336 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
337 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
338 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
339 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
340 check_added_monitors!(nodes[1], 1);
342 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
344 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
345 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
346 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
348 // Create the (3) update_fee message that nodes[0] will generate before it does...
349 let mut update_msg_2 = msgs::UpdateFee {
350 channel_id: update_msg_1.channel_id.clone(),
351 feerate_per_kw: (initial_feerate + 30) as u32,
354 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
356 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
358 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
360 // Deliver (1), generating (3) and (4)
361 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
362 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
363 check_added_monitors!(nodes[0], 1);
364 assert!(as_second_update.update_add_htlcs.is_empty());
365 assert!(as_second_update.update_fulfill_htlcs.is_empty());
366 assert!(as_second_update.update_fail_htlcs.is_empty());
367 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
368 // Check that the update_fee newly generated matches what we delivered:
369 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
370 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
372 // Deliver (2) commitment_signed
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 check_added_monitors!(nodes[0], 1);
376 // No commitment_signed so get_event_msg's assert(len == 1) passes
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
379 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
380 check_added_monitors!(nodes[1], 1);
383 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
384 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
385 check_added_monitors!(nodes[1], 1);
387 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
388 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
389 check_added_monitors!(nodes[0], 1);
391 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
392 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
393 // No commitment_signed so get_event_msg's assert(len == 1) passes
394 check_added_monitors!(nodes[0], 1);
396 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
397 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
398 check_added_monitors!(nodes[1], 1);
402 fn test_1_conf_open() {
403 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
404 // tests that we properly send one in that case.
405 let mut alice_config = UserConfig::default();
406 alice_config.own_channel_config.minimum_depth = 1;
407 alice_config.channel_options.announced_channel = true;
408 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
409 let mut bob_config = UserConfig::default();
410 bob_config.own_channel_config.minimum_depth = 1;
411 bob_config.channel_options.announced_channel = true;
412 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
413 let chanmon_cfgs = create_chanmon_cfgs(2);
414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
416 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
418 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
420 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
423 connect_block(&nodes[1], &block, 1);
424 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()));
426 connect_block(&nodes[0], &block, 1);
427 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
428 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
431 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
432 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
433 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
437 fn do_test_sanity_on_in_flight_opens(steps: u8) {
438 // Previously, we had issues deserializing channels when we hadn't connected the first block
439 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
440 // serialization round-trips and simply do steps towards opening a channel and then drop the
443 let chanmon_cfgs = create_chanmon_cfgs(2);
444 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
445 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
446 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
448 if steps & 0b1000_0000 != 0{
450 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
453 connect_block(&nodes[0], &block, 1);
454 connect_block(&nodes[1], &block, 1);
457 if steps & 0x0f == 0 { return; }
458 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
459 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
461 if steps & 0x0f == 1 { return; }
462 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
463 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
465 if steps & 0x0f == 2 { return; }
466 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
468 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
470 if steps & 0x0f == 3 { return; }
471 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
472 check_added_monitors!(nodes[0], 0);
473 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
475 if steps & 0x0f == 4 { return; }
476 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
478 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
479 assert_eq!(added_monitors.len(), 1);
480 assert_eq!(added_monitors[0].0, funding_output);
481 added_monitors.clear();
483 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
485 if steps & 0x0f == 5 { return; }
486 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
488 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
489 assert_eq!(added_monitors.len(), 1);
490 assert_eq!(added_monitors[0].0, funding_output);
491 added_monitors.clear();
494 let events_4 = nodes[0].node.get_and_clear_pending_events();
495 assert_eq!(events_4.len(), 1);
497 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
498 assert_eq!(user_channel_id, 42);
499 assert_eq!(*funding_txo, funding_output);
501 _ => panic!("Unexpected event"),
504 if steps & 0x0f == 6 { return; }
505 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
507 if steps & 0x0f == 7 { return; }
508 confirm_transaction(&nodes[0], &tx);
509 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
513 fn test_sanity_on_in_flight_opens() {
514 do_test_sanity_on_in_flight_opens(0);
515 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(1);
517 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
518 do_test_sanity_on_in_flight_opens(2);
519 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(3);
521 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(4);
523 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(5);
525 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(6);
527 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
528 do_test_sanity_on_in_flight_opens(7);
529 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
530 do_test_sanity_on_in_flight_opens(8);
531 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
535 fn test_update_fee_vanilla() {
536 let chanmon_cfgs = create_chanmon_cfgs(2);
537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
539 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
540 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
541 let channel_id = chan.2;
543 let feerate = get_feerate!(nodes[0], channel_id);
544 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
545 check_added_monitors!(nodes[0], 1);
547 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
548 assert_eq!(events_0.len(), 1);
549 let (update_msg, commitment_signed) = match events_0[0] {
550 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 } } => {
551 (update_fee.as_ref(), commitment_signed)
553 _ => panic!("Unexpected event"),
555 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
557 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
558 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
559 check_added_monitors!(nodes[1], 1);
561 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
562 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
563 check_added_monitors!(nodes[0], 1);
565 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
566 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
567 // No commitment_signed so get_event_msg's assert(len == 1) passes
568 check_added_monitors!(nodes[0], 1);
570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
571 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
572 check_added_monitors!(nodes[1], 1);
576 fn test_update_fee_that_funder_cannot_afford() {
577 let chanmon_cfgs = create_chanmon_cfgs(2);
578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
580 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
581 let channel_value = 1888;
582 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
583 let channel_id = chan.2;
586 nodes[0].node.update_fee(channel_id, feerate).unwrap();
587 check_added_monitors!(nodes[0], 1);
588 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
590 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
592 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
594 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
595 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
597 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
599 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
600 let num_htlcs = commitment_tx.output.len() - 2;
601 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
602 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
603 actual_fee = channel_value - actual_fee;
604 assert_eq!(total_fee, actual_fee);
607 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
608 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
609 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
610 check_added_monitors!(nodes[0], 1);
612 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
616 //While producing the commitment_signed response after handling a received update_fee request the
617 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
618 //Should produce and error.
619 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
620 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
621 check_added_monitors!(nodes[1], 1);
622 check_closed_broadcast!(nodes[1], true);
626 fn test_update_fee_with_fundee_update_add_htlc() {
627 let chanmon_cfgs = create_chanmon_cfgs(2);
628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
630 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
631 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
632 let channel_id = chan.2;
633 let logger = test_utils::TestLogger::new();
636 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
638 let feerate = get_feerate!(nodes[0], channel_id);
639 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
640 check_added_monitors!(nodes[0], 1);
642 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
643 assert_eq!(events_0.len(), 1);
644 let (update_msg, commitment_signed) = match events_0[0] {
645 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 } } => {
646 (update_fee.as_ref(), commitment_signed)
648 _ => panic!("Unexpected event"),
650 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
651 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
652 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
653 check_added_monitors!(nodes[1], 1);
655 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
656 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
657 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();
659 // nothing happens since node[1] is in AwaitingRemoteRevoke
660 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
662 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
663 assert_eq!(added_monitors.len(), 0);
664 added_monitors.clear();
666 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
667 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
668 // node[1] has nothing to do
670 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
671 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
672 check_added_monitors!(nodes[0], 1);
674 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
675 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
676 // No commitment_signed so get_event_msg's assert(len == 1) passes
677 check_added_monitors!(nodes[0], 1);
678 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
679 check_added_monitors!(nodes[1], 1);
680 // AwaitingRemoteRevoke ends here
682 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
683 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
684 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
685 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
686 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
687 assert_eq!(commitment_update.update_fee.is_none(), true);
689 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
690 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
691 check_added_monitors!(nodes[0], 1);
692 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
694 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
695 check_added_monitors!(nodes[1], 1);
696 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
698 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
699 check_added_monitors!(nodes[1], 1);
700 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
701 // No commitment_signed so get_event_msg's assert(len == 1) passes
703 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
704 check_added_monitors!(nodes[0], 1);
705 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
707 expect_pending_htlcs_forwardable!(nodes[0]);
709 let events = nodes[0].node.get_and_clear_pending_events();
710 assert_eq!(events.len(), 1);
712 Event::PaymentReceived { .. } => { },
713 _ => panic!("Unexpected event"),
716 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
718 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
719 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
720 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
724 fn test_update_fee() {
725 let chanmon_cfgs = create_chanmon_cfgs(2);
726 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
727 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
728 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
729 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
730 let channel_id = chan.2;
733 // (1) update_fee/commitment_signed ->
734 // <- (2) revoke_and_ack
735 // .- send (3) commitment_signed
736 // (4) update_fee/commitment_signed ->
737 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
738 // <- (3) commitment_signed delivered
739 // send (6) revoke_and_ack -.
740 // <- (5) deliver revoke_and_ack
741 // (6) deliver revoke_and_ack ->
742 // .- send (7) commitment_signed in response to (4)
743 // <- (7) deliver commitment_signed
746 // Create and deliver (1)...
747 let feerate = get_feerate!(nodes[0], channel_id);
748 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
749 check_added_monitors!(nodes[0], 1);
751 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
752 assert_eq!(events_0.len(), 1);
753 let (update_msg, commitment_signed) = match events_0[0] {
754 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 } } => {
755 (update_fee.as_ref(), commitment_signed)
757 _ => panic!("Unexpected event"),
759 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
761 // Generate (2) and (3):
762 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
763 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
764 check_added_monitors!(nodes[1], 1);
767 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
768 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
769 check_added_monitors!(nodes[0], 1);
771 // Create and deliver (4)...
772 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
773 check_added_monitors!(nodes[0], 1);
774 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
775 assert_eq!(events_0.len(), 1);
776 let (update_msg, commitment_signed) = match events_0[0] {
777 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 } } => {
778 (update_fee.as_ref(), commitment_signed)
780 _ => panic!("Unexpected event"),
783 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
784 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785 check_added_monitors!(nodes[1], 1);
787 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
788 // No commitment_signed so get_event_msg's assert(len == 1) passes
790 // Handle (3), creating (6):
791 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
792 check_added_monitors!(nodes[0], 1);
793 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
794 // No commitment_signed so get_event_msg's assert(len == 1) passes
797 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
798 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799 check_added_monitors!(nodes[0], 1);
801 // Deliver (6), creating (7):
802 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
803 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
804 assert!(commitment_update.update_add_htlcs.is_empty());
805 assert!(commitment_update.update_fulfill_htlcs.is_empty());
806 assert!(commitment_update.update_fail_htlcs.is_empty());
807 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
808 assert!(commitment_update.update_fee.is_none());
809 check_added_monitors!(nodes[1], 1);
812 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
813 check_added_monitors!(nodes[0], 1);
814 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
815 // No commitment_signed so get_event_msg's assert(len == 1) passes
817 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
818 check_added_monitors!(nodes[1], 1);
819 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
821 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
822 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
823 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
827 fn pre_funding_lock_shutdown_test() {
828 // Test sending a shutdown prior to funding_locked after funding generation
829 let chanmon_cfgs = create_chanmon_cfgs(2);
830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
833 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
834 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
835 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
836 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
838 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
839 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
840 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
841 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
842 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
844 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
845 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
846 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
847 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
848 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
849 assert!(node_0_none.is_none());
851 assert!(nodes[0].node.list_channels().is_empty());
852 assert!(nodes[1].node.list_channels().is_empty());
856 fn updates_shutdown_wait() {
857 // Test sending a shutdown with outstanding updates pending
858 let chanmon_cfgs = create_chanmon_cfgs(3);
859 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
860 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
861 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
862 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
863 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
864 let logger = test_utils::TestLogger::new();
866 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
868 nodes[0].node.close_channel(&chan_1.2).unwrap();
869 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
870 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
871 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
872 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
874 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
875 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
877 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
879 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
880 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
881 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();
882 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();
883 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
884 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
886 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
887 check_added_monitors!(nodes[2], 1);
888 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
889 assert!(updates.update_add_htlcs.is_empty());
890 assert!(updates.update_fail_htlcs.is_empty());
891 assert!(updates.update_fail_malformed_htlcs.is_empty());
892 assert!(updates.update_fee.is_none());
893 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
894 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
895 check_added_monitors!(nodes[1], 1);
896 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
897 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
899 assert!(updates_2.update_add_htlcs.is_empty());
900 assert!(updates_2.update_fail_htlcs.is_empty());
901 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
902 assert!(updates_2.update_fee.is_none());
903 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
904 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
905 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
907 let events = nodes[0].node.get_and_clear_pending_events();
908 assert_eq!(events.len(), 1);
910 Event::PaymentSent { ref payment_preimage } => {
911 assert_eq!(our_payment_preimage, *payment_preimage);
913 _ => panic!("Unexpected event"),
916 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
917 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
918 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
919 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
920 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
921 assert!(node_0_none.is_none());
923 assert!(nodes[0].node.list_channels().is_empty());
925 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
926 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
927 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
928 assert!(nodes[1].node.list_channels().is_empty());
929 assert!(nodes[2].node.list_channels().is_empty());
933 fn htlc_fail_async_shutdown() {
934 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
935 let chanmon_cfgs = create_chanmon_cfgs(3);
936 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
937 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
938 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
939 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
940 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
941 let logger = test_utils::TestLogger::new();
943 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
944 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
945 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();
946 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
947 check_added_monitors!(nodes[0], 1);
948 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
949 assert_eq!(updates.update_add_htlcs.len(), 1);
950 assert!(updates.update_fulfill_htlcs.is_empty());
951 assert!(updates.update_fail_htlcs.is_empty());
952 assert!(updates.update_fail_malformed_htlcs.is_empty());
953 assert!(updates.update_fee.is_none());
955 nodes[1].node.close_channel(&chan_1.2).unwrap();
956 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
957 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
958 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
961 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
962 check_added_monitors!(nodes[1], 1);
963 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
964 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
966 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
967 assert!(updates_2.update_add_htlcs.is_empty());
968 assert!(updates_2.update_fulfill_htlcs.is_empty());
969 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
970 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
971 assert!(updates_2.update_fee.is_none());
973 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
974 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
976 expect_payment_failed!(nodes[0], our_payment_hash, false);
978 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
979 assert_eq!(msg_events.len(), 2);
980 let node_0_closing_signed = match msg_events[0] {
981 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
982 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
985 _ => panic!("Unexpected event"),
987 match msg_events[1] {
988 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
989 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
991 _ => panic!("Unexpected event"),
994 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
995 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
996 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
997 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
998 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
999 assert!(node_0_none.is_none());
1001 assert!(nodes[0].node.list_channels().is_empty());
1003 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1004 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1005 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1006 assert!(nodes[1].node.list_channels().is_empty());
1007 assert!(nodes[2].node.list_channels().is_empty());
1010 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1011 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1012 // messages delivered prior to disconnect
1013 let chanmon_cfgs = create_chanmon_cfgs(3);
1014 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1015 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1016 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1017 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1018 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1020 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1022 nodes[1].node.close_channel(&chan_1.2).unwrap();
1023 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1025 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1026 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1028 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1032 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1033 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1035 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1037 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1038 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1040 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1041 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1042 assert!(node_1_shutdown == node_1_2nd_shutdown);
1044 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1045 let node_0_2nd_shutdown = if recv_count > 0 {
1046 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1047 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1050 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1051 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1052 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1054 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1056 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1057 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1059 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1060 check_added_monitors!(nodes[2], 1);
1061 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1062 assert!(updates.update_add_htlcs.is_empty());
1063 assert!(updates.update_fail_htlcs.is_empty());
1064 assert!(updates.update_fail_malformed_htlcs.is_empty());
1065 assert!(updates.update_fee.is_none());
1066 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1067 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1068 check_added_monitors!(nodes[1], 1);
1069 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1070 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1072 assert!(updates_2.update_add_htlcs.is_empty());
1073 assert!(updates_2.update_fail_htlcs.is_empty());
1074 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1075 assert!(updates_2.update_fee.is_none());
1076 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1077 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1078 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1080 let events = nodes[0].node.get_and_clear_pending_events();
1081 assert_eq!(events.len(), 1);
1083 Event::PaymentSent { ref payment_preimage } => {
1084 assert_eq!(our_payment_preimage, *payment_preimage);
1086 _ => panic!("Unexpected event"),
1089 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1091 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1092 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1093 assert!(node_1_closing_signed.is_some());
1096 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1097 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1099 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1101 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1102 if recv_count == 0 {
1103 // If all closing_signeds weren't delivered we can just resume where we left off...
1104 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1106 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1107 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1108 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1110 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1111 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1112 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1114 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1115 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1117 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1118 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1119 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1121 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1122 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1123 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1124 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1125 assert!(node_0_none.is_none());
1127 // If one node, however, received + responded with an identical closing_signed we end
1128 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1129 // There isn't really anything better we can do simply, but in the future we might
1130 // explore storing a set of recently-closed channels that got disconnected during
1131 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1132 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1136 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1137 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1138 assert_eq!(msg_events.len(), 1);
1139 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1141 &ErrorAction::SendErrorMessage { ref msg } => {
1142 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1143 assert_eq!(msg.channel_id, chan_1.2);
1145 _ => panic!("Unexpected event!"),
1147 } else { panic!("Needed SendErrorMessage close"); }
1149 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1150 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1151 // closing_signed so we do it ourselves
1152 check_closed_broadcast!(nodes[0], false);
1153 check_added_monitors!(nodes[0], 1);
1156 assert!(nodes[0].node.list_channels().is_empty());
1158 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1159 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1160 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1161 assert!(nodes[1].node.list_channels().is_empty());
1162 assert!(nodes[2].node.list_channels().is_empty());
1166 fn test_shutdown_rebroadcast() {
1167 do_test_shutdown_rebroadcast(0);
1168 do_test_shutdown_rebroadcast(1);
1169 do_test_shutdown_rebroadcast(2);
1173 fn fake_network_test() {
1174 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1175 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1176 let chanmon_cfgs = create_chanmon_cfgs(4);
1177 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1178 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1179 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1181 // Create some initial channels
1182 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1183 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1184 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1186 // Rebalance the network a bit by relaying one payment through all the channels...
1187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1189 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1190 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1192 // Send some more payments
1193 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1194 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1195 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1197 // Test failure packets
1198 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1199 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1201 // Add a new channel that skips 3
1202 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1204 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1205 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1206 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1209 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1210 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1212 // Do some rebalance loop payments, simultaneously
1213 let mut hops = Vec::with_capacity(3);
1214 hops.push(RouteHop {
1215 pubkey: nodes[2].node.get_our_node_id(),
1216 node_features: NodeFeatures::empty(),
1217 short_channel_id: chan_2.0.contents.short_channel_id,
1218 channel_features: ChannelFeatures::empty(),
1220 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1222 hops.push(RouteHop {
1223 pubkey: nodes[3].node.get_our_node_id(),
1224 node_features: NodeFeatures::empty(),
1225 short_channel_id: chan_3.0.contents.short_channel_id,
1226 channel_features: ChannelFeatures::empty(),
1228 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1230 hops.push(RouteHop {
1231 pubkey: nodes[1].node.get_our_node_id(),
1232 node_features: NodeFeatures::empty(),
1233 short_channel_id: chan_4.0.contents.short_channel_id,
1234 channel_features: ChannelFeatures::empty(),
1236 cltv_expiry_delta: TEST_FINAL_CLTV,
1238 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;
1239 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;
1240 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1242 let mut hops = Vec::with_capacity(3);
1243 hops.push(RouteHop {
1244 pubkey: nodes[3].node.get_our_node_id(),
1245 node_features: NodeFeatures::empty(),
1246 short_channel_id: chan_4.0.contents.short_channel_id,
1247 channel_features: ChannelFeatures::empty(),
1249 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1251 hops.push(RouteHop {
1252 pubkey: nodes[2].node.get_our_node_id(),
1253 node_features: NodeFeatures::empty(),
1254 short_channel_id: chan_3.0.contents.short_channel_id,
1255 channel_features: ChannelFeatures::empty(),
1257 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1259 hops.push(RouteHop {
1260 pubkey: nodes[1].node.get_our_node_id(),
1261 node_features: NodeFeatures::empty(),
1262 short_channel_id: chan_2.0.contents.short_channel_id,
1263 channel_features: ChannelFeatures::empty(),
1265 cltv_expiry_delta: TEST_FINAL_CLTV,
1267 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;
1268 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;
1269 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1271 // Claim the rebalances...
1272 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1273 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1275 // Add a duplicate new channel from 2 to 4
1276 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1278 // Send some payments across both channels
1279 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1281 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1284 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1285 let events = nodes[0].node.get_and_clear_pending_msg_events();
1286 assert_eq!(events.len(), 0);
1287 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);
1289 //TODO: Test that routes work again here as we've been notified that the channel is full
1291 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1292 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1293 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1295 // Close down the channels...
1296 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1297 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1298 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1299 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1300 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1304 fn holding_cell_htlc_counting() {
1305 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1306 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1307 // commitment dance rounds.
1308 let chanmon_cfgs = create_chanmon_cfgs(3);
1309 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1310 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1311 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1312 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1313 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1314 let logger = test_utils::TestLogger::new();
1316 let mut payments = Vec::new();
1317 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1318 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1319 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1320 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();
1321 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1322 payments.push((payment_preimage, payment_hash));
1324 check_added_monitors!(nodes[1], 1);
1326 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1327 assert_eq!(events.len(), 1);
1328 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1329 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1331 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1332 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1334 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1336 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1337 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();
1338 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1339 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1340 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1341 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1344 // This should also be true if we try to forward a payment.
1345 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1347 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1348 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();
1349 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1350 check_added_monitors!(nodes[0], 1);
1353 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1354 assert_eq!(events.len(), 1);
1355 let payment_event = SendEvent::from_event(events.pop().unwrap());
1356 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1359 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1360 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1361 // fails), the second will process the resulting failure and fail the HTLC backward.
1362 expect_pending_htlcs_forwardable!(nodes[1]);
1363 expect_pending_htlcs_forwardable!(nodes[1]);
1364 check_added_monitors!(nodes[1], 1);
1366 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1367 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1368 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1370 let events = nodes[0].node.get_and_clear_pending_msg_events();
1371 assert_eq!(events.len(), 1);
1373 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1374 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1376 _ => panic!("Unexpected event"),
1379 expect_payment_failed!(nodes[0], payment_hash_2, false);
1381 // Now forward all the pending HTLCs and claim them back
1382 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1383 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1384 check_added_monitors!(nodes[2], 1);
1386 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1387 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1388 check_added_monitors!(nodes[1], 1);
1389 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1391 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1392 check_added_monitors!(nodes[1], 1);
1393 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1395 for ref update in as_updates.update_add_htlcs.iter() {
1396 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1398 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1399 check_added_monitors!(nodes[2], 1);
1400 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1401 check_added_monitors!(nodes[2], 1);
1402 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1404 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1405 check_added_monitors!(nodes[1], 1);
1406 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1407 check_added_monitors!(nodes[1], 1);
1408 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1410 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1411 check_added_monitors!(nodes[2], 1);
1413 expect_pending_htlcs_forwardable!(nodes[2]);
1415 let events = nodes[2].node.get_and_clear_pending_events();
1416 assert_eq!(events.len(), payments.len());
1417 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1419 &Event::PaymentReceived { ref payment_hash, .. } => {
1420 assert_eq!(*payment_hash, *hash);
1422 _ => panic!("Unexpected event"),
1426 for (preimage, _) in payments.drain(..) {
1427 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1430 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1434 fn duplicate_htlc_test() {
1435 // Test that we accept duplicate payment_hash HTLCs across the network and that
1436 // claiming/failing them are all separate and don't affect each other
1437 let chanmon_cfgs = create_chanmon_cfgs(6);
1438 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1439 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1440 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1442 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1443 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1444 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1445 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1446 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1447 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1449 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1451 *nodes[0].network_payment_count.borrow_mut() -= 1;
1452 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1454 *nodes[0].network_payment_count.borrow_mut() -= 1;
1455 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1457 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1458 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1459 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1463 fn test_duplicate_htlc_different_direction_onchain() {
1464 // Test that ChannelMonitor doesn't generate 2 preimage txn
1465 // when we have 2 HTLCs with same preimage that go across a node
1466 // in opposite directions.
1467 let chanmon_cfgs = create_chanmon_cfgs(2);
1468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1470 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1473 let logger = test_utils::TestLogger::new();
1476 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1478 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1480 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1481 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();
1482 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1484 // Provide preimage to node 0 by claiming payment
1485 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1486 check_added_monitors!(nodes[0], 1);
1488 // Broadcast node 1 commitment txn
1489 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1491 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1492 let mut has_both_htlcs = 0; // check htlcs match ones committed
1493 for outp in remote_txn[0].output.iter() {
1494 if outp.value == 800_000 / 1000 {
1495 has_both_htlcs += 1;
1496 } else if outp.value == 900_000 / 1000 {
1497 has_both_htlcs += 1;
1500 assert_eq!(has_both_htlcs, 2);
1502 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1503 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1504 check_added_monitors!(nodes[0], 1);
1506 // Check we only broadcast 1 timeout tx
1507 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1508 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()) };
1509 assert_eq!(claim_txn.len(), 5);
1510 check_spends!(claim_txn[2], chan_1.3);
1511 check_spends!(claim_txn[3], claim_txn[2]);
1512 assert_eq!(htlc_pair.0.input.len(), 1);
1513 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1514 check_spends!(htlc_pair.0, remote_txn[0]);
1515 assert_eq!(htlc_pair.1.input.len(), 1);
1516 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1517 check_spends!(htlc_pair.1, remote_txn[0]);
1519 let events = nodes[0].node.get_and_clear_pending_msg_events();
1520 assert_eq!(events.len(), 2);
1523 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1524 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, .. } } => {
1525 assert!(update_add_htlcs.is_empty());
1526 assert!(update_fail_htlcs.is_empty());
1527 assert_eq!(update_fulfill_htlcs.len(), 1);
1528 assert!(update_fail_malformed_htlcs.is_empty());
1529 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1531 _ => panic!("Unexpected event"),
1537 fn test_basic_channel_reserve() {
1538 let chanmon_cfgs = create_chanmon_cfgs(2);
1539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1541 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1542 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1543 let logger = test_utils::TestLogger::new();
1545 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1546 let channel_reserve = chan_stat.channel_reserve_msat;
1548 // The 2* and +1 are for the fee spike reserve.
1549 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1550 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1551 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1552 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1553 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();
1554 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1556 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1558 &APIError::ChannelUnavailable{ref err} =>
1559 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1560 _ => panic!("Unexpected error variant"),
1563 _ => panic!("Unexpected error variant"),
1565 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1566 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);
1568 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1572 fn test_fee_spike_violation_fails_htlc() {
1573 let chanmon_cfgs = create_chanmon_cfgs(2);
1574 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1575 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1576 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1577 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1578 let logger = test_utils::TestLogger::new();
1580 macro_rules! get_route_and_payment_hash {
1581 ($recv_value: expr) => {{
1582 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1583 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1584 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();
1585 (route, payment_hash, payment_preimage)
1589 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1590 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1591 let secp_ctx = Secp256k1::new();
1592 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1594 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1596 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1597 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1598 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1599 let msg = msgs::UpdateAddHTLC {
1602 amount_msat: htlc_msat,
1603 payment_hash: payment_hash,
1604 cltv_expiry: htlc_cltv,
1605 onion_routing_packet: onion_packet,
1608 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1610 // Now manually create the commitment_signed message corresponding to the update_add
1611 // nodes[0] just sent. In the code for construction of this message, "local" refers
1612 // to the sender of the message, and "remote" refers to the receiver.
1614 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1616 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1618 // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1619 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1620 let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1621 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1622 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1623 let chan_keys = local_chan.get_keys();
1624 let pubkeys = chan_keys.pubkeys();
1625 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1626 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1628 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1629 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1630 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1631 let chan_keys = remote_chan.get_keys();
1632 let pubkeys = chan_keys.pubkeys();
1633 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1634 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1637 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1638 let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1639 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1640 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1641 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1643 // Build the remote commitment transaction so we can sign it, and then later use the
1644 // signature for the commitment_signed message.
1645 let local_chan_balance = 1313;
1646 let static_payment_pk = local_payment_point.serialize();
1647 let remote_commit_tx_output = TxOut {
1648 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1649 .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1651 value: local_chan_balance as u64
1654 let local_commit_tx_output = TxOut {
1655 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1657 &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1661 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1663 amount_msat: 3460001,
1664 cltv_expiry: htlc_cltv,
1665 payment_hash: payment_hash,
1666 transaction_output_index: Some(1),
1669 let htlc_output = TxOut {
1670 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1671 value: 3460001 / 1000
1674 let commit_tx_obscure_factor = {
1675 let mut sha = Sha256::engine();
1676 let remote_payment_point = &remote_payment_point.serialize();
1677 sha.input(&local_payment_point.serialize());
1678 sha.input(remote_payment_point);
1679 let res = Sha256::from_engine(sha).into_inner();
1681 ((res[26] as u64) << 5*8) |
1682 ((res[27] as u64) << 4*8) |
1683 ((res[28] as u64) << 3*8) |
1684 ((res[29] as u64) << 2*8) |
1685 ((res[30] as u64) << 1*8) |
1686 ((res[31] as u64) << 0*8)
1688 let commitment_number = 1;
1689 let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1690 let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1692 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1693 script_sig: Script::new(),
1694 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1695 witness: Vec::new(),
1698 let commit_tx = Transaction {
1702 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1705 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1706 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1707 let local_chan_keys = local_chan.get_keys();
1708 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1709 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1712 let commit_signed_msg = msgs::CommitmentSigned {
1715 htlc_signatures: res.1
1718 // Send the commitment_signed message to the nodes[1].
1719 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1720 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1722 // Send the RAA to nodes[1].
1723 let per_commitment_secret = local_secret;
1724 let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1725 let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1726 let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1727 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1729 let events = nodes[1].node.get_and_clear_pending_msg_events();
1730 assert_eq!(events.len(), 1);
1731 // Make sure the HTLC failed in the way we expect.
1733 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1734 assert_eq!(update_fail_htlcs.len(), 1);
1735 update_fail_htlcs[0].clone()
1737 _ => panic!("Unexpected event"),
1739 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1741 check_added_monitors!(nodes[1], 2);
1745 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1746 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1747 // Set the fee rate for the channel very high, to the point where the fundee
1748 // sending any amount would result in a channel reserve violation. In this test
1749 // we check that we would be prevented from sending an HTLC in this situation.
1750 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1751 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1755 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1756 let logger = test_utils::TestLogger::new();
1758 macro_rules! get_route_and_payment_hash {
1759 ($recv_value: expr) => {{
1760 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1761 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1762 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();
1763 (route, payment_hash, payment_preimage)
1767 let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1768 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1769 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771 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);
1775 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1776 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1777 // Set the fee rate for the channel very high, to the point where the funder
1778 // receiving 1 update_add_htlc would result in them closing the channel due
1779 // to channel reserve violation. This close could also happen if the fee went
1780 // up a more realistic amount, but many HTLCs were outstanding at the time of
1781 // the update_add_htlc.
1782 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1783 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1786 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1787 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1788 let logger = test_utils::TestLogger::new();
1790 macro_rules! get_route_and_payment_hash {
1791 ($recv_value: expr) => {{
1792 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1793 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1794 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();
1795 (route, payment_hash, payment_preimage)
1799 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1800 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1801 let secp_ctx = Secp256k1::new();
1802 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1803 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1804 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1805 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1806 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1807 let msg = msgs::UpdateAddHTLC {
1810 amount_msat: htlc_msat + 1,
1811 payment_hash: payment_hash,
1812 cltv_expiry: htlc_cltv,
1813 onion_routing_packet: onion_packet,
1816 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1817 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1818 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);
1819 assert_eq!(nodes[0].node.list_channels().len(), 0);
1820 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1821 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1822 check_added_monitors!(nodes[0], 1);
1826 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1827 let chanmon_cfgs = create_chanmon_cfgs(3);
1828 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1829 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1830 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1831 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1832 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1833 let logger = test_utils::TestLogger::new();
1835 macro_rules! get_route_and_payment_hash {
1836 ($recv_value: expr) => {{
1837 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1838 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1839 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();
1840 (route, payment_hash, payment_preimage)
1845 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1846 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1847 let feerate = get_feerate!(nodes[0], chan.2);
1849 // Add a 2* and +1 for the fee spike reserve.
1850 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1851 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;
1852 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1854 // Add a pending HTLC.
1855 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1856 let payment_event_1 = {
1857 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1858 check_added_monitors!(nodes[0], 1);
1860 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1861 assert_eq!(events.len(), 1);
1862 SendEvent::from_event(events.remove(0))
1864 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1866 // Attempt to trigger a channel reserve violation --> payment failure.
1867 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1868 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;
1869 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1870 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1872 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1873 let secp_ctx = Secp256k1::new();
1874 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1875 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1876 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1877 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1878 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1879 let msg = msgs::UpdateAddHTLC {
1882 amount_msat: htlc_msat + 1,
1883 payment_hash: our_payment_hash_1,
1884 cltv_expiry: htlc_cltv,
1885 onion_routing_packet: onion_packet,
1888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1889 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1890 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1891 assert_eq!(nodes[1].node.list_channels().len(), 1);
1892 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1893 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1894 check_added_monitors!(nodes[1], 1);
1898 fn test_inbound_outbound_capacity_is_not_zero() {
1899 let chanmon_cfgs = create_chanmon_cfgs(2);
1900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1903 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1904 let channels0 = node_chanmgrs[0].list_channels();
1905 let channels1 = node_chanmgrs[1].list_channels();
1906 assert_eq!(channels0.len(), 1);
1907 assert_eq!(channels1.len(), 1);
1909 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1910 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1912 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1913 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1916 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1917 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1921 fn test_channel_reserve_holding_cell_htlcs() {
1922 let chanmon_cfgs = create_chanmon_cfgs(3);
1923 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1924 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1925 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1926 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1927 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1928 let logger = test_utils::TestLogger::new();
1930 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1931 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1933 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1934 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1936 macro_rules! get_route_and_payment_hash {
1937 ($recv_value: expr) => {{
1938 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1939 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1940 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();
1941 (route, payment_hash, payment_preimage)
1945 macro_rules! expect_forward {
1947 let mut events = $node.node.get_and_clear_pending_msg_events();
1948 assert_eq!(events.len(), 1);
1949 check_added_monitors!($node, 1);
1950 let payment_event = SendEvent::from_event(events.remove(0));
1955 let feemsat = 239; // somehow we know?
1956 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1957 let feerate = get_feerate!(nodes[0], chan_1.2);
1959 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1961 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1963 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1964 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1965 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1966 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)));
1967 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1968 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);
1971 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1972 // nodes[0]'s wealth
1974 let amt_msat = recv_value_0 + total_fee_msat;
1975 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1976 // Also, ensure that each payment has enough to be over the dust limit to
1977 // ensure it'll be included in each commit tx fee calculation.
1978 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1979 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1980 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1983 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1985 let (stat01_, stat11_, stat12_, stat22_) = (
1986 get_channel_value_stat!(nodes[0], chan_1.2),
1987 get_channel_value_stat!(nodes[1], chan_1.2),
1988 get_channel_value_stat!(nodes[1], chan_2.2),
1989 get_channel_value_stat!(nodes[2], chan_2.2),
1992 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1993 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1994 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1995 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1996 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1999 // adding pending output.
2000 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2001 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2002 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2003 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2004 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2005 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2006 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2007 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2008 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2010 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2011 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2012 let amt_msat_1 = recv_value_1 + total_fee_msat;
2014 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2015 let payment_event_1 = {
2016 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2017 check_added_monitors!(nodes[0], 1);
2019 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2020 assert_eq!(events.len(), 1);
2021 SendEvent::from_event(events.remove(0))
2023 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2025 // channel reserve test with htlc pending output > 0
2026 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2028 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2029 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2030 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2031 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2034 // split the rest to test holding cell
2035 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2036 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2037 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2038 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2040 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2041 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);
2044 // now see if they go through on both sides
2045 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2046 // but this will stuck in the holding cell
2047 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2048 check_added_monitors!(nodes[0], 0);
2049 let events = nodes[0].node.get_and_clear_pending_events();
2050 assert_eq!(events.len(), 0);
2052 // test with outbound holding cell amount > 0
2054 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2055 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2056 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2057 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2058 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);
2061 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2062 // this will also stuck in the holding cell
2063 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2064 check_added_monitors!(nodes[0], 0);
2065 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2066 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2068 // flush the pending htlc
2069 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2070 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2071 check_added_monitors!(nodes[1], 1);
2073 // the pending htlc should be promoted to committed
2074 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2075 check_added_monitors!(nodes[0], 1);
2076 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2078 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2079 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2080 // No commitment_signed so get_event_msg's assert(len == 1) passes
2081 check_added_monitors!(nodes[0], 1);
2083 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2084 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2085 check_added_monitors!(nodes[1], 1);
2087 expect_pending_htlcs_forwardable!(nodes[1]);
2089 let ref payment_event_11 = expect_forward!(nodes[1]);
2090 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2091 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2093 expect_pending_htlcs_forwardable!(nodes[2]);
2094 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2096 // flush the htlcs in the holding cell
2097 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2098 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2099 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2100 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2101 expect_pending_htlcs_forwardable!(nodes[1]);
2103 let ref payment_event_3 = expect_forward!(nodes[1]);
2104 assert_eq!(payment_event_3.msgs.len(), 2);
2105 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2106 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2108 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2109 expect_pending_htlcs_forwardable!(nodes[2]);
2111 let events = nodes[2].node.get_and_clear_pending_events();
2112 assert_eq!(events.len(), 2);
2114 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2115 assert_eq!(our_payment_hash_21, *payment_hash);
2116 assert_eq!(*payment_secret, None);
2117 assert_eq!(recv_value_21, amt);
2119 _ => panic!("Unexpected event"),
2122 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2123 assert_eq!(our_payment_hash_22, *payment_hash);
2124 assert_eq!(None, *payment_secret);
2125 assert_eq!(recv_value_22, amt);
2127 _ => panic!("Unexpected event"),
2130 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2131 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2132 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2134 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2135 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2137 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2138 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2140 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2142 &APIError::ChannelUnavailable{ref err} =>
2143 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2144 _ => panic!("Unexpected error variant"),
2147 _ => panic!("Unexpected error variant"),
2149 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2150 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(), 3);
2153 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2155 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2156 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);
2157 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2158 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2159 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2161 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2162 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2166 fn channel_reserve_in_flight_removes() {
2167 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2168 // can send to its counterparty, but due to update ordering, the other side may not yet have
2169 // considered those HTLCs fully removed.
2170 // This tests that we don't count HTLCs which will not be included in the next remote
2171 // commitment transaction towards the reserve value (as it implies no commitment transaction
2172 // will be generated which violates the remote reserve value).
2173 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2175 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2176 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2177 // you only consider the value of the first HTLC, it may not),
2178 // * start routing a third HTLC from A to B,
2179 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2180 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2181 // * deliver the first fulfill from B
2182 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2184 // * deliver A's response CS and RAA.
2185 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2186 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2187 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2188 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2189 let chanmon_cfgs = create_chanmon_cfgs(2);
2190 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2191 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2192 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2193 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2194 let logger = test_utils::TestLogger::new();
2196 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2197 // Route the first two HTLCs.
2198 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2199 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2201 // Start routing the third HTLC (this is just used to get everyone in the right state).
2202 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2204 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2205 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();
2206 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2207 check_added_monitors!(nodes[0], 1);
2208 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2209 assert_eq!(events.len(), 1);
2210 SendEvent::from_event(events.remove(0))
2213 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2214 // initial fulfill/CS.
2215 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2216 check_added_monitors!(nodes[1], 1);
2217 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2219 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2220 // remove the second HTLC when we send the HTLC back from B to A.
2221 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2222 check_added_monitors!(nodes[1], 1);
2223 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2225 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2226 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2227 check_added_monitors!(nodes[0], 1);
2228 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2229 expect_payment_sent!(nodes[0], payment_preimage_1);
2231 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2232 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2233 check_added_monitors!(nodes[1], 1);
2234 // B is already AwaitingRAA, so cant generate a CS here
2235 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2237 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2238 check_added_monitors!(nodes[1], 1);
2239 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2241 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2242 check_added_monitors!(nodes[0], 1);
2243 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2245 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2246 check_added_monitors!(nodes[1], 1);
2247 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2249 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2250 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2251 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2252 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2253 // on-chain as necessary).
2254 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2255 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2256 check_added_monitors!(nodes[0], 1);
2257 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2258 expect_payment_sent!(nodes[0], payment_preimage_2);
2260 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2261 check_added_monitors!(nodes[1], 1);
2262 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2264 expect_pending_htlcs_forwardable!(nodes[1]);
2265 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2267 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2268 // resolve the second HTLC from A's point of view.
2269 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2270 check_added_monitors!(nodes[0], 1);
2271 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2273 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2274 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2275 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2277 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2278 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();
2279 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2280 check_added_monitors!(nodes[1], 1);
2281 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2282 assert_eq!(events.len(), 1);
2283 SendEvent::from_event(events.remove(0))
2286 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2288 check_added_monitors!(nodes[0], 1);
2289 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2291 // Now just resolve all the outstanding messages/HTLCs for completeness...
2293 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2294 check_added_monitors!(nodes[1], 1);
2295 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2297 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2298 check_added_monitors!(nodes[1], 1);
2300 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2301 check_added_monitors!(nodes[0], 1);
2302 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2304 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2305 check_added_monitors!(nodes[1], 1);
2306 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2308 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2309 check_added_monitors!(nodes[0], 1);
2311 expect_pending_htlcs_forwardable!(nodes[0]);
2312 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2314 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2315 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2319 fn channel_monitor_network_test() {
2320 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2321 // tests that ChannelMonitor is able to recover from various states.
2322 let chanmon_cfgs = create_chanmon_cfgs(5);
2323 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2324 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2325 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2327 // Create some initial channels
2328 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2329 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2330 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2331 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2333 // Rebalance the network a bit by relaying one payment through all the channels...
2334 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2337 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2339 // Simple case with no pending HTLCs:
2340 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2341 check_added_monitors!(nodes[1], 1);
2343 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2344 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2345 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2346 check_added_monitors!(nodes[0], 1);
2347 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2349 get_announce_close_broadcast_events(&nodes, 0, 1);
2350 assert_eq!(nodes[0].node.list_channels().len(), 0);
2351 assert_eq!(nodes[1].node.list_channels().len(), 1);
2353 // One pending HTLC is discarded by the force-close:
2354 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2356 // Simple case of one pending HTLC to HTLC-Timeout
2357 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2358 check_added_monitors!(nodes[1], 1);
2360 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2361 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2362 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2363 check_added_monitors!(nodes[2], 1);
2364 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2366 get_announce_close_broadcast_events(&nodes, 1, 2);
2367 assert_eq!(nodes[1].node.list_channels().len(), 0);
2368 assert_eq!(nodes[2].node.list_channels().len(), 1);
2370 macro_rules! claim_funds {
2371 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2373 assert!($node.node.claim_funds($preimage, &None, $amount));
2374 check_added_monitors!($node, 1);
2376 let events = $node.node.get_and_clear_pending_msg_events();
2377 assert_eq!(events.len(), 1);
2379 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2380 assert!(update_add_htlcs.is_empty());
2381 assert!(update_fail_htlcs.is_empty());
2382 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2384 _ => panic!("Unexpected event"),
2390 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2391 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2392 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2393 check_added_monitors!(nodes[2], 1);
2394 let node2_commitment_txid;
2396 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2397 node2_commitment_txid = node_txn[0].txid();
2399 // Claim the payment on nodes[3], giving it knowledge of the preimage
2400 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2402 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2403 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2404 check_added_monitors!(nodes[3], 1);
2406 check_preimage_claim(&nodes[3], &node_txn);
2408 get_announce_close_broadcast_events(&nodes, 2, 3);
2409 assert_eq!(nodes[2].node.list_channels().len(), 0);
2410 assert_eq!(nodes[3].node.list_channels().len(), 1);
2412 { // Cheat and reset nodes[4]'s height to 1
2413 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2414 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2417 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2418 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2419 // One pending HTLC to time out:
2420 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2421 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2424 let (close_chan_update_1, close_chan_update_2) = {
2425 let mut block = Block {
2426 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2429 connect_block(&nodes[3], &block, 2);
2430 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2432 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2435 connect_block(&nodes[3], &block, i);
2437 let events = nodes[3].node.get_and_clear_pending_msg_events();
2438 assert_eq!(events.len(), 1);
2439 let close_chan_update_1 = match events[0] {
2440 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2443 _ => panic!("Unexpected event"),
2445 check_added_monitors!(nodes[3], 1);
2447 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2449 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2450 node_txn.retain(|tx| {
2451 if tx.input[0].previous_output.txid == node2_commitment_txid {
2457 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2459 // Claim the payment on nodes[4], giving it knowledge of the preimage
2460 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2463 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2467 connect_block(&nodes[4], &block, 2);
2468 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2470 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2473 connect_block(&nodes[4], &block, i);
2475 let events = nodes[4].node.get_and_clear_pending_msg_events();
2476 assert_eq!(events.len(), 1);
2477 let close_chan_update_2 = match events[0] {
2478 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2481 _ => panic!("Unexpected event"),
2483 check_added_monitors!(nodes[4], 1);
2484 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2487 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2488 txdata: vec![node_txn[0].clone()],
2490 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2492 check_preimage_claim(&nodes[4], &node_txn);
2493 (close_chan_update_1, close_chan_update_2)
2495 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2496 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2497 assert_eq!(nodes[3].node.list_channels().len(), 0);
2498 assert_eq!(nodes[4].node.list_channels().len(), 0);
2502 fn test_justice_tx() {
2503 // Test justice txn built on revoked HTLC-Success tx, against both sides
2504 let mut alice_config = UserConfig::default();
2505 alice_config.channel_options.announced_channel = true;
2506 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2507 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2508 let mut bob_config = UserConfig::default();
2509 bob_config.channel_options.announced_channel = true;
2510 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2511 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2512 let user_cfgs = [Some(alice_config), Some(bob_config)];
2513 let chanmon_cfgs = create_chanmon_cfgs(2);
2514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2516 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2517 // Create some new channels:
2518 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2520 // A pending HTLC which will be revoked:
2521 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2522 // Get the will-be-revoked local txn from nodes[0]
2523 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2524 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2525 assert_eq!(revoked_local_txn[0].input.len(), 1);
2526 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2527 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2528 assert_eq!(revoked_local_txn[1].input.len(), 1);
2529 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2530 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2531 // Revoke the old state
2532 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2535 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2536 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2538 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2539 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2540 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2542 check_spends!(node_txn[0], revoked_local_txn[0]);
2543 node_txn.swap_remove(0);
2544 node_txn.truncate(1);
2546 check_added_monitors!(nodes[1], 1);
2547 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2549 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2550 // Verify broadcast of revoked HTLC-timeout
2551 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2552 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2553 check_added_monitors!(nodes[0], 1);
2554 // Broadcast revoked HTLC-timeout on node 1
2555 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2556 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2558 get_announce_close_broadcast_events(&nodes, 0, 1);
2560 assert_eq!(nodes[0].node.list_channels().len(), 0);
2561 assert_eq!(nodes[1].node.list_channels().len(), 0);
2563 // We test justice_tx build by A on B's revoked HTLC-Success tx
2564 // Create some new channels:
2565 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2567 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2571 // A pending HTLC which will be revoked:
2572 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2573 // Get the will-be-revoked local txn from B
2574 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2575 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2576 assert_eq!(revoked_local_txn[0].input.len(), 1);
2577 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2578 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2579 // Revoke the old state
2580 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2582 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2583 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2585 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2586 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2587 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2589 check_spends!(node_txn[0], revoked_local_txn[0]);
2590 node_txn.swap_remove(0);
2592 check_added_monitors!(nodes[0], 1);
2593 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2595 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2596 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2597 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2598 check_added_monitors!(nodes[1], 1);
2599 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2600 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2602 get_announce_close_broadcast_events(&nodes, 0, 1);
2603 assert_eq!(nodes[0].node.list_channels().len(), 0);
2604 assert_eq!(nodes[1].node.list_channels().len(), 0);
2608 fn revoked_output_claim() {
2609 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2610 // transaction is broadcast by its counterparty
2611 let chanmon_cfgs = create_chanmon_cfgs(2);
2612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2614 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2615 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2616 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2617 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2618 assert_eq!(revoked_local_txn.len(), 1);
2619 // Only output is the full channel value back to nodes[0]:
2620 assert_eq!(revoked_local_txn[0].output.len(), 1);
2621 // Send a payment through, updating everyone's latest commitment txn
2622 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2624 // Inform nodes[1] that nodes[0] broadcast a stale tx
2625 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2626 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2627 check_added_monitors!(nodes[1], 1);
2628 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2629 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2631 check_spends!(node_txn[0], revoked_local_txn[0]);
2632 check_spends!(node_txn[1], chan_1.3);
2634 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2635 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2636 get_announce_close_broadcast_events(&nodes, 0, 1);
2637 check_added_monitors!(nodes[0], 1)
2641 fn claim_htlc_outputs_shared_tx() {
2642 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2643 let chanmon_cfgs = create_chanmon_cfgs(2);
2644 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2645 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2646 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2648 // Create some new channel:
2649 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2651 // Rebalance the network to generate htlc in the two directions
2652 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2653 // 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
2654 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2655 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2657 // Get the will-be-revoked local txn from node[0]
2658 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2659 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2660 assert_eq!(revoked_local_txn[0].input.len(), 1);
2661 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2662 assert_eq!(revoked_local_txn[1].input.len(), 1);
2663 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2664 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2665 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2667 //Revoke the old state
2668 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2671 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2672 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2673 check_added_monitors!(nodes[0], 1);
2674 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2675 check_added_monitors!(nodes[1], 1);
2676 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2677 expect_payment_failed!(nodes[1], payment_hash_2, true);
2679 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2680 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2682 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2683 check_spends!(node_txn[0], revoked_local_txn[0]);
2685 let mut witness_lens = BTreeSet::new();
2686 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2687 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2688 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2689 assert_eq!(witness_lens.len(), 3);
2690 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2691 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2692 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2694 // Next nodes[1] broadcasts its current local tx state:
2695 assert_eq!(node_txn[1].input.len(), 1);
2696 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2698 assert_eq!(node_txn[2].input.len(), 1);
2699 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2700 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2701 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2702 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2703 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2705 get_announce_close_broadcast_events(&nodes, 0, 1);
2706 assert_eq!(nodes[0].node.list_channels().len(), 0);
2707 assert_eq!(nodes[1].node.list_channels().len(), 0);
2711 fn claim_htlc_outputs_single_tx() {
2712 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2713 let chanmon_cfgs = create_chanmon_cfgs(2);
2714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2716 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2718 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2720 // Rebalance the network to generate htlc in the two directions
2721 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2722 // 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
2723 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2724 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2725 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2727 // Get the will-be-revoked local txn from node[0]
2728 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2730 //Revoke the old state
2731 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2734 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2735 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2736 check_added_monitors!(nodes[0], 1);
2737 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2738 check_added_monitors!(nodes[1], 1);
2739 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2741 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2742 expect_payment_failed!(nodes[1], payment_hash_2, true);
2744 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2745 assert_eq!(node_txn.len(), 9);
2746 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2747 // ChannelManager: local commmitment + local HTLC-timeout (2)
2748 // 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)
2749 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2751 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2752 assert_eq!(node_txn[2].input.len(), 1);
2753 check_spends!(node_txn[2], chan_1.3);
2754 assert_eq!(node_txn[3].input.len(), 1);
2755 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2756 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2757 check_spends!(node_txn[3], node_txn[2]);
2759 // Justice transactions are indices 1-2-4
2760 assert_eq!(node_txn[0].input.len(), 1);
2761 assert_eq!(node_txn[1].input.len(), 1);
2762 assert_eq!(node_txn[4].input.len(), 1);
2764 check_spends!(node_txn[0], revoked_local_txn[0]);
2765 check_spends!(node_txn[1], revoked_local_txn[0]);
2766 check_spends!(node_txn[4], revoked_local_txn[0]);
2768 let mut witness_lens = BTreeSet::new();
2769 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2770 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2771 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2772 assert_eq!(witness_lens.len(), 3);
2773 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2774 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2775 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2777 get_announce_close_broadcast_events(&nodes, 0, 1);
2778 assert_eq!(nodes[0].node.list_channels().len(), 0);
2779 assert_eq!(nodes[1].node.list_channels().len(), 0);
2783 fn test_htlc_on_chain_success() {
2784 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2785 // the preimage backward accordingly. So here we test that ChannelManager is
2786 // broadcasting the right event to other nodes in payment path.
2787 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2788 // A --------------------> B ----------------------> C (preimage)
2789 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2790 // commitment transaction was broadcast.
2791 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2793 // B should be able to claim via preimage if A then broadcasts its local tx.
2794 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2795 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2796 // PaymentSent event).
2798 let chanmon_cfgs = create_chanmon_cfgs(3);
2799 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2800 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2801 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2803 // Create some initial channels
2804 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2805 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2807 // Rebalance the network a bit by relaying one payment through all the channels...
2808 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2809 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2811 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2812 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2813 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2815 // Broadcast legit commitment tx from C on B's chain
2816 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2817 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2818 assert_eq!(commitment_tx.len(), 1);
2819 check_spends!(commitment_tx[0], chan_2.3);
2820 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2821 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2822 check_added_monitors!(nodes[2], 2);
2823 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2824 assert!(updates.update_add_htlcs.is_empty());
2825 assert!(updates.update_fail_htlcs.is_empty());
2826 assert!(updates.update_fail_malformed_htlcs.is_empty());
2827 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2829 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2830 check_closed_broadcast!(nodes[2], false);
2831 check_added_monitors!(nodes[2], 1);
2832 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)
2833 assert_eq!(node_txn.len(), 5);
2834 assert_eq!(node_txn[0], node_txn[3]);
2835 assert_eq!(node_txn[1], node_txn[4]);
2836 assert_eq!(node_txn[2], commitment_tx[0]);
2837 check_spends!(node_txn[0], commitment_tx[0]);
2838 check_spends!(node_txn[1], commitment_tx[0]);
2839 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2840 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2842 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843 assert_eq!(node_txn[0].lock_time, 0);
2844 assert_eq!(node_txn[1].lock_time, 0);
2846 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2847 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2849 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2850 assert_eq!(added_monitors.len(), 1);
2851 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2852 added_monitors.clear();
2854 let events = nodes[1].node.get_and_clear_pending_msg_events();
2856 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2857 assert_eq!(added_monitors.len(), 2);
2858 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2859 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2860 added_monitors.clear();
2862 assert_eq!(events.len(), 2);
2864 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2865 _ => panic!("Unexpected event"),
2868 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, .. } } => {
2869 assert!(update_add_htlcs.is_empty());
2870 assert!(update_fail_htlcs.is_empty());
2871 assert_eq!(update_fulfill_htlcs.len(), 1);
2872 assert!(update_fail_malformed_htlcs.is_empty());
2873 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2875 _ => panic!("Unexpected event"),
2877 macro_rules! check_tx_local_broadcast {
2878 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2879 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2880 assert_eq!(node_txn.len(), 5);
2881 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2882 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2883 check_spends!(node_txn[0], $commitment_tx);
2884 check_spends!(node_txn[1], $commitment_tx);
2885 assert_ne!(node_txn[0].lock_time, 0);
2886 assert_ne!(node_txn[1].lock_time, 0);
2888 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2889 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2890 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2891 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2893 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2894 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2895 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2896 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2898 check_spends!(node_txn[2], $chan_tx);
2899 check_spends!(node_txn[3], node_txn[2]);
2900 check_spends!(node_txn[4], node_txn[2]);
2901 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2902 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2903 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2904 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2905 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2906 assert_ne!(node_txn[3].lock_time, 0);
2907 assert_ne!(node_txn[4].lock_time, 0);
2911 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2912 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2913 // timeout-claim of the output that nodes[2] just claimed via success.
2914 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2916 // Broadcast legit commitment tx from A on B's chain
2917 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2918 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2919 check_spends!(commitment_tx[0], chan_1.3);
2920 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2921 check_closed_broadcast!(nodes[1], false);
2922 check_added_monitors!(nodes[1], 1);
2923 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2924 assert_eq!(node_txn.len(), 4);
2925 check_spends!(node_txn[0], commitment_tx[0]);
2926 assert_eq!(node_txn[0].input.len(), 2);
2927 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2928 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2929 assert_eq!(node_txn[0].lock_time, 0);
2930 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2931 check_spends!(node_txn[1], chan_1.3);
2932 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2933 check_spends!(node_txn[2], node_txn[1]);
2934 check_spends!(node_txn[3], node_txn[1]);
2935 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2936 // we already checked the same situation with A.
2938 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2939 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2940 check_closed_broadcast!(nodes[0], false);
2941 check_added_monitors!(nodes[0], 1);
2942 let events = nodes[0].node.get_and_clear_pending_events();
2943 assert_eq!(events.len(), 2);
2944 let mut first_claimed = false;
2945 for event in events {
2947 Event::PaymentSent { payment_preimage } => {
2948 if payment_preimage == our_payment_preimage {
2949 assert!(!first_claimed);
2950 first_claimed = true;
2952 assert_eq!(payment_preimage, our_payment_preimage_2);
2955 _ => panic!("Unexpected event"),
2958 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2962 fn test_htlc_on_chain_timeout() {
2963 // Test that in case of a unilateral close onchain, we detect the state of output and
2964 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2965 // broadcasting the right event to other nodes in payment path.
2966 // A ------------------> B ----------------------> C (timeout)
2967 // B's commitment tx C's commitment tx
2969 // B's HTLC timeout tx B's timeout tx
2971 let chanmon_cfgs = create_chanmon_cfgs(3);
2972 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2973 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2974 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2976 // Create some intial channels
2977 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2978 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2980 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2981 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2982 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2984 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2985 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2987 // Broadcast legit commitment tx from C on B's chain
2988 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2989 check_spends!(commitment_tx[0], chan_2.3);
2990 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2991 check_added_monitors!(nodes[2], 0);
2992 expect_pending_htlcs_forwardable!(nodes[2]);
2993 check_added_monitors!(nodes[2], 1);
2995 let events = nodes[2].node.get_and_clear_pending_msg_events();
2996 assert_eq!(events.len(), 1);
2998 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, .. } } => {
2999 assert!(update_add_htlcs.is_empty());
3000 assert!(!update_fail_htlcs.is_empty());
3001 assert!(update_fulfill_htlcs.is_empty());
3002 assert!(update_fail_malformed_htlcs.is_empty());
3003 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3005 _ => panic!("Unexpected event"),
3007 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3008 check_closed_broadcast!(nodes[2], false);
3009 check_added_monitors!(nodes[2], 1);
3010 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3011 assert_eq!(node_txn.len(), 1);
3012 check_spends!(node_txn[0], chan_2.3);
3013 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3015 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3016 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3017 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3020 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3021 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3022 assert_eq!(node_txn[1], node_txn[3]);
3023 assert_eq!(node_txn[2], node_txn[4]);
3025 check_spends!(node_txn[0], commitment_tx[0]);
3026 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3028 check_spends!(node_txn[1], chan_2.3);
3029 check_spends!(node_txn[2], node_txn[1]);
3030 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3031 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3033 timeout_tx = node_txn[0].clone();
3037 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3038 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3039 check_added_monitors!(nodes[1], 1);
3040 check_closed_broadcast!(nodes[1], false);
3042 expect_pending_htlcs_forwardable!(nodes[1]);
3043 check_added_monitors!(nodes[1], 1);
3044 let events = nodes[1].node.get_and_clear_pending_msg_events();
3045 assert_eq!(events.len(), 1);
3047 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, .. } } => {
3048 assert!(update_add_htlcs.is_empty());
3049 assert!(!update_fail_htlcs.is_empty());
3050 assert!(update_fulfill_htlcs.is_empty());
3051 assert!(update_fail_malformed_htlcs.is_empty());
3052 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3054 _ => panic!("Unexpected event"),
3056 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
3057 assert_eq!(node_txn.len(), 0);
3059 // Broadcast legit commitment tx from B on A's chain
3060 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3061 check_spends!(commitment_tx[0], chan_1.3);
3063 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3064 check_closed_broadcast!(nodes[0], false);
3065 check_added_monitors!(nodes[0], 1);
3066 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3067 assert_eq!(node_txn.len(), 3);
3068 check_spends!(node_txn[0], commitment_tx[0]);
3069 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3070 check_spends!(node_txn[1], chan_1.3);
3071 check_spends!(node_txn[2], node_txn[1]);
3072 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3073 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3077 fn test_simple_commitment_revoked_fail_backward() {
3078 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3079 // and fail backward accordingly.
3081 let chanmon_cfgs = create_chanmon_cfgs(3);
3082 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3083 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3084 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3086 // Create some initial channels
3087 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3088 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3090 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3091 // Get the will-be-revoked local txn from nodes[2]
3092 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3093 // Revoke the old state
3094 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3096 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3098 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3099 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3100 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3101 check_added_monitors!(nodes[1], 1);
3102 check_closed_broadcast!(nodes[1], false);
3104 expect_pending_htlcs_forwardable!(nodes[1]);
3105 check_added_monitors!(nodes[1], 1);
3106 let events = nodes[1].node.get_and_clear_pending_msg_events();
3107 assert_eq!(events.len(), 1);
3109 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, .. } } => {
3110 assert!(update_add_htlcs.is_empty());
3111 assert_eq!(update_fail_htlcs.len(), 1);
3112 assert!(update_fulfill_htlcs.is_empty());
3113 assert!(update_fail_malformed_htlcs.is_empty());
3114 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3116 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3117 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3119 let events = nodes[0].node.get_and_clear_pending_msg_events();
3120 assert_eq!(events.len(), 1);
3122 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3123 _ => panic!("Unexpected event"),
3125 expect_payment_failed!(nodes[0], payment_hash, false);
3127 _ => panic!("Unexpected event"),
3131 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3132 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3133 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3134 // commitment transaction anymore.
3135 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3136 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3137 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3138 // technically disallowed and we should probably handle it reasonably.
3139 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3140 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3142 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3143 // commitment_signed (implying it will be in the latest remote commitment transaction).
3144 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3145 // and once they revoke the previous commitment transaction (allowing us to send a new
3146 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3147 let chanmon_cfgs = create_chanmon_cfgs(3);
3148 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3149 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3150 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3152 // Create some initial channels
3153 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3154 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3156 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3157 // Get the will-be-revoked local txn from nodes[2]
3158 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3159 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3160 // Revoke the old state
3161 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3163 let value = if use_dust {
3164 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3165 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3166 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3169 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3170 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3171 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3173 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3174 expect_pending_htlcs_forwardable!(nodes[2]);
3175 check_added_monitors!(nodes[2], 1);
3176 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3177 assert!(updates.update_add_htlcs.is_empty());
3178 assert!(updates.update_fulfill_htlcs.is_empty());
3179 assert!(updates.update_fail_malformed_htlcs.is_empty());
3180 assert_eq!(updates.update_fail_htlcs.len(), 1);
3181 assert!(updates.update_fee.is_none());
3182 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3183 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3184 // Drop the last RAA from 3 -> 2
3186 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3187 expect_pending_htlcs_forwardable!(nodes[2]);
3188 check_added_monitors!(nodes[2], 1);
3189 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3190 assert!(updates.update_add_htlcs.is_empty());
3191 assert!(updates.update_fulfill_htlcs.is_empty());
3192 assert!(updates.update_fail_malformed_htlcs.is_empty());
3193 assert_eq!(updates.update_fail_htlcs.len(), 1);
3194 assert!(updates.update_fee.is_none());
3195 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3196 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3197 check_added_monitors!(nodes[1], 1);
3198 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3199 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3200 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3201 check_added_monitors!(nodes[2], 1);
3203 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3204 expect_pending_htlcs_forwardable!(nodes[2]);
3205 check_added_monitors!(nodes[2], 1);
3206 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3207 assert!(updates.update_add_htlcs.is_empty());
3208 assert!(updates.update_fulfill_htlcs.is_empty());
3209 assert!(updates.update_fail_malformed_htlcs.is_empty());
3210 assert_eq!(updates.update_fail_htlcs.len(), 1);
3211 assert!(updates.update_fee.is_none());
3212 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3213 // At this point first_payment_hash has dropped out of the latest two commitment
3214 // transactions that nodes[1] is tracking...
3215 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3216 check_added_monitors!(nodes[1], 1);
3217 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3218 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3219 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3220 check_added_monitors!(nodes[2], 1);
3222 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3223 // on nodes[2]'s RAA.
3224 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3225 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3226 let logger = test_utils::TestLogger::new();
3227 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();
3228 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3229 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3230 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3231 check_added_monitors!(nodes[1], 0);
3234 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3235 // One monitor for the new revocation preimage, no second on as we won't generate a new
3236 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3237 check_added_monitors!(nodes[1], 1);
3238 let events = nodes[1].node.get_and_clear_pending_events();
3239 assert_eq!(events.len(), 1);
3241 Event::PendingHTLCsForwardable { .. } => { },
3242 _ => panic!("Unexpected event"),
3244 // Deliberately don't process the pending fail-back so they all fail back at once after
3245 // block connection just like the !deliver_bs_raa case
3248 let mut failed_htlcs = HashSet::new();
3249 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3251 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3252 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3253 check_added_monitors!(nodes[1], 1);
3254 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3256 let events = nodes[1].node.get_and_clear_pending_events();
3257 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3259 Event::PaymentFailed { ref payment_hash, .. } => {
3260 assert_eq!(*payment_hash, fourth_payment_hash);
3262 _ => panic!("Unexpected event"),
3264 if !deliver_bs_raa {
3266 Event::PendingHTLCsForwardable { .. } => { },
3267 _ => panic!("Unexpected event"),
3270 nodes[1].node.process_pending_htlc_forwards();
3271 check_added_monitors!(nodes[1], 1);
3273 let events = nodes[1].node.get_and_clear_pending_msg_events();
3274 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3275 match events[if deliver_bs_raa { 1 } else { 0 }] {
3276 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3277 _ => panic!("Unexpected event"),
3281 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, .. } } => {
3282 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3283 assert_eq!(update_add_htlcs.len(), 1);
3284 assert!(update_fulfill_htlcs.is_empty());
3285 assert!(update_fail_htlcs.is_empty());
3286 assert!(update_fail_malformed_htlcs.is_empty());
3288 _ => panic!("Unexpected event"),
3291 match events[if deliver_bs_raa { 2 } else { 1 }] {
3292 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, .. } } => {
3293 assert!(update_add_htlcs.is_empty());
3294 assert_eq!(update_fail_htlcs.len(), 3);
3295 assert!(update_fulfill_htlcs.is_empty());
3296 assert!(update_fail_malformed_htlcs.is_empty());
3297 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3299 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3300 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3301 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3303 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3305 let events = nodes[0].node.get_and_clear_pending_msg_events();
3306 // If we delivered B's RAA we got an unknown preimage error, not something
3307 // that we should update our routing table for.
3308 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3309 for event in events {
3311 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3312 _ => panic!("Unexpected event"),
3315 let events = nodes[0].node.get_and_clear_pending_events();
3316 assert_eq!(events.len(), 3);
3318 Event::PaymentFailed { ref payment_hash, .. } => {
3319 assert!(failed_htlcs.insert(payment_hash.0));
3321 _ => panic!("Unexpected event"),
3324 Event::PaymentFailed { ref payment_hash, .. } => {
3325 assert!(failed_htlcs.insert(payment_hash.0));
3327 _ => panic!("Unexpected event"),
3330 Event::PaymentFailed { ref payment_hash, .. } => {
3331 assert!(failed_htlcs.insert(payment_hash.0));
3333 _ => panic!("Unexpected event"),
3336 _ => panic!("Unexpected event"),
3339 assert!(failed_htlcs.contains(&first_payment_hash.0));
3340 assert!(failed_htlcs.contains(&second_payment_hash.0));
3341 assert!(failed_htlcs.contains(&third_payment_hash.0));
3345 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3346 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3347 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3348 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3349 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3353 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3354 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3355 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3356 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3357 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3361 fn fail_backward_pending_htlc_upon_channel_failure() {
3362 let chanmon_cfgs = create_chanmon_cfgs(2);
3363 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3364 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3365 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3366 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3367 let logger = test_utils::TestLogger::new();
3369 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3371 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3372 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3373 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();
3374 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3375 check_added_monitors!(nodes[0], 1);
3377 let payment_event = {
3378 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3379 assert_eq!(events.len(), 1);
3380 SendEvent::from_event(events.remove(0))
3382 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3383 assert_eq!(payment_event.msgs.len(), 1);
3386 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3387 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3389 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3390 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();
3391 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3392 check_added_monitors!(nodes[0], 0);
3394 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3397 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3399 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3401 let secp_ctx = Secp256k1::new();
3402 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3403 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3404 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3405 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();
3406 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3407 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3408 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3410 // Send a 0-msat update_add_htlc to fail the channel.
3411 let update_add_htlc = msgs::UpdateAddHTLC {
3417 onion_routing_packet,
3419 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3422 // Check that Alice fails backward the pending HTLC from the second payment.
3423 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3424 check_closed_broadcast!(nodes[0], true);
3425 check_added_monitors!(nodes[0], 1);
3429 fn test_htlc_ignore_latest_remote_commitment() {
3430 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3431 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3432 let chanmon_cfgs = create_chanmon_cfgs(2);
3433 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3434 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3435 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3436 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3438 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3439 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3440 check_closed_broadcast!(nodes[0], false);
3441 check_added_monitors!(nodes[0], 1);
3443 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3444 assert_eq!(node_txn.len(), 2);
3446 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3447 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3448 check_closed_broadcast!(nodes[1], false);
3449 check_added_monitors!(nodes[1], 1);
3451 // Duplicate the connect_block call since this may happen due to other listeners
3452 // registering new transactions
3453 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3457 fn test_force_close_fail_back() {
3458 // Check which HTLCs are failed-backwards on channel force-closure
3459 let chanmon_cfgs = create_chanmon_cfgs(3);
3460 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3461 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3462 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3463 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3464 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3465 let logger = test_utils::TestLogger::new();
3467 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3469 let mut payment_event = {
3470 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3471 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();
3472 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3473 check_added_monitors!(nodes[0], 1);
3475 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3476 assert_eq!(events.len(), 1);
3477 SendEvent::from_event(events.remove(0))
3480 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3481 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3483 expect_pending_htlcs_forwardable!(nodes[1]);
3485 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3486 assert_eq!(events_2.len(), 1);
3487 payment_event = SendEvent::from_event(events_2.remove(0));
3488 assert_eq!(payment_event.msgs.len(), 1);
3490 check_added_monitors!(nodes[1], 1);
3491 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3492 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3493 check_added_monitors!(nodes[2], 1);
3494 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3496 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3497 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3498 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3500 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3501 check_closed_broadcast!(nodes[2], false);
3502 check_added_monitors!(nodes[2], 1);
3504 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3505 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3506 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3507 // back to nodes[1] upon timeout otherwise.
3508 assert_eq!(node_txn.len(), 1);
3513 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3514 txdata: vec![tx.clone()],
3516 connect_block(&nodes[1], &block, 1);
3518 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3519 check_closed_broadcast!(nodes[1], false);
3520 check_added_monitors!(nodes[1], 1);
3522 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3524 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3525 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3526 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3528 connect_block(&nodes[2], &block, 1);
3529 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3530 assert_eq!(node_txn.len(), 1);
3531 assert_eq!(node_txn[0].input.len(), 1);
3532 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3533 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3534 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3536 check_spends!(node_txn[0], tx);
3540 fn test_unconf_chan() {
3541 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3542 let chanmon_cfgs = create_chanmon_cfgs(2);
3543 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3544 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3545 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3546 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3548 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3549 assert_eq!(channel_state.by_id.len(), 1);
3550 assert_eq!(channel_state.short_to_id.len(), 1);
3551 mem::drop(channel_state);
3553 let mut headers = Vec::new();
3554 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3555 headers.push(header.clone());
3557 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3558 headers.push(header.clone());
3560 while !headers.is_empty() {
3561 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3563 check_closed_broadcast!(nodes[0], false);
3564 check_added_monitors!(nodes[0], 1);
3565 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3566 assert_eq!(channel_state.by_id.len(), 0);
3567 assert_eq!(channel_state.short_to_id.len(), 0);
3571 fn test_simple_peer_disconnect() {
3572 // Test that we can reconnect when there are no lost messages
3573 let chanmon_cfgs = create_chanmon_cfgs(3);
3574 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3575 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3576 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3577 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3578 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3582 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3585 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3586 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3587 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3591 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3593 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3594 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3596 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3598 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3599 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3601 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3602 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3604 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3606 let events = nodes[0].node.get_and_clear_pending_events();
3607 assert_eq!(events.len(), 2);
3609 Event::PaymentSent { payment_preimage } => {
3610 assert_eq!(payment_preimage, payment_preimage_3);
3612 _ => panic!("Unexpected event"),
3615 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3616 assert_eq!(payment_hash, payment_hash_5);
3617 assert!(rejected_by_dest);
3619 _ => panic!("Unexpected event"),
3623 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3624 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3627 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3628 // Test that we can reconnect when in-flight HTLC updates get dropped
3629 let chanmon_cfgs = create_chanmon_cfgs(2);
3630 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3631 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3632 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3633 if messages_delivered == 0 {
3634 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3635 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3637 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3640 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3642 let logger = test_utils::TestLogger::new();
3643 let payment_event = {
3644 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3645 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3646 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3647 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3648 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3649 check_added_monitors!(nodes[0], 1);
3651 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3652 assert_eq!(events.len(), 1);
3653 SendEvent::from_event(events.remove(0))
3655 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3657 if messages_delivered < 2 {
3658 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3660 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3661 if messages_delivered >= 3 {
3662 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3663 check_added_monitors!(nodes[1], 1);
3664 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3666 if messages_delivered >= 4 {
3667 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3668 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3669 check_added_monitors!(nodes[0], 1);
3671 if messages_delivered >= 5 {
3672 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3673 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3674 // No commitment_signed so get_event_msg's assert(len == 1) passes
3675 check_added_monitors!(nodes[0], 1);
3677 if messages_delivered >= 6 {
3678 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3679 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3680 check_added_monitors!(nodes[1], 1);
3687 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3688 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3689 if messages_delivered < 3 {
3690 // Even if the funding_locked messages get exchanged, as long as nothing further was
3691 // received on either side, both sides will need to resend them.
3692 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3693 } else if messages_delivered == 3 {
3694 // nodes[0] still wants its RAA + commitment_signed
3695 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3696 } else if messages_delivered == 4 {
3697 // nodes[0] still wants its commitment_signed
3698 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3699 } else if messages_delivered == 5 {
3700 // nodes[1] still wants its final RAA
3701 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3702 } else if messages_delivered == 6 {
3703 // Everything was delivered...
3704 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3707 let events_1 = nodes[1].node.get_and_clear_pending_events();
3708 assert_eq!(events_1.len(), 1);
3710 Event::PendingHTLCsForwardable { .. } => { },
3711 _ => panic!("Unexpected event"),
3714 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3715 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3716 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3718 nodes[1].node.process_pending_htlc_forwards();
3720 let events_2 = nodes[1].node.get_and_clear_pending_events();
3721 assert_eq!(events_2.len(), 1);
3723 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3724 assert_eq!(payment_hash_1, *payment_hash);
3725 assert_eq!(*payment_secret, None);
3726 assert_eq!(amt, 1000000);
3728 _ => panic!("Unexpected event"),
3731 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3732 check_added_monitors!(nodes[1], 1);
3734 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3735 assert_eq!(events_3.len(), 1);
3736 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3737 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3738 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3739 assert!(updates.update_add_htlcs.is_empty());
3740 assert!(updates.update_fail_htlcs.is_empty());
3741 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3742 assert!(updates.update_fail_malformed_htlcs.is_empty());
3743 assert!(updates.update_fee.is_none());
3744 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3746 _ => panic!("Unexpected event"),
3749 if messages_delivered >= 1 {
3750 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3752 let events_4 = nodes[0].node.get_and_clear_pending_events();
3753 assert_eq!(events_4.len(), 1);
3755 Event::PaymentSent { ref payment_preimage } => {
3756 assert_eq!(payment_preimage_1, *payment_preimage);
3758 _ => panic!("Unexpected event"),
3761 if messages_delivered >= 2 {
3762 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3763 check_added_monitors!(nodes[0], 1);
3764 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3766 if messages_delivered >= 3 {
3767 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3768 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3769 check_added_monitors!(nodes[1], 1);
3771 if messages_delivered >= 4 {
3772 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3773 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3774 // No commitment_signed so get_event_msg's assert(len == 1) passes
3775 check_added_monitors!(nodes[1], 1);
3777 if messages_delivered >= 5 {
3778 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3779 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3780 check_added_monitors!(nodes[0], 1);
3787 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3788 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3789 if messages_delivered < 2 {
3790 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3791 //TODO: Deduplicate PaymentSent events, then enable this if:
3792 //if messages_delivered < 1 {
3793 let events_4 = nodes[0].node.get_and_clear_pending_events();
3794 assert_eq!(events_4.len(), 1);
3796 Event::PaymentSent { ref payment_preimage } => {
3797 assert_eq!(payment_preimage_1, *payment_preimage);
3799 _ => panic!("Unexpected event"),
3802 } else if messages_delivered == 2 {
3803 // nodes[0] still wants its RAA + commitment_signed
3804 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3805 } else if messages_delivered == 3 {
3806 // nodes[0] still wants its commitment_signed
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3808 } else if messages_delivered == 4 {
3809 // nodes[1] still wants its final RAA
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3811 } else if messages_delivered == 5 {
3812 // Everything was delivered...
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3816 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3817 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3818 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3820 // Channel should still work fine...
3821 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3822 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3823 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3824 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3825 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3826 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3830 fn test_drop_messages_peer_disconnect_a() {
3831 do_test_drop_messages_peer_disconnect(0);
3832 do_test_drop_messages_peer_disconnect(1);
3833 do_test_drop_messages_peer_disconnect(2);
3834 do_test_drop_messages_peer_disconnect(3);
3838 fn test_drop_messages_peer_disconnect_b() {
3839 do_test_drop_messages_peer_disconnect(4);
3840 do_test_drop_messages_peer_disconnect(5);
3841 do_test_drop_messages_peer_disconnect(6);
3845 fn test_funding_peer_disconnect() {
3846 // Test that we can lock in our funding tx while disconnected
3847 let chanmon_cfgs = create_chanmon_cfgs(2);
3848 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3849 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3850 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3851 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3853 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3854 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3856 confirm_transaction(&nodes[0], &tx);
3857 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3858 assert_eq!(events_1.len(), 1);
3860 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3861 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3863 _ => panic!("Unexpected event"),
3866 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3868 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3869 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3871 confirm_transaction(&nodes[1], &tx);
3872 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3873 assert_eq!(events_2.len(), 2);
3874 let funding_locked = match events_2[0] {
3875 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3876 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3879 _ => panic!("Unexpected event"),
3881 let bs_announcement_sigs = match events_2[1] {
3882 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3883 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3886 _ => panic!("Unexpected event"),
3889 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3891 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3892 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3893 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3894 assert_eq!(events_3.len(), 2);
3895 let as_announcement_sigs = match events_3[0] {
3896 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3897 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3900 _ => panic!("Unexpected event"),
3902 let (as_announcement, as_update) = match events_3[1] {
3903 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3904 (msg.clone(), update_msg.clone())
3906 _ => panic!("Unexpected event"),
3909 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3910 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3911 assert_eq!(events_4.len(), 1);
3912 let (_, bs_update) = match events_4[0] {
3913 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3914 (msg.clone(), update_msg.clone())
3916 _ => panic!("Unexpected event"),
3919 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3920 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3921 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3923 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3924 let logger = test_utils::TestLogger::new();
3925 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();
3926 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3927 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3931 fn test_drop_messages_peer_disconnect_dual_htlc() {
3932 // Test that we can handle reconnecting when both sides of a channel have pending
3933 // commitment_updates when we disconnect.
3934 let chanmon_cfgs = create_chanmon_cfgs(2);
3935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3937 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3938 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3939 let logger = test_utils::TestLogger::new();
3941 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3943 // Now try to send a second payment which will fail to send
3944 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3945 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3946 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();
3947 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3948 check_added_monitors!(nodes[0], 1);
3950 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3951 assert_eq!(events_1.len(), 1);
3953 MessageSendEvent::UpdateHTLCs { .. } => {},
3954 _ => panic!("Unexpected event"),
3957 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3958 check_added_monitors!(nodes[1], 1);
3960 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3961 assert_eq!(events_2.len(), 1);
3963 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 } } => {
3964 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3965 assert!(update_add_htlcs.is_empty());
3966 assert_eq!(update_fulfill_htlcs.len(), 1);
3967 assert!(update_fail_htlcs.is_empty());
3968 assert!(update_fail_malformed_htlcs.is_empty());
3969 assert!(update_fee.is_none());
3971 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3972 let events_3 = nodes[0].node.get_and_clear_pending_events();
3973 assert_eq!(events_3.len(), 1);
3975 Event::PaymentSent { ref payment_preimage } => {
3976 assert_eq!(*payment_preimage, payment_preimage_1);
3978 _ => panic!("Unexpected event"),
3981 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3982 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3983 // No commitment_signed so get_event_msg's assert(len == 1) passes
3984 check_added_monitors!(nodes[0], 1);
3986 _ => panic!("Unexpected event"),
3989 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3990 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3992 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3993 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3994 assert_eq!(reestablish_1.len(), 1);
3995 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3996 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3997 assert_eq!(reestablish_2.len(), 1);
3999 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4000 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4001 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4002 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4004 assert!(as_resp.0.is_none());
4005 assert!(bs_resp.0.is_none());
4007 assert!(bs_resp.1.is_none());
4008 assert!(bs_resp.2.is_none());
4010 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4012 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4013 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4014 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4015 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4016 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4017 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4018 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4019 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4020 // No commitment_signed so get_event_msg's assert(len == 1) passes
4021 check_added_monitors!(nodes[1], 1);
4023 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4024 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4025 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4026 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4027 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4028 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4029 assert!(bs_second_commitment_signed.update_fee.is_none());
4030 check_added_monitors!(nodes[1], 1);
4032 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4033 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4034 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4035 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4036 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4037 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4038 assert!(as_commitment_signed.update_fee.is_none());
4039 check_added_monitors!(nodes[0], 1);
4041 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4042 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4043 // No commitment_signed so get_event_msg's assert(len == 1) passes
4044 check_added_monitors!(nodes[0], 1);
4046 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4047 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4048 // No commitment_signed so get_event_msg's assert(len == 1) passes
4049 check_added_monitors!(nodes[1], 1);
4051 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4052 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4053 check_added_monitors!(nodes[1], 1);
4055 expect_pending_htlcs_forwardable!(nodes[1]);
4057 let events_5 = nodes[1].node.get_and_clear_pending_events();
4058 assert_eq!(events_5.len(), 1);
4060 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4061 assert_eq!(payment_hash_2, *payment_hash);
4062 assert_eq!(*payment_secret, None);
4064 _ => panic!("Unexpected event"),
4067 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4068 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4069 check_added_monitors!(nodes[0], 1);
4071 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4074 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4075 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4076 // to avoid our counterparty failing the channel.
4077 let chanmon_cfgs = create_chanmon_cfgs(2);
4078 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4079 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4080 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4082 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4083 let logger = test_utils::TestLogger::new();
4085 let our_payment_hash = if send_partial_mpp {
4086 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4087 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();
4088 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4089 let payment_secret = PaymentSecret([0xdb; 32]);
4090 // Use the utility function send_payment_along_path to send the payment with MPP data which
4091 // indicates there are more HTLCs coming.
4092 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4093 check_added_monitors!(nodes[0], 1);
4094 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4095 assert_eq!(events.len(), 1);
4096 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4097 // hop should *not* yet generate any PaymentReceived event(s).
4098 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4101 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4104 let mut block = Block {
4105 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4108 connect_block(&nodes[0], &block, 101);
4109 connect_block(&nodes[1], &block, 101);
4110 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4111 block.header.prev_blockhash = block.block_hash();
4112 connect_block(&nodes[0], &block, i);
4113 connect_block(&nodes[1], &block, i);
4116 expect_pending_htlcs_forwardable!(nodes[1]);
4118 check_added_monitors!(nodes[1], 1);
4119 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4120 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4121 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4122 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4123 assert!(htlc_timeout_updates.update_fee.is_none());
4125 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4126 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4127 // 100_000 msat as u64, followed by a height of 123 as u32
4128 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4129 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4130 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4134 fn test_htlc_timeout() {
4135 do_test_htlc_timeout(true);
4136 do_test_htlc_timeout(false);
4139 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4140 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4141 let chanmon_cfgs = create_chanmon_cfgs(3);
4142 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4143 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4144 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4145 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4146 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4147 let logger = test_utils::TestLogger::new();
4149 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4150 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4152 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4153 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();
4154 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4156 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4157 check_added_monitors!(nodes[1], 1);
4159 // Now attempt to route a second payment, which should be placed in the holding cell
4160 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4162 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4163 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();
4164 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4165 check_added_monitors!(nodes[0], 1);
4166 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4167 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4168 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4169 expect_pending_htlcs_forwardable!(nodes[1]);
4170 check_added_monitors!(nodes[1], 0);
4172 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4173 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();
4174 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4175 check_added_monitors!(nodes[1], 0);
4178 let mut block = Block {
4179 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4182 connect_block(&nodes[1], &block, 101);
4183 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4184 block.header.prev_blockhash = block.block_hash();
4185 connect_block(&nodes[1], &block, i);
4188 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4189 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4191 block.header.prev_blockhash = block.block_hash();
4192 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4195 expect_pending_htlcs_forwardable!(nodes[1]);
4196 check_added_monitors!(nodes[1], 1);
4197 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4198 assert_eq!(fail_commit.len(), 1);
4199 match fail_commit[0] {
4200 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4201 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4202 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4204 _ => unreachable!(),
4206 expect_payment_failed!(nodes[0], second_payment_hash, false);
4207 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4209 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4210 _ => panic!("Unexpected event"),
4213 panic!("Unexpected event");
4216 expect_payment_failed!(nodes[1], second_payment_hash, true);
4221 fn test_holding_cell_htlc_add_timeouts() {
4222 do_test_holding_cell_htlc_add_timeouts(false);
4223 do_test_holding_cell_htlc_add_timeouts(true);
4227 fn test_invalid_channel_announcement() {
4228 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4229 let secp_ctx = Secp256k1::new();
4230 let chanmon_cfgs = create_chanmon_cfgs(2);
4231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4235 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4237 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4238 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4239 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4240 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4242 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 } );
4244 let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4245 let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4247 let as_network_key = nodes[0].node.get_our_node_id();
4248 let bs_network_key = nodes[1].node.get_our_node_id();
4250 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4252 let mut chan_announcement;
4254 macro_rules! dummy_unsigned_msg {
4256 msgs::UnsignedChannelAnnouncement {
4257 features: ChannelFeatures::known(),
4258 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4259 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4260 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4261 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4262 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4263 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4264 excess_data: Vec::new(),
4269 macro_rules! sign_msg {
4270 ($unsigned_msg: expr) => {
4271 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4272 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4273 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4274 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4275 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4276 chan_announcement = msgs::ChannelAnnouncement {
4277 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4278 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4279 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4280 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4281 contents: $unsigned_msg
4286 let unsigned_msg = dummy_unsigned_msg!();
4287 sign_msg!(unsigned_msg);
4288 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4289 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 } );
4291 // Configured with Network::Testnet
4292 let mut unsigned_msg = dummy_unsigned_msg!();
4293 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4294 sign_msg!(unsigned_msg);
4295 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4297 let mut unsigned_msg = dummy_unsigned_msg!();
4298 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4299 sign_msg!(unsigned_msg);
4300 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4304 fn test_no_txn_manager_serialize_deserialize() {
4305 let chanmon_cfgs = create_chanmon_cfgs(2);
4306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4308 let logger: test_utils::TestLogger;
4309 let fee_estimator: test_utils::TestFeeEstimator;
4310 let new_chain_monitor: test_utils::TestChainMonitor;
4311 let keys_manager: test_utils::TestKeysInterface;
4312 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4313 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4315 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4317 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4319 let nodes_0_serialized = nodes[0].node.encode();
4320 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4321 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4323 logger = test_utils::TestLogger::new();
4324 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4325 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4326 nodes[0].chain_monitor = &new_chain_monitor;
4327 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4328 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4329 assert!(chan_0_monitor_read.is_empty());
4331 let mut nodes_0_read = &nodes_0_serialized[..];
4332 let config = UserConfig::default();
4333 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4334 let (_, nodes_0_deserialized_tmp) = {
4335 let mut channel_monitors = HashMap::new();
4336 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4337 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4338 default_config: config,
4339 keys_manager: &keys_manager,
4340 fee_estimator: &fee_estimator,
4341 chain_monitor: nodes[0].chain_monitor,
4342 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4347 nodes_0_deserialized = nodes_0_deserialized_tmp;
4348 assert!(nodes_0_read.is_empty());
4350 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4351 nodes[0].node = &nodes_0_deserialized;
4352 assert_eq!(nodes[0].node.list_channels().len(), 1);
4353 check_added_monitors!(nodes[0], 1);
4355 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4356 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4357 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4358 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4360 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4361 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4362 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4363 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4365 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4366 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4367 for node in nodes.iter() {
4368 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4369 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4370 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4373 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4377 fn test_manager_serialize_deserialize_events() {
4378 // This test makes sure the events field in ChannelManager survives de/serialization
4379 let chanmon_cfgs = create_chanmon_cfgs(2);
4380 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4381 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4382 let fee_estimator: test_utils::TestFeeEstimator;
4383 let logger: test_utils::TestLogger;
4384 let new_chain_monitor: test_utils::TestChainMonitor;
4385 let keys_manager: test_utils::TestKeysInterface;
4386 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4387 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4389 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4390 let channel_value = 100000;
4391 let push_msat = 10001;
4392 let a_flags = InitFeatures::known();
4393 let b_flags = InitFeatures::known();
4394 let node_a = nodes.pop().unwrap();
4395 let node_b = nodes.pop().unwrap();
4396 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4397 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()));
4398 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()));
4400 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4402 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4403 check_added_monitors!(node_a, 0);
4405 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()));
4407 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4408 assert_eq!(added_monitors.len(), 1);
4409 assert_eq!(added_monitors[0].0, funding_output);
4410 added_monitors.clear();
4413 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()));
4415 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4416 assert_eq!(added_monitors.len(), 1);
4417 assert_eq!(added_monitors[0].0, funding_output);
4418 added_monitors.clear();
4420 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4425 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4426 let nodes_0_serialized = nodes[0].node.encode();
4427 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4428 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4430 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4431 logger = test_utils::TestLogger::new();
4432 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4433 nodes[0].chain_monitor = &new_chain_monitor;
4434 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4435 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4436 assert!(chan_0_monitor_read.is_empty());
4438 let mut nodes_0_read = &nodes_0_serialized[..];
4439 let config = UserConfig::default();
4440 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4441 let (_, nodes_0_deserialized_tmp) = {
4442 let mut channel_monitors = HashMap::new();
4443 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4444 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4445 default_config: config,
4446 keys_manager: &keys_manager,
4447 fee_estimator: &fee_estimator,
4448 chain_monitor: nodes[0].chain_monitor,
4449 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4454 nodes_0_deserialized = nodes_0_deserialized_tmp;
4455 assert!(nodes_0_read.is_empty());
4457 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4459 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4460 nodes[0].node = &nodes_0_deserialized;
4462 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4463 let events_4 = nodes[0].node.get_and_clear_pending_events();
4464 assert_eq!(events_4.len(), 1);
4466 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4467 assert_eq!(user_channel_id, 42);
4468 assert_eq!(*funding_txo, funding_output);
4470 _ => panic!("Unexpected event"),
4473 // Make sure the channel is functioning as though the de/serialization never happened
4474 assert_eq!(nodes[0].node.list_channels().len(), 1);
4475 check_added_monitors!(nodes[0], 1);
4477 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4478 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4479 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4480 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4482 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4483 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4484 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4485 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4487 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4488 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4489 for node in nodes.iter() {
4490 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4491 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4492 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4495 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4499 fn test_simple_manager_serialize_deserialize() {
4500 let chanmon_cfgs = create_chanmon_cfgs(2);
4501 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4502 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4503 let logger: test_utils::TestLogger;
4504 let fee_estimator: test_utils::TestFeeEstimator;
4505 let new_chain_monitor: test_utils::TestChainMonitor;
4506 let keys_manager: test_utils::TestKeysInterface;
4507 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4508 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4509 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4511 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4512 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4514 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4516 let nodes_0_serialized = nodes[0].node.encode();
4517 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4518 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4520 logger = test_utils::TestLogger::new();
4521 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4522 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4523 nodes[0].chain_monitor = &new_chain_monitor;
4524 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4525 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4526 assert!(chan_0_monitor_read.is_empty());
4528 let mut nodes_0_read = &nodes_0_serialized[..];
4529 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4530 let (_, nodes_0_deserialized_tmp) = {
4531 let mut channel_monitors = HashMap::new();
4532 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4533 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4534 default_config: UserConfig::default(),
4535 keys_manager: &keys_manager,
4536 fee_estimator: &fee_estimator,
4537 chain_monitor: nodes[0].chain_monitor,
4538 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4543 nodes_0_deserialized = nodes_0_deserialized_tmp;
4544 assert!(nodes_0_read.is_empty());
4546 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4547 nodes[0].node = &nodes_0_deserialized;
4548 check_added_monitors!(nodes[0], 1);
4550 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4552 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4553 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4557 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4558 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4559 let chanmon_cfgs = create_chanmon_cfgs(4);
4560 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4561 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4562 let logger: test_utils::TestLogger;
4563 let fee_estimator: test_utils::TestFeeEstimator;
4564 let new_chain_monitor: test_utils::TestChainMonitor;
4565 let keys_manager: test_utils::TestKeysInterface;
4566 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4567 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4568 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4569 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4570 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4572 let mut node_0_stale_monitors_serialized = Vec::new();
4573 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4574 let mut writer = test_utils::TestVecWriter(Vec::new());
4575 monitor.1.write_for_disk(&mut writer).unwrap();
4576 node_0_stale_monitors_serialized.push(writer.0);
4579 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4581 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4582 let nodes_0_serialized = nodes[0].node.encode();
4584 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4585 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4586 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4587 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4589 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4591 let mut node_0_monitors_serialized = Vec::new();
4592 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4593 let mut writer = test_utils::TestVecWriter(Vec::new());
4594 monitor.1.write_for_disk(&mut writer).unwrap();
4595 node_0_monitors_serialized.push(writer.0);
4598 logger = test_utils::TestLogger::new();
4599 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4600 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4601 nodes[0].chain_monitor = &new_chain_monitor;
4603 let mut node_0_stale_monitors = Vec::new();
4604 for serialized in node_0_stale_monitors_serialized.iter() {
4605 let mut read = &serialized[..];
4606 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4607 assert!(read.is_empty());
4608 node_0_stale_monitors.push(monitor);
4611 let mut node_0_monitors = Vec::new();
4612 for serialized in node_0_monitors_serialized.iter() {
4613 let mut read = &serialized[..];
4614 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4615 assert!(read.is_empty());
4616 node_0_monitors.push(monitor);
4619 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4621 let mut nodes_0_read = &nodes_0_serialized[..];
4622 if let Err(msgs::DecodeError::InvalidValue) =
4623 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4624 default_config: UserConfig::default(),
4625 keys_manager: &keys_manager,
4626 fee_estimator: &fee_estimator,
4627 chain_monitor: nodes[0].chain_monitor,
4628 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4630 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4632 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4635 let mut nodes_0_read = &nodes_0_serialized[..];
4636 let (_, nodes_0_deserialized_tmp) =
4637 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4638 default_config: UserConfig::default(),
4639 keys_manager: &keys_manager,
4640 fee_estimator: &fee_estimator,
4641 chain_monitor: nodes[0].chain_monitor,
4642 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4644 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4646 nodes_0_deserialized = nodes_0_deserialized_tmp;
4647 assert!(nodes_0_read.is_empty());
4649 { // Channel close should result in a commitment tx and an HTLC tx
4650 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4651 assert_eq!(txn.len(), 2);
4652 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4653 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4656 for monitor in node_0_monitors.drain(..) {
4657 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4658 check_added_monitors!(nodes[0], 1);
4660 nodes[0].node = &nodes_0_deserialized;
4662 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4663 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4664 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4665 //... and we can even still claim the payment!
4666 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4668 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4669 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4670 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4671 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4672 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4673 assert_eq!(msg_events.len(), 1);
4674 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4676 &ErrorAction::SendErrorMessage { ref msg } => {
4677 assert_eq!(msg.channel_id, channel_id);
4679 _ => panic!("Unexpected event!"),
4684 macro_rules! check_spendable_outputs {
4685 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4687 let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4688 let mut txn = Vec::new();
4689 for event in events {
4691 Event::SpendableOutputs { ref outputs } => {
4692 for outp in outputs {
4694 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4696 previous_output: outpoint.into_bitcoin_outpoint(),
4697 script_sig: Script::new(),
4699 witness: Vec::new(),
4702 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4703 value: output.value,
4705 let mut spend_tx = Transaction {
4711 let secp_ctx = Secp256k1::new();
4712 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4713 let remotepubkey = keys.pubkeys().payment_point;
4714 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4715 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4716 let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4717 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4718 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4719 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4722 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4724 previous_output: outpoint.into_bitcoin_outpoint(),
4725 script_sig: Script::new(),
4726 sequence: *to_self_delay as u32,
4727 witness: Vec::new(),
4730 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4731 value: output.value,
4733 let mut spend_tx = Transaction {
4739 let secp_ctx = Secp256k1::new();
4740 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4741 if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4743 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4744 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4745 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4746 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4747 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4748 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4749 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4750 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4754 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4755 let secp_ctx = Secp256k1::new();
4757 previous_output: outpoint.into_bitcoin_outpoint(),
4758 script_sig: Script::new(),
4760 witness: Vec::new(),
4763 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4764 value: output.value,
4766 let mut spend_tx = Transaction {
4770 output: vec![outp.clone()],
4773 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4775 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4777 Err(_) => panic!("Your RNG is busted"),
4780 Err(_) => panic!("Your rng is busted"),
4783 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4784 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4785 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4786 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4787 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4788 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4789 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4795 _ => panic!("Unexpected event"),
4804 fn test_claim_sizeable_push_msat() {
4805 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment 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 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4812 nodes[1].node.force_close_channel(&chan.2);
4813 check_closed_broadcast!(nodes[1], false);
4814 check_added_monitors!(nodes[1], 1);
4815 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4816 assert_eq!(node_txn.len(), 1);
4817 check_spends!(node_txn[0], chan.3);
4818 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
4820 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4821 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4822 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4824 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4825 assert_eq!(spend_txn.len(), 1);
4826 check_spends!(spend_txn[0], node_txn[0]);
4830 fn test_claim_on_remote_sizeable_push_msat() {
4831 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4832 // to_remote output is encumbered by a P2WPKH
4833 let chanmon_cfgs = create_chanmon_cfgs(2);
4834 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4835 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4836 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4838 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4839 nodes[0].node.force_close_channel(&chan.2);
4840 check_closed_broadcast!(nodes[0], false);
4841 check_added_monitors!(nodes[0], 1);
4843 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4844 assert_eq!(node_txn.len(), 1);
4845 check_spends!(node_txn[0], chan.3);
4846 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
4848 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4849 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4850 check_closed_broadcast!(nodes[1], false);
4851 check_added_monitors!(nodes[1], 1);
4852 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4854 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4855 assert_eq!(spend_txn.len(), 1);
4856 check_spends!(spend_txn[0], node_txn[0]);
4860 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4861 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4862 // to_remote output is encumbered by a P2WPKH
4864 let chanmon_cfgs = create_chanmon_cfgs(2);
4865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4869 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4870 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4871 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4872 assert_eq!(revoked_local_txn[0].input.len(), 1);
4873 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4875 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4876 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4877 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4878 check_closed_broadcast!(nodes[1], false);
4879 check_added_monitors!(nodes[1], 1);
4881 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4882 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4883 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4884 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4886 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4887 assert_eq!(spend_txn.len(), 2);
4888 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4889 check_spends!(spend_txn[1], node_txn[0]);
4893 fn test_static_spendable_outputs_preimage_tx() {
4894 let chanmon_cfgs = create_chanmon_cfgs(2);
4895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4899 // Create some initial channels
4900 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4902 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4904 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4905 assert_eq!(commitment_tx[0].input.len(), 1);
4906 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4908 // Settle A's commitment tx on B's chain
4909 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4910 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4911 check_added_monitors!(nodes[1], 1);
4912 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4913 check_added_monitors!(nodes[1], 1);
4914 let events = nodes[1].node.get_and_clear_pending_msg_events();
4916 MessageSendEvent::UpdateHTLCs { .. } => {},
4917 _ => panic!("Unexpected event"),
4920 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4921 _ => panic!("Unexepected event"),
4924 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4925 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4926 assert_eq!(node_txn.len(), 3);
4927 check_spends!(node_txn[0], commitment_tx[0]);
4928 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4929 check_spends!(node_txn[1], chan_1.3);
4930 check_spends!(node_txn[2], node_txn[1]);
4932 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4933 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4934 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4936 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4937 assert_eq!(spend_txn.len(), 1);
4938 check_spends!(spend_txn[0], node_txn[0]);
4942 fn test_static_spendable_outputs_timeout_tx() {
4943 let chanmon_cfgs = create_chanmon_cfgs(2);
4944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4946 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4948 // Create some initial channels
4949 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4951 // Rebalance the network a bit by relaying one payment through all the channels ...
4952 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4954 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4956 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4957 assert_eq!(commitment_tx[0].input.len(), 1);
4958 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4960 // Settle A's commitment tx on B' chain
4961 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4962 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4963 check_added_monitors!(nodes[1], 1);
4964 let events = nodes[1].node.get_and_clear_pending_msg_events();
4966 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4967 _ => panic!("Unexpected event"),
4970 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4971 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4972 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4973 check_spends!(node_txn[0], commitment_tx[0].clone());
4974 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4975 check_spends!(node_txn[1], chan_1.3.clone());
4976 check_spends!(node_txn[2], node_txn[1]);
4978 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4979 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4980 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4981 expect_payment_failed!(nodes[1], our_payment_hash, true);
4983 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4984 assert_eq!(spend_txn.len(), 2); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4985 check_spends!(spend_txn[1], node_txn[0]);
4989 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4990 let chanmon_cfgs = create_chanmon_cfgs(2);
4991 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4992 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4993 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4995 // Create some initial channels
4996 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4998 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4999 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5000 assert_eq!(revoked_local_txn[0].input.len(), 1);
5001 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5003 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5005 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5006 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
5007 check_closed_broadcast!(nodes[1], false);
5008 check_added_monitors!(nodes[1], 1);
5010 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5011 assert_eq!(node_txn.len(), 2);
5012 assert_eq!(node_txn[0].input.len(), 2);
5013 check_spends!(node_txn[0], revoked_local_txn[0]);
5015 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5016 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
5017 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5019 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5020 assert_eq!(spend_txn.len(), 1);
5021 check_spends!(spend_txn[0], node_txn[0]);
5025 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5026 let chanmon_cfgs = create_chanmon_cfgs(2);
5027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5029 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5031 // Create some initial channels
5032 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5034 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5035 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5036 assert_eq!(revoked_local_txn[0].input.len(), 1);
5037 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5039 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5041 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5042 // A will generate HTLC-Timeout from revoked commitment tx
5043 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5044 check_closed_broadcast!(nodes[0], false);
5045 check_added_monitors!(nodes[0], 1);
5047 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5048 assert_eq!(revoked_htlc_txn.len(), 2);
5049 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5050 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5051 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5052 check_spends!(revoked_htlc_txn[1], chan_1.3);
5054 // B will generate justice tx from A's revoked commitment/HTLC tx
5055 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5056 check_closed_broadcast!(nodes[1], false);
5057 check_added_monitors!(nodes[1], 1);
5059 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5060 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5061 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5062 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5063 // transactions next...
5064 assert_eq!(node_txn[0].input.len(), 3);
5065 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5067 assert_eq!(node_txn[1].input.len(), 2);
5068 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5069 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5070 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5072 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5073 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5076 assert_eq!(node_txn[2].input.len(), 1);
5077 check_spends!(node_txn[2], chan_1.3);
5079 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5080 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5081 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5083 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5084 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5085 assert_eq!(spend_txn.len(), 1);
5086 assert_eq!(spend_txn[0].input.len(), 1);
5087 check_spends!(spend_txn[0], node_txn[1]);
5091 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5092 let chanmon_cfgs = create_chanmon_cfgs(2);
5093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5097 // Create some initial channels
5098 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5100 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5101 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5102 assert_eq!(revoked_local_txn[0].input.len(), 1);
5103 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5105 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5106 assert_eq!(revoked_local_txn[0].output.len(), 2);
5108 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5110 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5111 // B will generate HTLC-Success from revoked commitment tx
5112 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5113 check_closed_broadcast!(nodes[1], false);
5114 check_added_monitors!(nodes[1], 1);
5115 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5117 assert_eq!(revoked_htlc_txn.len(), 2);
5118 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5119 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5120 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5122 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5123 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5124 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5126 // A will generate justice tx from B's revoked commitment/HTLC tx
5127 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5128 check_closed_broadcast!(nodes[0], false);
5129 check_added_monitors!(nodes[0], 1);
5131 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5132 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5134 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5135 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5136 // transactions next...
5137 assert_eq!(node_txn[0].input.len(), 2);
5138 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5139 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5140 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5142 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5143 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5146 assert_eq!(node_txn[1].input.len(), 1);
5147 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5149 check_spends!(node_txn[2], chan_1.3);
5151 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5152 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5153 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5155 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5156 // didn't try to generate any new transactions.
5158 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5159 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5160 assert_eq!(spend_txn.len(), 2);
5161 assert_eq!(spend_txn[0].input.len(), 1);
5162 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5163 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5164 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5168 fn test_onchain_to_onchain_claim() {
5169 // Test that in case of channel closure, we detect the state of output and claim HTLC
5170 // on downstream peer's remote commitment tx.
5171 // First, have C claim an HTLC against its own latest commitment transaction.
5172 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5174 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5177 let chanmon_cfgs = create_chanmon_cfgs(3);
5178 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5179 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5180 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5182 // Create some initial channels
5183 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5184 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5186 // Rebalance the network a bit by relaying one payment through all the channels ...
5187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5190 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5191 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5192 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5193 check_spends!(commitment_tx[0], chan_2.3);
5194 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5195 check_added_monitors!(nodes[2], 1);
5196 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5197 assert!(updates.update_add_htlcs.is_empty());
5198 assert!(updates.update_fail_htlcs.is_empty());
5199 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5200 assert!(updates.update_fail_malformed_htlcs.is_empty());
5202 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5203 check_closed_broadcast!(nodes[2], false);
5204 check_added_monitors!(nodes[2], 1);
5206 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5207 assert_eq!(c_txn.len(), 3);
5208 assert_eq!(c_txn[0], c_txn[2]);
5209 assert_eq!(commitment_tx[0], c_txn[1]);
5210 check_spends!(c_txn[1], chan_2.3);
5211 check_spends!(c_txn[2], c_txn[1]);
5212 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5213 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5214 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5215 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5217 // 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
5218 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5220 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5221 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5222 assert_eq!(b_txn.len(), 3);
5223 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5224 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5225 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5226 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5227 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5228 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5229 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5230 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5231 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5234 check_added_monitors!(nodes[1], 1);
5235 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5236 check_added_monitors!(nodes[1], 1);
5237 match msg_events[0] {
5238 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5239 _ => panic!("Unexpected event"),
5241 match msg_events[1] {
5242 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, .. } } => {
5243 assert!(update_add_htlcs.is_empty());
5244 assert!(update_fail_htlcs.is_empty());
5245 assert_eq!(update_fulfill_htlcs.len(), 1);
5246 assert!(update_fail_malformed_htlcs.is_empty());
5247 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5249 _ => panic!("Unexpected event"),
5251 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5252 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5253 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5254 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5255 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5256 assert_eq!(b_txn.len(), 3);
5257 check_spends!(b_txn[1], chan_1.3);
5258 check_spends!(b_txn[2], b_txn[1]);
5259 check_spends!(b_txn[0], commitment_tx[0]);
5260 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5261 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5262 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5264 check_closed_broadcast!(nodes[1], false);
5265 check_added_monitors!(nodes[1], 1);
5269 fn test_duplicate_payment_hash_one_failure_one_success() {
5270 // Topology : A --> B --> C
5271 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5272 let chanmon_cfgs = create_chanmon_cfgs(3);
5273 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5274 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5275 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5277 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5278 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5280 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5281 *nodes[0].network_payment_count.borrow_mut() -= 1;
5282 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5284 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5285 assert_eq!(commitment_txn[0].input.len(), 1);
5286 check_spends!(commitment_txn[0], chan_2.3);
5288 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5289 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5290 check_closed_broadcast!(nodes[1], false);
5291 check_added_monitors!(nodes[1], 1);
5293 let htlc_timeout_tx;
5294 { // Extract one of the two HTLC-Timeout transaction
5295 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5296 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5297 assert_eq!(node_txn.len(), 5);
5298 check_spends!(node_txn[0], commitment_txn[0]);
5299 assert_eq!(node_txn[0].input.len(), 1);
5300 check_spends!(node_txn[1], commitment_txn[0]);
5301 assert_eq!(node_txn[1].input.len(), 1);
5302 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5303 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5304 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5305 check_spends!(node_txn[2], chan_2.3);
5306 check_spends!(node_txn[3], node_txn[2]);
5307 check_spends!(node_txn[4], node_txn[2]);
5308 htlc_timeout_tx = node_txn[1].clone();
5311 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5312 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5313 check_added_monitors!(nodes[2], 3);
5314 let events = nodes[2].node.get_and_clear_pending_msg_events();
5316 MessageSendEvent::UpdateHTLCs { .. } => {},
5317 _ => panic!("Unexpected event"),
5320 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5321 _ => panic!("Unexepected event"),
5323 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5324 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)
5325 check_spends!(htlc_success_txn[2], chan_2.3);
5326 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5327 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5328 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5329 assert_eq!(htlc_success_txn[0].input.len(), 1);
5330 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5331 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5332 assert_eq!(htlc_success_txn[1].input.len(), 1);
5333 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5334 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5335 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5336 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5338 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5339 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5340 expect_pending_htlcs_forwardable!(nodes[1]);
5341 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5342 assert!(htlc_updates.update_add_htlcs.is_empty());
5343 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5344 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5345 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5346 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5347 check_added_monitors!(nodes[1], 1);
5349 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5350 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5352 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5353 let events = nodes[0].node.get_and_clear_pending_msg_events();
5354 assert_eq!(events.len(), 1);
5356 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5358 _ => { panic!("Unexpected event"); }
5361 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5363 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5364 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5365 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5366 assert!(updates.update_add_htlcs.is_empty());
5367 assert!(updates.update_fail_htlcs.is_empty());
5368 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5369 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5370 assert!(updates.update_fail_malformed_htlcs.is_empty());
5371 check_added_monitors!(nodes[1], 1);
5373 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5374 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5376 let events = nodes[0].node.get_and_clear_pending_events();
5378 Event::PaymentSent { ref payment_preimage } => {
5379 assert_eq!(*payment_preimage, our_payment_preimage);
5381 _ => panic!("Unexpected event"),
5386 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5387 let chanmon_cfgs = create_chanmon_cfgs(2);
5388 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5389 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5390 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5392 // Create some initial channels
5393 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5395 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5396 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5397 assert_eq!(local_txn[0].input.len(), 1);
5398 check_spends!(local_txn[0], chan_1.3);
5400 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5401 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5402 check_added_monitors!(nodes[1], 1);
5403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5404 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5405 check_added_monitors!(nodes[1], 1);
5406 let events = nodes[1].node.get_and_clear_pending_msg_events();
5408 MessageSendEvent::UpdateHTLCs { .. } => {},
5409 _ => panic!("Unexpected event"),
5412 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5413 _ => panic!("Unexepected event"),
5416 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5417 assert_eq!(node_txn[0].input.len(), 1);
5418 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5419 check_spends!(node_txn[0], local_txn[0]);
5420 vec![node_txn[0].clone(), node_txn[2].clone()]
5423 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5424 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5425 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5427 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5428 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5429 assert_eq!(spend_txn.len(), 2);
5430 check_spends!(spend_txn[0], node_txn[0]);
5431 check_spends!(spend_txn[1], node_txn[1]);
5434 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5435 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5436 // unrevoked commitment transaction.
5437 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5438 // a remote RAA before they could be failed backwards (and combinations thereof).
5439 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5440 // use the same payment hashes.
5441 // Thus, we use a six-node network:
5446 // And test where C fails back to A/B when D announces its latest commitment transaction
5447 let chanmon_cfgs = create_chanmon_cfgs(6);
5448 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5449 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5450 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5451 let logger = test_utils::TestLogger::new();
5453 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5454 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5455 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5456 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5457 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5459 // Rebalance and check output sanity...
5460 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5461 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5462 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5464 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5466 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
5468 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
5469 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5470 let our_node_id = &nodes[1].node.get_our_node_id();
5471 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();
5473 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
5475 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
5477 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5479 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5480 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();
5482 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5484 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5487 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5489 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();
5490 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
5493 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
5495 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();
5496 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5498 // Double-check that six of the new HTLC were added
5499 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5500 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5501 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5502 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5504 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5505 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5506 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5507 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5508 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5509 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5510 check_added_monitors!(nodes[4], 0);
5511 expect_pending_htlcs_forwardable!(nodes[4]);
5512 check_added_monitors!(nodes[4], 1);
5514 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5515 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5516 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5517 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5518 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5519 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5521 // Fail 3rd below-dust and 7th above-dust HTLCs
5522 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5523 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5524 check_added_monitors!(nodes[5], 0);
5525 expect_pending_htlcs_forwardable!(nodes[5]);
5526 check_added_monitors!(nodes[5], 1);
5528 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5529 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5530 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5531 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5533 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5535 expect_pending_htlcs_forwardable!(nodes[3]);
5536 check_added_monitors!(nodes[3], 1);
5537 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5538 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5539 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5540 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5541 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5542 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5543 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5544 if deliver_last_raa {
5545 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5547 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5550 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5551 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5552 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5553 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5555 // We now broadcast the latest commitment transaction, which *should* result in failures for
5556 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5557 // the non-broadcast above-dust HTLCs.
5559 // Alternatively, we may broadcast the previous commitment transaction, which should only
5560 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5561 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5563 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5564 if announce_latest {
5565 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5567 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5569 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5570 check_closed_broadcast!(nodes[2], false);
5571 expect_pending_htlcs_forwardable!(nodes[2]);
5572 check_added_monitors!(nodes[2], 3);
5574 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5575 assert_eq!(cs_msgs.len(), 2);
5576 let mut a_done = false;
5577 for msg in cs_msgs {
5579 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5580 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5581 // should be failed-backwards here.
5582 let target = if *node_id == nodes[0].node.get_our_node_id() {
5583 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5584 for htlc in &updates.update_fail_htlcs {
5585 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 });
5587 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5592 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5593 for htlc in &updates.update_fail_htlcs {
5594 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5596 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5597 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5600 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5601 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5602 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5603 if announce_latest {
5604 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5605 if *node_id == nodes[0].node.get_our_node_id() {
5606 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5609 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5611 _ => panic!("Unexpected event"),
5615 let as_events = nodes[0].node.get_and_clear_pending_events();
5616 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5617 let mut as_failds = HashSet::new();
5618 for event in as_events.iter() {
5619 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5620 assert!(as_failds.insert(*payment_hash));
5621 if *payment_hash != payment_hash_2 {
5622 assert_eq!(*rejected_by_dest, deliver_last_raa);
5624 assert!(!rejected_by_dest);
5626 } else { panic!("Unexpected event"); }
5628 assert!(as_failds.contains(&payment_hash_1));
5629 assert!(as_failds.contains(&payment_hash_2));
5630 if announce_latest {
5631 assert!(as_failds.contains(&payment_hash_3));
5632 assert!(as_failds.contains(&payment_hash_5));
5634 assert!(as_failds.contains(&payment_hash_6));
5636 let bs_events = nodes[1].node.get_and_clear_pending_events();
5637 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5638 let mut bs_failds = HashSet::new();
5639 for event in bs_events.iter() {
5640 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5641 assert!(bs_failds.insert(*payment_hash));
5642 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5643 assert_eq!(*rejected_by_dest, deliver_last_raa);
5645 assert!(!rejected_by_dest);
5647 } else { panic!("Unexpected event"); }
5649 assert!(bs_failds.contains(&payment_hash_1));
5650 assert!(bs_failds.contains(&payment_hash_2));
5651 if announce_latest {
5652 assert!(bs_failds.contains(&payment_hash_4));
5654 assert!(bs_failds.contains(&payment_hash_5));
5656 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5657 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5658 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5659 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5660 // PaymentFailureNetworkUpdates.
5661 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5662 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5663 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5664 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5665 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5667 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5668 _ => panic!("Unexpected event"),
5674 fn test_fail_backwards_latest_remote_announce_a() {
5675 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5679 fn test_fail_backwards_latest_remote_announce_b() {
5680 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5684 fn test_fail_backwards_previous_remote_announce() {
5685 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5686 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5687 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5691 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5692 let chanmon_cfgs = create_chanmon_cfgs(2);
5693 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5694 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5695 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5697 // Create some initial channels
5698 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5700 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5701 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5702 assert_eq!(local_txn[0].input.len(), 1);
5703 check_spends!(local_txn[0], chan_1.3);
5705 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5706 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5707 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5708 check_closed_broadcast!(nodes[0], false);
5709 check_added_monitors!(nodes[0], 1);
5711 let htlc_timeout = {
5712 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5713 assert_eq!(node_txn[0].input.len(), 1);
5714 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5715 check_spends!(node_txn[0], local_txn[0]);
5719 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5720 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5721 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5722 expect_payment_failed!(nodes[0], our_payment_hash, true);
5724 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5725 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5726 assert_eq!(spend_txn.len(), 2);
5727 check_spends!(spend_txn[0], local_txn[0]);
5728 check_spends!(spend_txn[1], htlc_timeout);
5732 fn test_key_derivation_params() {
5733 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5734 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5735 // let us re-derive the channel key set to then derive a delayed_payment_key.
5737 let chanmon_cfgs = create_chanmon_cfgs(3);
5739 // We manually create the node configuration to backup the seed.
5740 let seed = [42; 32];
5741 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5742 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);
5743 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, node_seed: seed };
5744 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5745 node_cfgs.remove(0);
5746 node_cfgs.insert(0, node);
5748 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5749 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5751 // Create some initial channels
5752 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5754 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5755 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5756 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5758 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5759 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5760 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5761 assert_eq!(local_txn_1[0].input.len(), 1);
5762 check_spends!(local_txn_1[0], chan_1.3);
5764 // We check funding pubkey are unique
5765 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]));
5766 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]));
5767 if from_0_funding_key_0 == from_1_funding_key_0
5768 || from_0_funding_key_0 == from_1_funding_key_1
5769 || from_0_funding_key_1 == from_1_funding_key_0
5770 || from_0_funding_key_1 == from_1_funding_key_1 {
5771 panic!("Funding pubkeys aren't unique");
5774 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5775 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5776 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5777 check_closed_broadcast!(nodes[0], false);
5778 check_added_monitors!(nodes[0], 1);
5780 let htlc_timeout = {
5781 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5782 assert_eq!(node_txn[0].input.len(), 1);
5783 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5784 check_spends!(node_txn[0], local_txn_1[0]);
5788 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5789 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5790 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5791 expect_payment_failed!(nodes[0], our_payment_hash, true);
5793 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5794 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5795 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5796 assert_eq!(spend_txn.len(), 2);
5797 check_spends!(spend_txn[0], local_txn_1[0]);
5798 check_spends!(spend_txn[1], htlc_timeout);
5802 fn test_static_output_closing_tx() {
5803 let chanmon_cfgs = create_chanmon_cfgs(2);
5804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5806 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5808 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5810 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5811 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5813 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5814 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5815 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5817 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5818 assert_eq!(spend_txn.len(), 1);
5819 check_spends!(spend_txn[0], closing_tx);
5821 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5822 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5824 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5825 assert_eq!(spend_txn.len(), 1);
5826 check_spends!(spend_txn[0], closing_tx);
5829 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5830 let chanmon_cfgs = create_chanmon_cfgs(2);
5831 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5833 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5834 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5836 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5838 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5839 // present in B's local commitment transaction, but none of A's commitment transactions.
5840 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
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_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5845 let events = nodes[0].node.get_and_clear_pending_events();
5846 assert_eq!(events.len(), 1);
5848 Event::PaymentSent { payment_preimage } => {
5849 assert_eq!(payment_preimage, our_payment_preimage);
5851 _ => panic!("Unexpected event"),
5854 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5855 check_added_monitors!(nodes[0], 1);
5856 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5857 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5858 check_added_monitors!(nodes[1], 1);
5860 let mut block = Block {
5861 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5864 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5865 connect_block(&nodes[1], &block, i);
5866 block.header.prev_blockhash = block.block_hash();
5868 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5869 check_closed_broadcast!(nodes[1], false);
5870 check_added_monitors!(nodes[1], 1);
5873 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5874 let chanmon_cfgs = create_chanmon_cfgs(2);
5875 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5876 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5877 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5878 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5879 let logger = test_utils::TestLogger::new();
5881 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5882 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5883 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();
5884 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5885 check_added_monitors!(nodes[0], 1);
5887 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5889 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5890 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5891 // to "time out" the HTLC.
5893 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5895 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5896 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5897 header.prev_blockhash = header.block_hash();
5899 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5900 check_closed_broadcast!(nodes[0], false);
5901 check_added_monitors!(nodes[0], 1);
5904 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5905 let chanmon_cfgs = create_chanmon_cfgs(3);
5906 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5907 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5908 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5909 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5911 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5912 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5913 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5914 // actually revoked.
5915 let htlc_value = if use_dust { 50000 } else { 3000000 };
5916 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5917 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5918 expect_pending_htlcs_forwardable!(nodes[1]);
5919 check_added_monitors!(nodes[1], 1);
5921 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5922 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5923 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5924 check_added_monitors!(nodes[0], 1);
5925 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5926 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5927 check_added_monitors!(nodes[1], 1);
5928 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5929 check_added_monitors!(nodes[1], 1);
5930 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5932 if check_revoke_no_close {
5933 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5934 check_added_monitors!(nodes[0], 1);
5937 let mut block = Block {
5938 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5941 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5942 connect_block(&nodes[0], &block, i);
5943 block.header.prev_blockhash = block.block_hash();
5945 if !check_revoke_no_close {
5946 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5947 check_closed_broadcast!(nodes[0], false);
5948 check_added_monitors!(nodes[0], 1);
5950 expect_payment_failed!(nodes[0], our_payment_hash, true);
5954 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5955 // There are only a few cases to test here:
5956 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5957 // broadcastable commitment transactions result in channel closure,
5958 // * its included in an unrevoked-but-previous remote commitment transaction,
5959 // * its included in the latest remote or local commitment transactions.
5960 // We test each of the three possible commitment transactions individually and use both dust and
5962 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5963 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5964 // tested for at least one of the cases in other tests.
5966 fn htlc_claim_single_commitment_only_a() {
5967 do_htlc_claim_local_commitment_only(true);
5968 do_htlc_claim_local_commitment_only(false);
5970 do_htlc_claim_current_remote_commitment_only(true);
5971 do_htlc_claim_current_remote_commitment_only(false);
5975 fn htlc_claim_single_commitment_only_b() {
5976 do_htlc_claim_previous_remote_commitment_only(true, false);
5977 do_htlc_claim_previous_remote_commitment_only(false, false);
5978 do_htlc_claim_previous_remote_commitment_only(true, true);
5979 do_htlc_claim_previous_remote_commitment_only(false, true);
5984 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5985 let chanmon_cfgs = create_chanmon_cfgs(2);
5986 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5987 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5988 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5989 //Force duplicate channel ids
5990 for node in nodes.iter() {
5991 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5994 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5995 let channel_value_satoshis=10000;
5996 let push_msat=10001;
5997 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5998 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5999 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6001 //Create a second channel with a channel_id collision
6002 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6006 fn bolt2_open_channel_sending_node_checks_part2() {
6007 let chanmon_cfgs = create_chanmon_cfgs(2);
6008 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6009 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6010 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6012 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6013 let channel_value_satoshis=2^24;
6014 let push_msat=10001;
6015 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6017 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6018 let channel_value_satoshis=10000;
6019 // Test when push_msat is equal to 1000 * funding_satoshis.
6020 let push_msat=1000*channel_value_satoshis+1;
6021 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6023 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6024 let channel_value_satoshis=10000;
6025 let push_msat=10001;
6026 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
6027 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6028 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6030 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6031 // 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
6032 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6034 // 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.
6035 assert!(BREAKDOWN_TIMEOUT>0);
6036 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6038 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6039 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6040 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6042 // 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.
6043 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6044 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6045 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6046 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6047 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6050 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6051 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6052 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6053 // is no longer affordable once it's freed.
6055 fn test_fail_holding_cell_htlc_upon_free() {
6056 let chanmon_cfgs = create_chanmon_cfgs(2);
6057 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6058 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6059 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6060 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6061 let logger = test_utils::TestLogger::new();
6063 // First nodes[0] generates an update_fee, setting the channel's
6064 // pending_update_fee.
6065 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6066 check_added_monitors!(nodes[0], 1);
6068 let events = nodes[0].node.get_and_clear_pending_msg_events();
6069 assert_eq!(events.len(), 1);
6070 let (update_msg, commitment_signed) = match events[0] {
6071 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6072 (update_fee.as_ref(), commitment_signed)
6074 _ => panic!("Unexpected event"),
6077 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6079 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6080 let channel_reserve = chan_stat.channel_reserve_msat;
6081 let feerate = get_feerate!(nodes[0], chan.2);
6083 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6084 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6085 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6086 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6087 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();
6089 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6090 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6091 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6092 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6094 // Flush the pending fee update.
6095 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6096 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6097 check_added_monitors!(nodes[1], 1);
6098 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6099 check_added_monitors!(nodes[0], 1);
6101 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6102 // HTLC, but now that the fee has been raised the payment will now fail, causing
6103 // us to surface its failure to the user.
6104 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6105 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6106 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6107 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);
6108 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6110 // Check that the payment failed to be sent out.
6111 let events = nodes[0].node.get_and_clear_pending_events();
6112 assert_eq!(events.len(), 1);
6114 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6115 assert_eq!(our_payment_hash.clone(), *payment_hash);
6116 assert_eq!(*rejected_by_dest, false);
6117 assert_eq!(*error_code, None);
6118 assert_eq!(*error_data, None);
6120 _ => panic!("Unexpected event"),
6124 // Test that if multiple HTLCs are released from the holding cell and one is
6125 // valid but the other is no longer valid upon release, the valid HTLC can be
6126 // successfully completed while the other one fails as expected.
6128 fn test_free_and_fail_holding_cell_htlcs() {
6129 let chanmon_cfgs = create_chanmon_cfgs(2);
6130 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6131 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6132 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6133 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6134 let logger = test_utils::TestLogger::new();
6136 // First nodes[0] generates an update_fee, setting the channel's
6137 // pending_update_fee.
6138 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6139 check_added_monitors!(nodes[0], 1);
6141 let events = nodes[0].node.get_and_clear_pending_msg_events();
6142 assert_eq!(events.len(), 1);
6143 let (update_msg, commitment_signed) = match events[0] {
6144 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6145 (update_fee.as_ref(), commitment_signed)
6147 _ => panic!("Unexpected event"),
6150 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6152 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6153 let channel_reserve = chan_stat.channel_reserve_msat;
6154 let feerate = get_feerate!(nodes[0], chan.2);
6156 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6157 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6159 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6160 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6161 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6162 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();
6163 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();
6165 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6166 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6167 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6168 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6169 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6170 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6171 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6173 // Flush the pending fee update.
6174 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6175 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6176 check_added_monitors!(nodes[1], 1);
6177 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6178 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6179 check_added_monitors!(nodes[0], 2);
6181 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6182 // but now that the fee has been raised the second payment will now fail, causing us
6183 // to surface its failure to the user. The first payment should succeed.
6184 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6185 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6186 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6187 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);
6188 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6190 // Check that the second payment failed to be sent out.
6191 let events = nodes[0].node.get_and_clear_pending_events();
6192 assert_eq!(events.len(), 1);
6194 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6195 assert_eq!(payment_hash_2.clone(), *payment_hash);
6196 assert_eq!(*rejected_by_dest, false);
6197 assert_eq!(*error_code, None);
6198 assert_eq!(*error_data, None);
6200 _ => panic!("Unexpected event"),
6203 // Complete the first payment and the RAA from the fee update.
6204 let (payment_event, send_raa_event) = {
6205 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6206 assert_eq!(msgs.len(), 2);
6207 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6209 let raa = match send_raa_event {
6210 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6211 _ => panic!("Unexpected event"),
6213 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6214 check_added_monitors!(nodes[1], 1);
6215 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6216 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6217 let events = nodes[1].node.get_and_clear_pending_events();
6218 assert_eq!(events.len(), 1);
6220 Event::PendingHTLCsForwardable { .. } => {},
6221 _ => panic!("Unexpected event"),
6223 nodes[1].node.process_pending_htlc_forwards();
6224 let events = nodes[1].node.get_and_clear_pending_events();
6225 assert_eq!(events.len(), 1);
6227 Event::PaymentReceived { .. } => {},
6228 _ => panic!("Unexpected event"),
6230 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6231 check_added_monitors!(nodes[1], 1);
6232 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6233 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6234 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6235 let events = nodes[0].node.get_and_clear_pending_events();
6236 assert_eq!(events.len(), 1);
6238 Event::PaymentSent { ref payment_preimage } => {
6239 assert_eq!(*payment_preimage, payment_preimage_1);
6241 _ => panic!("Unexpected event"),
6245 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6246 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6247 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6250 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6251 let chanmon_cfgs = create_chanmon_cfgs(3);
6252 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6253 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6254 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6255 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6256 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6257 let logger = test_utils::TestLogger::new();
6259 // First nodes[1] generates an update_fee, setting the channel's
6260 // pending_update_fee.
6261 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6262 check_added_monitors!(nodes[1], 1);
6264 let events = nodes[1].node.get_and_clear_pending_msg_events();
6265 assert_eq!(events.len(), 1);
6266 let (update_msg, commitment_signed) = match events[0] {
6267 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6268 (update_fee.as_ref(), commitment_signed)
6270 _ => panic!("Unexpected event"),
6273 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6275 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6276 let channel_reserve = chan_stat.channel_reserve_msat;
6277 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6279 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6281 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6282 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6283 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6284 let payment_event = {
6285 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6286 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();
6287 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6288 check_added_monitors!(nodes[0], 1);
6290 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6291 assert_eq!(events.len(), 1);
6293 SendEvent::from_event(events.remove(0))
6295 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6296 check_added_monitors!(nodes[1], 0);
6297 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6298 expect_pending_htlcs_forwardable!(nodes[1]);
6300 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6301 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6303 // Flush the pending fee update.
6304 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6305 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6306 check_added_monitors!(nodes[2], 1);
6307 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6308 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6309 check_added_monitors!(nodes[1], 2);
6311 // A final RAA message is generated to finalize the fee update.
6312 let events = nodes[1].node.get_and_clear_pending_msg_events();
6313 assert_eq!(events.len(), 1);
6315 let raa_msg = match &events[0] {
6316 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6319 _ => panic!("Unexpected event"),
6322 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6323 check_added_monitors!(nodes[2], 1);
6324 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6326 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6327 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6328 assert_eq!(process_htlc_forwards_event.len(), 1);
6329 match &process_htlc_forwards_event[0] {
6330 &Event::PendingHTLCsForwardable { .. } => {},
6331 _ => panic!("Unexpected event"),
6334 // In response, we call ChannelManager's process_pending_htlc_forwards
6335 nodes[1].node.process_pending_htlc_forwards();
6336 check_added_monitors!(nodes[1], 1);
6338 // This causes the HTLC to be failed backwards.
6339 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6340 assert_eq!(fail_event.len(), 1);
6341 let (fail_msg, commitment_signed) = match &fail_event[0] {
6342 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6343 assert_eq!(updates.update_add_htlcs.len(), 0);
6344 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6345 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6346 assert_eq!(updates.update_fail_htlcs.len(), 1);
6347 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6349 _ => panic!("Unexpected event"),
6352 // Pass the failure messages back to nodes[0].
6353 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6354 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6356 // Complete the HTLC failure+removal process.
6357 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6358 check_added_monitors!(nodes[0], 1);
6359 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6360 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6361 check_added_monitors!(nodes[1], 2);
6362 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6363 assert_eq!(final_raa_event.len(), 1);
6364 let raa = match &final_raa_event[0] {
6365 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6366 _ => panic!("Unexpected event"),
6368 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6369 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6370 assert_eq!(fail_msg_event.len(), 1);
6371 match &fail_msg_event[0] {
6372 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6373 _ => panic!("Unexpected event"),
6375 let failure_event = nodes[0].node.get_and_clear_pending_events();
6376 assert_eq!(failure_event.len(), 1);
6377 match &failure_event[0] {
6378 &Event::PaymentFailed { rejected_by_dest, .. } => {
6379 assert!(!rejected_by_dest);
6381 _ => panic!("Unexpected event"),
6383 check_added_monitors!(nodes[0], 1);
6386 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6387 // 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.
6388 //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.
6391 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6392 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6393 let chanmon_cfgs = create_chanmon_cfgs(2);
6394 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6395 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6396 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6397 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6399 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6400 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6401 let logger = test_utils::TestLogger::new();
6402 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();
6403 route.paths[0][0].fee_msat = 100;
6405 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6406 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6407 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6408 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6412 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6413 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6414 let chanmon_cfgs = create_chanmon_cfgs(2);
6415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6417 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6418 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6419 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6421 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6422 let logger = test_utils::TestLogger::new();
6423 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();
6424 route.paths[0][0].fee_msat = 0;
6425 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6426 assert_eq!(err, "Cannot send 0-msat HTLC"));
6428 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6429 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6433 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6434 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6435 let chanmon_cfgs = create_chanmon_cfgs(2);
6436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6438 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6439 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6441 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6442 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6443 let logger = test_utils::TestLogger::new();
6444 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();
6445 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6446 check_added_monitors!(nodes[0], 1);
6447 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6448 updates.update_add_htlcs[0].amount_msat = 0;
6450 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6451 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6452 check_closed_broadcast!(nodes[1], true).unwrap();
6453 check_added_monitors!(nodes[1], 1);
6457 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6458 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6459 //It is enforced when constructing a route.
6460 let chanmon_cfgs = create_chanmon_cfgs(2);
6461 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6462 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6463 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6464 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6465 let logger = test_utils::TestLogger::new();
6467 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6469 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6470 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();
6471 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6472 assert_eq!(err, &"Channel CLTV overflowed?"));
6476 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6477 //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.
6478 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6479 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6480 let chanmon_cfgs = create_chanmon_cfgs(2);
6481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6483 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6484 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6485 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6487 let logger = test_utils::TestLogger::new();
6488 for i in 0..max_accepted_htlcs {
6489 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6490 let payment_event = {
6491 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6492 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();
6493 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6494 check_added_monitors!(nodes[0], 1);
6496 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6497 assert_eq!(events.len(), 1);
6498 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6499 assert_eq!(htlcs[0].htlc_id, i);
6503 SendEvent::from_event(events.remove(0))
6505 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6506 check_added_monitors!(nodes[1], 0);
6507 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6509 expect_pending_htlcs_forwardable!(nodes[1]);
6510 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6512 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6513 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6514 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();
6515 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6516 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6518 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6519 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6523 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6524 //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.
6525 let chanmon_cfgs = create_chanmon_cfgs(2);
6526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6528 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6529 let channel_value = 100000;
6530 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6531 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6533 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6535 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6536 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6537 let logger = test_utils::TestLogger::new();
6538 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();
6539 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6540 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)));
6542 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6543 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);
6545 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6548 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6550 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6551 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6552 let chanmon_cfgs = create_chanmon_cfgs(2);
6553 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6554 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6555 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6556 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6557 let htlc_minimum_msat: u64;
6559 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6560 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6561 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6564 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6565 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6566 let logger = test_utils::TestLogger::new();
6567 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();
6568 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6569 check_added_monitors!(nodes[0], 1);
6570 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6571 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6572 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6573 assert!(nodes[1].node.list_channels().is_empty());
6574 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6575 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()));
6576 check_added_monitors!(nodes[1], 1);
6580 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6581 //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
6582 let chanmon_cfgs = create_chanmon_cfgs(2);
6583 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6584 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6585 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6586 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6587 let logger = test_utils::TestLogger::new();
6589 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6590 let channel_reserve = chan_stat.channel_reserve_msat;
6591 let feerate = get_feerate!(nodes[0], chan.2);
6592 // The 2* and +1 are for the fee spike reserve.
6593 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6595 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6596 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6597 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6598 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();
6599 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6600 check_added_monitors!(nodes[0], 1);
6601 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6603 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6604 // at this time channel-initiatee receivers are not required to enforce that senders
6605 // respect the fee_spike_reserve.
6606 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6607 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6609 assert!(nodes[1].node.list_channels().is_empty());
6610 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6611 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6612 check_added_monitors!(nodes[1], 1);
6616 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6617 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6618 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6619 let chanmon_cfgs = create_chanmon_cfgs(2);
6620 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6621 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6622 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6623 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6624 let logger = test_utils::TestLogger::new();
6626 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6627 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6629 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6630 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6632 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6633 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6634 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6635 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6637 let mut msg = msgs::UpdateAddHTLC {
6641 payment_hash: our_payment_hash,
6642 cltv_expiry: htlc_cltv,
6643 onion_routing_packet: onion_packet.clone(),
6646 for i in 0..super::channel::OUR_MAX_HTLCS {
6647 msg.htlc_id = i as u64;
6648 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6650 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6651 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6653 assert!(nodes[1].node.list_channels().is_empty());
6654 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6655 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6656 check_added_monitors!(nodes[1], 1);
6660 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6661 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6662 let chanmon_cfgs = create_chanmon_cfgs(2);
6663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6665 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6666 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6667 let logger = test_utils::TestLogger::new();
6669 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6670 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6671 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();
6672 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6673 check_added_monitors!(nodes[0], 1);
6674 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6675 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6678 assert!(nodes[1].node.list_channels().is_empty());
6679 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6680 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6681 check_added_monitors!(nodes[1], 1);
6685 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6686 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6687 let chanmon_cfgs = create_chanmon_cfgs(2);
6688 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6689 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6690 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6691 let logger = test_utils::TestLogger::new();
6693 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6694 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6695 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6696 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();
6697 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6698 check_added_monitors!(nodes[0], 1);
6699 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6700 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6701 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703 assert!(nodes[1].node.list_channels().is_empty());
6704 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6705 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6706 check_added_monitors!(nodes[1], 1);
6710 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6711 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6712 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6713 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6714 let chanmon_cfgs = create_chanmon_cfgs(2);
6715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6717 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6718 let logger = test_utils::TestLogger::new();
6720 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6721 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6722 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6723 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();
6724 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6725 check_added_monitors!(nodes[0], 1);
6726 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6727 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6729 //Disconnect and Reconnect
6730 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6731 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6732 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6733 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6734 assert_eq!(reestablish_1.len(), 1);
6735 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6736 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6737 assert_eq!(reestablish_2.len(), 1);
6738 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6739 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6740 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6741 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6744 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6745 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6746 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6747 check_added_monitors!(nodes[1], 1);
6748 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6750 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6752 assert!(nodes[1].node.list_channels().is_empty());
6753 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6754 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6755 check_added_monitors!(nodes[1], 1);
6759 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6760 //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.
6762 let chanmon_cfgs = create_chanmon_cfgs(2);
6763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6765 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6766 let logger = test_utils::TestLogger::new();
6767 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6768 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6769 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6770 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();
6771 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6773 check_added_monitors!(nodes[0], 1);
6774 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6775 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6777 let update_msg = msgs::UpdateFulfillHTLC{
6780 payment_preimage: our_payment_preimage,
6783 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6785 assert!(nodes[0].node.list_channels().is_empty());
6786 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6787 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()));
6788 check_added_monitors!(nodes[0], 1);
6792 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6793 //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.
6795 let chanmon_cfgs = create_chanmon_cfgs(2);
6796 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6797 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6798 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6799 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6800 let logger = test_utils::TestLogger::new();
6802 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6803 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6804 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();
6805 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6806 check_added_monitors!(nodes[0], 1);
6807 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6808 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6810 let update_msg = msgs::UpdateFailHTLC{
6813 reason: msgs::OnionErrorPacket { data: Vec::new()},
6816 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6818 assert!(nodes[0].node.list_channels().is_empty());
6819 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6820 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()));
6821 check_added_monitors!(nodes[0], 1);
6825 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6826 //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.
6828 let chanmon_cfgs = create_chanmon_cfgs(2);
6829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6830 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6831 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6832 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6833 let logger = test_utils::TestLogger::new();
6835 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6836 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6837 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();
6838 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6839 check_added_monitors!(nodes[0], 1);
6840 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6841 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6843 let update_msg = msgs::UpdateFailMalformedHTLC{
6846 sha256_of_onion: [1; 32],
6847 failure_code: 0x8000,
6850 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6852 assert!(nodes[0].node.list_channels().is_empty());
6853 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6854 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()));
6855 check_added_monitors!(nodes[0], 1);
6859 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6860 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6862 let chanmon_cfgs = create_chanmon_cfgs(2);
6863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6865 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6866 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6868 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6870 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6871 check_added_monitors!(nodes[1], 1);
6873 let events = nodes[1].node.get_and_clear_pending_msg_events();
6874 assert_eq!(events.len(), 1);
6875 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6877 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6878 assert!(update_add_htlcs.is_empty());
6879 assert_eq!(update_fulfill_htlcs.len(), 1);
6880 assert!(update_fail_htlcs.is_empty());
6881 assert!(update_fail_malformed_htlcs.is_empty());
6882 assert!(update_fee.is_none());
6883 update_fulfill_htlcs[0].clone()
6885 _ => panic!("Unexpected event"),
6889 update_fulfill_msg.htlc_id = 1;
6891 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6893 assert!(nodes[0].node.list_channels().is_empty());
6894 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6895 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6896 check_added_monitors!(nodes[0], 1);
6900 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6901 //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.
6903 let chanmon_cfgs = create_chanmon_cfgs(2);
6904 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6905 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6906 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6907 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6909 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6911 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6912 check_added_monitors!(nodes[1], 1);
6914 let events = nodes[1].node.get_and_clear_pending_msg_events();
6915 assert_eq!(events.len(), 1);
6916 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6918 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, .. } } => {
6919 assert!(update_add_htlcs.is_empty());
6920 assert_eq!(update_fulfill_htlcs.len(), 1);
6921 assert!(update_fail_htlcs.is_empty());
6922 assert!(update_fail_malformed_htlcs.is_empty());
6923 assert!(update_fee.is_none());
6924 update_fulfill_htlcs[0].clone()
6926 _ => panic!("Unexpected event"),
6930 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6932 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6934 assert!(nodes[0].node.list_channels().is_empty());
6935 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6936 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6937 check_added_monitors!(nodes[0], 1);
6941 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6942 //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.
6944 let chanmon_cfgs = create_chanmon_cfgs(2);
6945 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6946 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6947 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6948 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6949 let logger = test_utils::TestLogger::new();
6951 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6952 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6953 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();
6954 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6955 check_added_monitors!(nodes[0], 1);
6957 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6958 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6961 check_added_monitors!(nodes[1], 0);
6962 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6964 let events = nodes[1].node.get_and_clear_pending_msg_events();
6966 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6968 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, .. } } => {
6969 assert!(update_add_htlcs.is_empty());
6970 assert!(update_fulfill_htlcs.is_empty());
6971 assert!(update_fail_htlcs.is_empty());
6972 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6973 assert!(update_fee.is_none());
6974 update_fail_malformed_htlcs[0].clone()
6976 _ => panic!("Unexpected event"),
6979 update_msg.failure_code &= !0x8000;
6980 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6982 assert!(nodes[0].node.list_channels().is_empty());
6983 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6984 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6985 check_added_monitors!(nodes[0], 1);
6989 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6990 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6991 // * 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.
6993 let chanmon_cfgs = create_chanmon_cfgs(3);
6994 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6995 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6996 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6997 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6998 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6999 let logger = test_utils::TestLogger::new();
7001 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7004 let mut payment_event = {
7005 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7006 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();
7007 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7008 check_added_monitors!(nodes[0], 1);
7009 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7010 assert_eq!(events.len(), 1);
7011 SendEvent::from_event(events.remove(0))
7013 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7014 check_added_monitors!(nodes[1], 0);
7015 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7016 expect_pending_htlcs_forwardable!(nodes[1]);
7017 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7018 assert_eq!(events_2.len(), 1);
7019 check_added_monitors!(nodes[1], 1);
7020 payment_event = SendEvent::from_event(events_2.remove(0));
7021 assert_eq!(payment_event.msgs.len(), 1);
7024 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7025 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7026 check_added_monitors!(nodes[2], 0);
7027 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7029 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7030 assert_eq!(events_3.len(), 1);
7031 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7033 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 } } => {
7034 assert!(update_add_htlcs.is_empty());
7035 assert!(update_fulfill_htlcs.is_empty());
7036 assert!(update_fail_htlcs.is_empty());
7037 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7038 assert!(update_fee.is_none());
7039 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7041 _ => panic!("Unexpected event"),
7045 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7047 check_added_monitors!(nodes[1], 0);
7048 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7049 expect_pending_htlcs_forwardable!(nodes[1]);
7050 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7051 assert_eq!(events_4.len(), 1);
7053 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7055 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, .. } } => {
7056 assert!(update_add_htlcs.is_empty());
7057 assert!(update_fulfill_htlcs.is_empty());
7058 assert_eq!(update_fail_htlcs.len(), 1);
7059 assert!(update_fail_malformed_htlcs.is_empty());
7060 assert!(update_fee.is_none());
7062 _ => panic!("Unexpected event"),
7065 check_added_monitors!(nodes[1], 1);
7068 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7069 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7070 // 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
7071 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7073 let chanmon_cfgs = create_chanmon_cfgs(2);
7074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7077 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7079 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7081 // We route 2 dust-HTLCs between A and B
7082 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7083 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7084 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7086 // Cache one local commitment tx as previous
7087 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7089 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7090 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7091 check_added_monitors!(nodes[1], 0);
7092 expect_pending_htlcs_forwardable!(nodes[1]);
7093 check_added_monitors!(nodes[1], 1);
7095 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7096 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7097 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7098 check_added_monitors!(nodes[0], 1);
7100 // Cache one local commitment tx as lastest
7101 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7103 let events = nodes[0].node.get_and_clear_pending_msg_events();
7105 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7106 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7108 _ => panic!("Unexpected event"),
7111 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7112 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7114 _ => panic!("Unexpected event"),
7117 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7118 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7119 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7121 if announce_latest {
7122 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7124 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7127 check_closed_broadcast!(nodes[0], false);
7128 check_added_monitors!(nodes[0], 1);
7130 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7131 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7132 let events = nodes[0].node.get_and_clear_pending_events();
7133 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7134 assert_eq!(events.len(), 2);
7135 let mut first_failed = false;
7136 for event in events {
7138 Event::PaymentFailed { payment_hash, .. } => {
7139 if payment_hash == payment_hash_1 {
7140 assert!(!first_failed);
7141 first_failed = true;
7143 assert_eq!(payment_hash, payment_hash_2);
7146 _ => panic!("Unexpected event"),
7152 fn test_failure_delay_dust_htlc_local_commitment() {
7153 do_test_failure_delay_dust_htlc_local_commitment(true);
7154 do_test_failure_delay_dust_htlc_local_commitment(false);
7158 fn test_no_failure_dust_htlc_local_commitment() {
7159 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7160 // prone to error, we test here that a dummy transaction don't fail them.
7162 let chanmon_cfgs = create_chanmon_cfgs(2);
7163 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7164 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7165 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7166 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7169 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7171 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7172 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7174 // We route 2 dust-HTLCs between A and B
7175 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7176 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7178 // Build a dummy invalid transaction trying to spend a commitment tx
7180 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7181 script_sig: Script::new(),
7183 witness: Vec::new(),
7187 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7191 let dummy_tx = Transaction {
7198 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7199 nodes[0].chain_monitor.chain_monitor.block_connected(&header, &[(0, &dummy_tx)], 1);
7200 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7201 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7202 // We broadcast a few more block to check everything is all right
7203 connect_blocks(&nodes[0], 20, 1, true, header.block_hash());
7204 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7205 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7207 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7208 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7211 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7212 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7213 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7214 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7215 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7216 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7217 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7219 let chanmon_cfgs = create_chanmon_cfgs(3);
7220 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7221 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7222 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7223 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7225 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7227 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7228 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7230 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7231 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7233 // We revoked bs_commitment_tx
7235 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7236 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7239 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7240 let mut timeout_tx = Vec::new();
7242 // We fail dust-HTLC 1 by broadcast of local commitment tx
7243 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7244 check_closed_broadcast!(nodes[0], false);
7245 check_added_monitors!(nodes[0], 1);
7246 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7247 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7248 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7249 expect_payment_failed!(nodes[0], dust_hash, true);
7250 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7251 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7252 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7253 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7254 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7255 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7256 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7257 expect_payment_failed!(nodes[0], non_dust_hash, true);
7259 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7260 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7261 check_closed_broadcast!(nodes[0], false);
7262 check_added_monitors!(nodes[0], 1);
7263 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7264 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7265 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7266 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7268 expect_payment_failed!(nodes[0], dust_hash, true);
7269 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7270 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7271 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7272 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7273 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7274 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7275 expect_payment_failed!(nodes[0], non_dust_hash, true);
7277 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7279 let events = nodes[0].node.get_and_clear_pending_events();
7280 assert_eq!(events.len(), 2);
7283 Event::PaymentFailed { payment_hash, .. } => {
7284 if payment_hash == dust_hash { first = true; }
7285 else { first = false; }
7287 _ => panic!("Unexpected event"),
7290 Event::PaymentFailed { payment_hash, .. } => {
7291 if first { assert_eq!(payment_hash, non_dust_hash); }
7292 else { assert_eq!(payment_hash, dust_hash); }
7294 _ => panic!("Unexpected event"),
7301 fn test_sweep_outbound_htlc_failure_update() {
7302 do_test_sweep_outbound_htlc_failure_update(false, true);
7303 do_test_sweep_outbound_htlc_failure_update(false, false);
7304 do_test_sweep_outbound_htlc_failure_update(true, false);
7308 fn test_upfront_shutdown_script() {
7309 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7310 // enforce it at shutdown message
7312 let mut config = UserConfig::default();
7313 config.channel_options.announced_channel = true;
7314 config.peer_channel_config_limits.force_announced_channel_preference = false;
7315 config.channel_options.commit_upfront_shutdown_pubkey = false;
7316 let user_cfgs = [None, Some(config), None];
7317 let chanmon_cfgs = create_chanmon_cfgs(3);
7318 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7319 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7320 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7322 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7323 let flags = InitFeatures::known();
7324 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7325 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7326 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7327 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7328 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7329 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7330 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()));
7331 check_added_monitors!(nodes[2], 1);
7333 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7334 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7335 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7336 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7337 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7338 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7339 let events = nodes[2].node.get_and_clear_pending_msg_events();
7340 assert_eq!(events.len(), 1);
7342 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7343 _ => panic!("Unexpected event"),
7346 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7347 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7348 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7349 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7350 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7351 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7352 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7353 let events = nodes[1].node.get_and_clear_pending_msg_events();
7354 assert_eq!(events.len(), 1);
7356 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7357 _ => panic!("Unexpected event"),
7360 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7361 // channel smoothly, opt-out is from channel initiator here
7362 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7363 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7364 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7365 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7366 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7367 let events = nodes[0].node.get_and_clear_pending_msg_events();
7368 assert_eq!(events.len(), 1);
7370 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7371 _ => panic!("Unexpected event"),
7374 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7375 //// channel smoothly
7376 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7377 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7378 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7379 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7380 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7381 let events = nodes[0].node.get_and_clear_pending_msg_events();
7382 assert_eq!(events.len(), 2);
7384 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7385 _ => panic!("Unexpected event"),
7388 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7389 _ => panic!("Unexpected event"),
7394 fn test_user_configurable_csv_delay() {
7395 // We test our channel constructors yield errors when we pass them absurd csv delay
7397 let mut low_our_to_self_config = UserConfig::default();
7398 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7399 let mut high_their_to_self_config = UserConfig::default();
7400 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7401 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7402 let chanmon_cfgs = create_chanmon_cfgs(2);
7403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7405 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7407 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7408 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7409 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7411 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())); },
7412 _ => panic!("Unexpected event"),
7414 } else { assert!(false) }
7416 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7417 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7418 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7419 open_channel.to_self_delay = 200;
7420 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7422 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())); },
7423 _ => panic!("Unexpected event"),
7425 } else { assert!(false); }
7427 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7428 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7429 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()));
7430 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7431 accept_channel.to_self_delay = 200;
7432 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7433 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7435 &ErrorAction::SendErrorMessage { ref msg } => {
7436 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()));
7438 _ => { assert!(false); }
7440 } else { assert!(false); }
7442 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7443 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7444 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7445 open_channel.to_self_delay = 200;
7446 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7448 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())); },
7449 _ => panic!("Unexpected event"),
7451 } else { assert!(false); }
7455 fn test_data_loss_protect() {
7456 // We want to be sure that :
7457 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7458 // * we close channel in case of detecting other being fallen behind
7459 // * we are able to claim our own outputs thanks to to_remote being static
7467 let chanmon_cfgs = create_chanmon_cfgs(2);
7468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7470 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7472 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7474 // Cache node A state before any channel update
7475 let previous_node_state = nodes[0].node.encode();
7476 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7477 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chain_monitor_state).unwrap();
7479 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7480 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7482 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7483 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7485 // Restore node A from previous state
7486 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7487 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0)).unwrap().1;
7488 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7489 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7490 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7491 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7492 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator);
7494 let mut channel_monitors = HashMap::new();
7495 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7496 <(BlockHash, ChannelManager<EnforcingChannelKeys, &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 {
7497 keys_manager: &keys_manager,
7498 fee_estimator: &fee_estimator,
7499 chain_monitor: &monitor,
7501 tx_broadcaster: &tx_broadcaster,
7502 default_config: UserConfig::default(),
7506 nodes[0].node = &node_state_0;
7507 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7508 nodes[0].chain_monitor = &monitor;
7509 nodes[0].chain_source = &chain_source;
7511 check_added_monitors!(nodes[0], 1);
7513 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7514 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7516 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7518 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7519 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7520 check_added_monitors!(nodes[0], 1);
7523 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7524 assert_eq!(node_txn.len(), 0);
7527 let mut reestablish_1 = Vec::with_capacity(1);
7528 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7529 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7530 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7531 reestablish_1.push(msg.clone());
7532 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7533 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7535 &ErrorAction::SendErrorMessage { ref msg } => {
7536 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");
7538 _ => panic!("Unexpected event!"),
7541 panic!("Unexpected event")
7545 // Check we close channel detecting A is fallen-behind
7546 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7547 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7548 check_added_monitors!(nodes[1], 1);
7551 // Check A is able to claim to_remote output
7552 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7553 assert_eq!(node_txn.len(), 1);
7554 check_spends!(node_txn[0], chan.3);
7555 assert_eq!(node_txn[0].output.len(), 2);
7556 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7557 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7558 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7559 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7560 assert_eq!(spend_txn.len(), 1);
7561 check_spends!(spend_txn[0], node_txn[0]);
7565 fn test_check_htlc_underpaying() {
7566 // Send payment through A -> B but A is maliciously
7567 // sending a probe payment (i.e less than expected value0
7568 // to B, B should refuse payment.
7570 let chanmon_cfgs = create_chanmon_cfgs(2);
7571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7575 // Create some initial channels
7576 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7578 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7580 // Node 3 is expecting payment of 100_000 but receive 10_000,
7581 // fail htlc like we didn't know the preimage.
7582 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7583 nodes[1].node.process_pending_htlc_forwards();
7585 let events = nodes[1].node.get_and_clear_pending_msg_events();
7586 assert_eq!(events.len(), 1);
7587 let (update_fail_htlc, commitment_signed) = match events[0] {
7588 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 } } => {
7589 assert!(update_add_htlcs.is_empty());
7590 assert!(update_fulfill_htlcs.is_empty());
7591 assert_eq!(update_fail_htlcs.len(), 1);
7592 assert!(update_fail_malformed_htlcs.is_empty());
7593 assert!(update_fee.is_none());
7594 (update_fail_htlcs[0].clone(), commitment_signed)
7596 _ => panic!("Unexpected event"),
7598 check_added_monitors!(nodes[1], 1);
7600 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7601 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7603 // 10_000 msat as u64, followed by a height of 99 as u32
7604 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7605 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7606 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7607 nodes[1].node.get_and_clear_pending_events();
7611 fn test_announce_disable_channels() {
7612 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7613 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7615 let chanmon_cfgs = create_chanmon_cfgs(2);
7616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7618 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7620 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7621 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7622 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7625 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7626 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7628 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7629 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7630 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7631 assert_eq!(msg_events.len(), 3);
7632 for e in msg_events {
7634 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7635 let short_id = msg.contents.short_channel_id;
7636 // Check generated channel_update match list in PendingChannelUpdate
7637 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7638 panic!("Generated ChannelUpdate for wrong chan!");
7641 _ => panic!("Unexpected event"),
7645 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7646 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7647 assert_eq!(reestablish_1.len(), 3);
7648 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7649 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7650 assert_eq!(reestablish_2.len(), 3);
7652 // Reestablish chan_1
7653 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7654 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7655 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7656 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7657 // Reestablish chan_2
7658 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7659 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7661 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7662 // Reestablish chan_3
7663 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7664 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7665 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7666 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7668 nodes[0].node.timer_chan_freshness_every_min();
7669 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7673 fn test_bump_penalty_txn_on_revoked_commitment() {
7674 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7675 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7677 let chanmon_cfgs = create_chanmon_cfgs(2);
7678 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7679 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7680 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7682 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7683 let logger = test_utils::TestLogger::new();
7686 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7687 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7688 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();
7689 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7691 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7692 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7693 assert_eq!(revoked_txn[0].output.len(), 4);
7694 assert_eq!(revoked_txn[0].input.len(), 1);
7695 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7696 let revoked_txid = revoked_txn[0].txid();
7698 let mut penalty_sum = 0;
7699 for outp in revoked_txn[0].output.iter() {
7700 if outp.script_pubkey.is_v0_p2wsh() {
7701 penalty_sum += outp.value;
7705 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7706 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7708 // Actually revoke tx by claiming a HTLC
7709 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7710 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7711 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7712 check_added_monitors!(nodes[1], 1);
7714 // One or more justice tx should have been broadcast, check it
7718 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7719 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7720 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7721 assert_eq!(node_txn[0].output.len(), 1);
7722 check_spends!(node_txn[0], revoked_txn[0]);
7723 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7724 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7725 penalty_1 = node_txn[0].txid();
7729 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7730 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7731 let mut penalty_2 = penalty_1;
7732 let mut feerate_2 = 0;
7734 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7735 assert_eq!(node_txn.len(), 1);
7736 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7737 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7738 assert_eq!(node_txn[0].output.len(), 1);
7739 check_spends!(node_txn[0], revoked_txn[0]);
7740 penalty_2 = node_txn[0].txid();
7741 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7742 assert_ne!(penalty_2, penalty_1);
7743 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7744 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7745 // Verify 25% bump heuristic
7746 assert!(feerate_2 * 100 >= feerate_1 * 125);
7750 assert_ne!(feerate_2, 0);
7752 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7753 connect_blocks(&nodes[1], 3, 118, true, header);
7755 let mut feerate_3 = 0;
7757 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7758 assert_eq!(node_txn.len(), 1);
7759 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7760 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7761 assert_eq!(node_txn[0].output.len(), 1);
7762 check_spends!(node_txn[0], revoked_txn[0]);
7763 penalty_3 = node_txn[0].txid();
7764 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7765 assert_ne!(penalty_3, penalty_2);
7766 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7767 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7768 // Verify 25% bump heuristic
7769 assert!(feerate_3 * 100 >= feerate_2 * 125);
7773 assert_ne!(feerate_3, 0);
7775 nodes[1].node.get_and_clear_pending_events();
7776 nodes[1].node.get_and_clear_pending_msg_events();
7780 fn test_bump_penalty_txn_on_revoked_htlcs() {
7781 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7782 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7784 let chanmon_cfgs = create_chanmon_cfgs(2);
7785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7789 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7790 // Lock HTLC in both directions
7791 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7792 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7794 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7795 assert_eq!(revoked_local_txn[0].input.len(), 1);
7796 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7798 // Revoke local commitment tx
7799 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7801 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7802 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7803 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7804 check_closed_broadcast!(nodes[1], false);
7805 check_added_monitors!(nodes[1], 1);
7807 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7808 assert_eq!(revoked_htlc_txn.len(), 4);
7809 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7810 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7811 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7812 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7813 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7814 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7815 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7816 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7817 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7818 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7819 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7820 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7821 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7822 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7825 // Broadcast set of revoked txn on A
7826 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7827 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7828 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7829 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7830 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7835 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7836 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7837 // Verify claim tx are spending revoked HTLC txn
7839 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7840 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7841 // which are included in the same block (they are broadcasted because we scan the
7842 // transactions linearly and generate claims as we go, they likely should be removed in the
7844 assert_eq!(node_txn[0].input.len(), 1);
7845 check_spends!(node_txn[0], revoked_local_txn[0]);
7846 assert_eq!(node_txn[1].input.len(), 1);
7847 check_spends!(node_txn[1], revoked_local_txn[0]);
7848 assert_eq!(node_txn[2].input.len(), 1);
7849 check_spends!(node_txn[2], revoked_local_txn[0]);
7851 // Each of the three justice transactions claim a separate (single) output of the three
7852 // available, which we check here:
7853 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7854 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7855 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7857 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7858 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7860 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7861 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7862 // a remote commitment tx has already been confirmed).
7863 check_spends!(node_txn[3], chan.3);
7865 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7866 // output, checked above).
7867 assert_eq!(node_txn[4].input.len(), 2);
7868 assert_eq!(node_txn[4].output.len(), 1);
7869 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7871 first = node_txn[4].txid();
7872 // Store both feerates for later comparison
7873 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7874 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7875 penalty_txn = vec![node_txn[2].clone()];
7879 // Connect one more block to see if bumped penalty are issued for HTLC txn
7880 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7881 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7882 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7883 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7885 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7886 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7888 check_spends!(node_txn[0], revoked_local_txn[0]);
7889 check_spends!(node_txn[1], revoked_local_txn[0]);
7890 // Note that these are both bogus - they spend outputs already claimed in block 129:
7891 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7892 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7894 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7895 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7901 // Few more blocks to confirm penalty txn
7902 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7903 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7904 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7906 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7907 assert_eq!(node_txn.len(), 1);
7909 assert_eq!(node_txn[0].input.len(), 2);
7910 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7911 // Verify bumped tx is different and 25% bump heuristic
7912 assert_ne!(first, node_txn[0].txid());
7913 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7914 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7915 assert!(feerate_2 * 100 > feerate_1 * 125);
7916 let txn = vec![node_txn[0].clone()];
7920 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7921 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7922 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7923 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7925 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7926 // We verify than no new transaction has been broadcast because previously
7927 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7928 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7929 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7930 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7931 // up bumped justice generation.
7932 assert_eq!(node_txn.len(), 0);
7935 check_closed_broadcast!(nodes[0], false);
7936 check_added_monitors!(nodes[0], 1);
7940 fn test_bump_penalty_txn_on_remote_commitment() {
7941 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7942 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7945 // Provide preimage for one
7946 // Check aggregation
7948 let chanmon_cfgs = create_chanmon_cfgs(2);
7949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7951 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7953 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7954 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7955 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7957 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7958 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7959 assert_eq!(remote_txn[0].output.len(), 4);
7960 assert_eq!(remote_txn[0].input.len(), 1);
7961 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7963 // Claim a HTLC without revocation (provide B monitor with preimage)
7964 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7965 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7966 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7967 check_added_monitors!(nodes[1], 2);
7969 // One or more claim tx should have been broadcast, check it
7972 let feerate_timeout;
7973 let feerate_preimage;
7975 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7976 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7977 assert_eq!(node_txn[0].input.len(), 1);
7978 assert_eq!(node_txn[1].input.len(), 1);
7979 check_spends!(node_txn[0], remote_txn[0]);
7980 check_spends!(node_txn[1], remote_txn[0]);
7981 check_spends!(node_txn[2], chan.3);
7982 check_spends!(node_txn[3], node_txn[2]);
7983 check_spends!(node_txn[4], node_txn[2]);
7984 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7985 timeout = node_txn[0].txid();
7986 let index = node_txn[0].input[0].previous_output.vout;
7987 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7988 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7990 preimage = node_txn[1].txid();
7991 let index = node_txn[1].input[0].previous_output.vout;
7992 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7993 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7995 timeout = node_txn[1].txid();
7996 let index = node_txn[1].input[0].previous_output.vout;
7997 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7998 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8000 preimage = node_txn[0].txid();
8001 let index = node_txn[0].input[0].previous_output.vout;
8002 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8003 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8007 assert_ne!(feerate_timeout, 0);
8008 assert_ne!(feerate_preimage, 0);
8010 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8011 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
8013 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8014 assert_eq!(node_txn.len(), 2);
8015 assert_eq!(node_txn[0].input.len(), 1);
8016 assert_eq!(node_txn[1].input.len(), 1);
8017 check_spends!(node_txn[0], remote_txn[0]);
8018 check_spends!(node_txn[1], remote_txn[0]);
8019 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8020 let index = node_txn[0].input[0].previous_output.vout;
8021 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8022 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8023 assert!(new_feerate * 100 > feerate_timeout * 125);
8024 assert_ne!(timeout, node_txn[0].txid());
8026 let index = node_txn[1].input[0].previous_output.vout;
8027 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8028 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8029 assert!(new_feerate * 100 > feerate_preimage * 125);
8030 assert_ne!(preimage, node_txn[1].txid());
8032 let index = node_txn[1].input[0].previous_output.vout;
8033 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8034 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8035 assert!(new_feerate * 100 > feerate_timeout * 125);
8036 assert_ne!(timeout, node_txn[1].txid());
8038 let index = node_txn[0].input[0].previous_output.vout;
8039 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8040 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8041 assert!(new_feerate * 100 > feerate_preimage * 125);
8042 assert_ne!(preimage, node_txn[0].txid());
8047 nodes[1].node.get_and_clear_pending_events();
8048 nodes[1].node.get_and_clear_pending_msg_events();
8052 fn test_set_outpoints_partial_claiming() {
8053 // - remote party claim tx, new bump tx
8054 // - disconnect remote claiming tx, new bump
8055 // - disconnect tx, see no tx anymore
8056 let chanmon_cfgs = create_chanmon_cfgs(2);
8057 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8058 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8059 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8061 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8062 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8063 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8065 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8066 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8067 assert_eq!(remote_txn.len(), 3);
8068 assert_eq!(remote_txn[0].output.len(), 4);
8069 assert_eq!(remote_txn[0].input.len(), 1);
8070 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8071 check_spends!(remote_txn[1], remote_txn[0]);
8072 check_spends!(remote_txn[2], remote_txn[0]);
8074 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8075 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8076 // Provide node A with both preimage
8077 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8078 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8079 check_added_monitors!(nodes[0], 2);
8080 nodes[0].node.get_and_clear_pending_events();
8081 nodes[0].node.get_and_clear_pending_msg_events();
8083 // Connect blocks on node A commitment transaction
8084 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8085 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8086 check_closed_broadcast!(nodes[0], false);
8087 check_added_monitors!(nodes[0], 1);
8088 // Verify node A broadcast tx claiming both HTLCs
8090 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8091 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8092 assert_eq!(node_txn.len(), 4);
8093 check_spends!(node_txn[0], remote_txn[0]);
8094 check_spends!(node_txn[1], chan.3);
8095 check_spends!(node_txn[2], node_txn[1]);
8096 check_spends!(node_txn[3], node_txn[1]);
8097 assert_eq!(node_txn[0].input.len(), 2);
8101 // Connect blocks on node B
8102 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8103 check_closed_broadcast!(nodes[1], false);
8104 check_added_monitors!(nodes[1], 1);
8105 // Verify node B broadcast 2 HTLC-timeout txn
8106 let partial_claim_tx = {
8107 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8108 assert_eq!(node_txn.len(), 3);
8109 check_spends!(node_txn[1], node_txn[0]);
8110 check_spends!(node_txn[2], node_txn[0]);
8111 assert_eq!(node_txn[1].input.len(), 1);
8112 assert_eq!(node_txn[2].input.len(), 1);
8116 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8117 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8118 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8120 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8121 assert_eq!(node_txn.len(), 1);
8122 check_spends!(node_txn[0], remote_txn[0]);
8123 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8126 nodes[0].node.get_and_clear_pending_msg_events();
8128 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8129 disconnect_block(&nodes[0], &header, 102);
8131 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8132 assert_eq!(node_txn.len(), 1);
8133 check_spends!(node_txn[0], remote_txn[0]);
8134 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8138 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8139 disconnect_block(&nodes[0], &header, 101);
8140 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8142 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8143 assert_eq!(node_txn.len(), 0);
8149 fn test_counterparty_raa_skip_no_crash() {
8150 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8151 // commitment transaction, we would have happily carried on and provided them the next
8152 // commitment transaction based on one RAA forward. This would probably eventually have led to
8153 // channel closure, but it would not have resulted in funds loss. Still, our
8154 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8155 // check simply that the channel is closed in response to such an RAA, but don't check whether
8156 // we decide to punish our counterparty for revoking their funds (as we don't currently
8158 let chanmon_cfgs = create_chanmon_cfgs(2);
8159 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8160 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8161 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8162 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8164 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8165 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8166 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8167 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8168 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8169 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8171 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8172 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8173 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8174 check_added_monitors!(nodes[1], 1);
8178 fn test_bump_txn_sanitize_tracking_maps() {
8179 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8180 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8182 let chanmon_cfgs = create_chanmon_cfgs(2);
8183 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8184 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8185 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8187 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8188 // Lock HTLC in both directions
8189 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8190 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8192 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8193 assert_eq!(revoked_local_txn[0].input.len(), 1);
8194 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8196 // Revoke local commitment tx
8197 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8199 // Broadcast set of revoked txn on A
8200 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8201 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8203 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8204 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8205 check_closed_broadcast!(nodes[0], false);
8206 check_added_monitors!(nodes[0], 1);
8208 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8209 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8210 check_spends!(node_txn[0], revoked_local_txn[0]);
8211 check_spends!(node_txn[1], revoked_local_txn[0]);
8212 check_spends!(node_txn[2], revoked_local_txn[0]);
8213 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8217 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8218 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8219 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8221 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8222 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8223 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8224 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8230 fn test_override_channel_config() {
8231 let chanmon_cfgs = create_chanmon_cfgs(2);
8232 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8233 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8234 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8236 // Node0 initiates a channel to node1 using the override config.
8237 let mut override_config = UserConfig::default();
8238 override_config.own_channel_config.our_to_self_delay = 200;
8240 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8242 // Assert the channel created by node0 is using the override config.
8243 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8244 assert_eq!(res.channel_flags, 0);
8245 assert_eq!(res.to_self_delay, 200);
8249 fn test_override_0msat_htlc_minimum() {
8250 let mut zero_config = UserConfig::default();
8251 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8252 let chanmon_cfgs = create_chanmon_cfgs(2);
8253 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8254 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8255 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8257 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8258 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8259 assert_eq!(res.htlc_minimum_msat, 1);
8261 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8262 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8263 assert_eq!(res.htlc_minimum_msat, 1);
8267 fn test_simple_payment_secret() {
8268 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8269 // features, however.
8270 let chanmon_cfgs = create_chanmon_cfgs(3);
8271 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8272 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8273 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8275 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8276 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8277 let logger = test_utils::TestLogger::new();
8279 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8280 let payment_secret = PaymentSecret([0xdb; 32]);
8281 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8282 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();
8283 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8284 // Claiming with all the correct values but the wrong secret should result in nothing...
8285 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8286 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8287 // ...but with the right secret we should be able to claim all the way back
8288 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8292 fn test_simple_mpp() {
8293 // Simple test of sending a multi-path payment.
8294 let chanmon_cfgs = create_chanmon_cfgs(4);
8295 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8296 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8297 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8299 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8300 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8301 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8302 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8303 let logger = test_utils::TestLogger::new();
8305 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8306 let payment_secret = PaymentSecret([0xdb; 32]);
8307 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8308 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();
8309 let path = route.paths[0].clone();
8310 route.paths.push(path);
8311 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8312 route.paths[0][0].short_channel_id = chan_1_id;
8313 route.paths[0][1].short_channel_id = chan_3_id;
8314 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8315 route.paths[1][0].short_channel_id = chan_2_id;
8316 route.paths[1][1].short_channel_id = chan_4_id;
8317 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8318 // Claiming with all the correct values but the wrong secret should result in nothing...
8319 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8320 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8321 // ...but with the right secret we should be able to claim all the way back
8322 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8326 fn test_update_err_monitor_lockdown() {
8327 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8328 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8329 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8331 // This scenario may happen in a watchtower setup, where watchtower process a block height
8332 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8333 // commitment at same time.
8335 let chanmon_cfgs = create_chanmon_cfgs(2);
8336 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8337 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8338 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8340 // Create some initial channel
8341 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8342 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8344 // Rebalance the network to generate htlc in the two directions
8345 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8347 // Route a HTLC from node 0 to node 1 (but don't settle)
8348 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8350 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8351 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8352 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8354 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8355 let monitor = monitors.get(&outpoint).unwrap();
8356 let mut w = test_utils::TestVecWriter(Vec::new());
8357 monitor.write_for_disk(&mut w).unwrap();
8358 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8359 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8360 assert!(new_monitor == *monitor);
8361 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8362 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8365 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8366 watchtower.chain_monitor.block_connected(&header, &[], 200);
8368 // Try to update ChannelMonitor
8369 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8370 check_added_monitors!(nodes[1], 1);
8371 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8372 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8373 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8374 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8375 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8376 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8377 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8378 } else { assert!(false); }
8379 } else { assert!(false); };
8380 // Our local monitor is in-sync and hasn't processed yet timeout
8381 check_added_monitors!(nodes[0], 1);
8382 let events = nodes[0].node.get_and_clear_pending_events();
8383 assert_eq!(events.len(), 1);
8387 fn test_concurrent_monitor_claim() {
8388 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8389 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8390 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8391 // state N+1 confirms. Alice claims output from state N+1.
8393 let chanmon_cfgs = create_chanmon_cfgs(2);
8394 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8395 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8396 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8398 // Create some initial channel
8399 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8400 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8402 // Rebalance the network to generate htlc in the two directions
8403 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8405 // Route a HTLC from node 0 to node 1 (but don't settle)
8406 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8408 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8409 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8410 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8411 let watchtower_alice = {
8412 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8413 let monitor = monitors.get(&outpoint).unwrap();
8414 let mut w = test_utils::TestVecWriter(Vec::new());
8415 monitor.write_for_disk(&mut w).unwrap();
8416 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8417 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8418 assert!(new_monitor == *monitor);
8419 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8420 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8423 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8424 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8426 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8428 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8429 assert_eq!(txn.len(), 2);
8433 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8434 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8435 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8436 let watchtower_bob = {
8437 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8438 let monitor = monitors.get(&outpoint).unwrap();
8439 let mut w = test_utils::TestVecWriter(Vec::new());
8440 monitor.write_for_disk(&mut w).unwrap();
8441 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8442 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8443 assert!(new_monitor == *monitor);
8444 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8445 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8448 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8449 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8451 // Route another payment to generate another update with still previous HTLC pending
8452 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8454 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8455 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();
8456 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8458 check_added_monitors!(nodes[1], 1);
8460 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8461 assert_eq!(updates.update_add_htlcs.len(), 1);
8462 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8463 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8464 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8465 // Watchtower Alice should already have seen the block and reject the update
8466 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8467 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8468 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8469 } else { assert!(false); }
8470 } else { assert!(false); };
8471 // Our local monitor is in-sync and hasn't processed yet timeout
8472 check_added_monitors!(nodes[0], 1);
8474 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8475 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8477 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8480 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8481 assert_eq!(txn.len(), 2);
8482 bob_state_y = txn[0].clone();
8486 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8487 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8489 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8490 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8491 // the onchain detection of the HTLC output
8492 assert_eq!(htlc_txn.len(), 2);
8493 check_spends!(htlc_txn[0], bob_state_y);
8494 check_spends!(htlc_txn[1], bob_state_y);