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.
14 use chain::transaction::OutPoint;
15 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
16 use chain::chaininterface::{ChainListener, BlockNotifier};
17 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
18 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
19 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
20 use ln::channelmonitor;
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].chan_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].chan_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].chan_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].chan_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].chan_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].chan_monitor.simple_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 let mut height = 99;
3561 while !headers.is_empty() {
3562 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3565 check_closed_broadcast!(nodes[0], false);
3566 check_added_monitors!(nodes[0], 1);
3567 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3568 assert_eq!(channel_state.by_id.len(), 0);
3569 assert_eq!(channel_state.short_to_id.len(), 0);
3573 fn test_simple_peer_disconnect() {
3574 // Test that we can reconnect when there are no lost messages
3575 let chanmon_cfgs = create_chanmon_cfgs(3);
3576 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3577 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3578 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3579 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3580 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3582 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3583 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3584 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3586 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3587 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3588 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3589 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3591 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3592 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3593 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3595 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3596 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3597 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3598 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3600 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3601 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3603 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3604 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3606 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3608 let events = nodes[0].node.get_and_clear_pending_events();
3609 assert_eq!(events.len(), 2);
3611 Event::PaymentSent { payment_preimage } => {
3612 assert_eq!(payment_preimage, payment_preimage_3);
3614 _ => panic!("Unexpected event"),
3617 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3618 assert_eq!(payment_hash, payment_hash_5);
3619 assert!(rejected_by_dest);
3621 _ => panic!("Unexpected event"),
3625 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3626 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3629 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3630 // Test that we can reconnect when in-flight HTLC updates get dropped
3631 let chanmon_cfgs = create_chanmon_cfgs(2);
3632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3634 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3635 if messages_delivered == 0 {
3636 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3637 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3639 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3642 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3644 let logger = test_utils::TestLogger::new();
3645 let payment_event = {
3646 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3647 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3648 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3649 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3650 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3651 check_added_monitors!(nodes[0], 1);
3653 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3654 assert_eq!(events.len(), 1);
3655 SendEvent::from_event(events.remove(0))
3657 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3659 if messages_delivered < 2 {
3660 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3662 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3663 if messages_delivered >= 3 {
3664 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3665 check_added_monitors!(nodes[1], 1);
3666 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3668 if messages_delivered >= 4 {
3669 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3670 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3671 check_added_monitors!(nodes[0], 1);
3673 if messages_delivered >= 5 {
3674 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3675 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3676 // No commitment_signed so get_event_msg's assert(len == 1) passes
3677 check_added_monitors!(nodes[0], 1);
3679 if messages_delivered >= 6 {
3680 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3681 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3682 check_added_monitors!(nodes[1], 1);
3689 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3690 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3691 if messages_delivered < 3 {
3692 // Even if the funding_locked messages get exchanged, as long as nothing further was
3693 // received on either side, both sides will need to resend them.
3694 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3695 } else if messages_delivered == 3 {
3696 // nodes[0] still wants its RAA + commitment_signed
3697 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3698 } else if messages_delivered == 4 {
3699 // nodes[0] still wants its commitment_signed
3700 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3701 } else if messages_delivered == 5 {
3702 // nodes[1] still wants its final RAA
3703 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3704 } else if messages_delivered == 6 {
3705 // Everything was delivered...
3706 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3709 let events_1 = nodes[1].node.get_and_clear_pending_events();
3710 assert_eq!(events_1.len(), 1);
3712 Event::PendingHTLCsForwardable { .. } => { },
3713 _ => panic!("Unexpected event"),
3716 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3717 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3718 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3720 nodes[1].node.process_pending_htlc_forwards();
3722 let events_2 = nodes[1].node.get_and_clear_pending_events();
3723 assert_eq!(events_2.len(), 1);
3725 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3726 assert_eq!(payment_hash_1, *payment_hash);
3727 assert_eq!(*payment_secret, None);
3728 assert_eq!(amt, 1000000);
3730 _ => panic!("Unexpected event"),
3733 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3734 check_added_monitors!(nodes[1], 1);
3736 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3737 assert_eq!(events_3.len(), 1);
3738 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3739 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3740 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3741 assert!(updates.update_add_htlcs.is_empty());
3742 assert!(updates.update_fail_htlcs.is_empty());
3743 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3744 assert!(updates.update_fail_malformed_htlcs.is_empty());
3745 assert!(updates.update_fee.is_none());
3746 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3748 _ => panic!("Unexpected event"),
3751 if messages_delivered >= 1 {
3752 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3754 let events_4 = nodes[0].node.get_and_clear_pending_events();
3755 assert_eq!(events_4.len(), 1);
3757 Event::PaymentSent { ref payment_preimage } => {
3758 assert_eq!(payment_preimage_1, *payment_preimage);
3760 _ => panic!("Unexpected event"),
3763 if messages_delivered >= 2 {
3764 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3765 check_added_monitors!(nodes[0], 1);
3766 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3768 if messages_delivered >= 3 {
3769 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3771 check_added_monitors!(nodes[1], 1);
3773 if messages_delivered >= 4 {
3774 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3775 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3776 // No commitment_signed so get_event_msg's assert(len == 1) passes
3777 check_added_monitors!(nodes[1], 1);
3779 if messages_delivered >= 5 {
3780 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3781 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3782 check_added_monitors!(nodes[0], 1);
3789 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3790 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3791 if messages_delivered < 2 {
3792 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3793 //TODO: Deduplicate PaymentSent events, then enable this if:
3794 //if messages_delivered < 1 {
3795 let events_4 = nodes[0].node.get_and_clear_pending_events();
3796 assert_eq!(events_4.len(), 1);
3798 Event::PaymentSent { ref payment_preimage } => {
3799 assert_eq!(payment_preimage_1, *payment_preimage);
3801 _ => panic!("Unexpected event"),
3804 } else if messages_delivered == 2 {
3805 // nodes[0] still wants its RAA + commitment_signed
3806 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3807 } else if messages_delivered == 3 {
3808 // nodes[0] still wants its commitment_signed
3809 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3810 } else if messages_delivered == 4 {
3811 // nodes[1] still wants its final RAA
3812 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3813 } else if messages_delivered == 5 {
3814 // Everything was delivered...
3815 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3818 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3819 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3820 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3822 // Channel should still work fine...
3823 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3824 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3825 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3826 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3827 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3828 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3832 fn test_drop_messages_peer_disconnect_a() {
3833 do_test_drop_messages_peer_disconnect(0);
3834 do_test_drop_messages_peer_disconnect(1);
3835 do_test_drop_messages_peer_disconnect(2);
3836 do_test_drop_messages_peer_disconnect(3);
3840 fn test_drop_messages_peer_disconnect_b() {
3841 do_test_drop_messages_peer_disconnect(4);
3842 do_test_drop_messages_peer_disconnect(5);
3843 do_test_drop_messages_peer_disconnect(6);
3847 fn test_funding_peer_disconnect() {
3848 // Test that we can lock in our funding tx while disconnected
3849 let chanmon_cfgs = create_chanmon_cfgs(2);
3850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3852 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3853 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3855 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3856 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3858 confirm_transaction(&nodes[0], &tx);
3859 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3860 assert_eq!(events_1.len(), 1);
3862 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3863 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3865 _ => panic!("Unexpected event"),
3868 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3870 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3871 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3873 confirm_transaction(&nodes[1], &tx);
3874 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3875 assert_eq!(events_2.len(), 2);
3876 let funding_locked = match events_2[0] {
3877 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3878 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3881 _ => panic!("Unexpected event"),
3883 let bs_announcement_sigs = match events_2[1] {
3884 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3885 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3888 _ => panic!("Unexpected event"),
3891 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3893 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3894 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3895 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3896 assert_eq!(events_3.len(), 2);
3897 let as_announcement_sigs = match events_3[0] {
3898 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3899 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3902 _ => panic!("Unexpected event"),
3904 let (as_announcement, as_update) = match events_3[1] {
3905 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3906 (msg.clone(), update_msg.clone())
3908 _ => panic!("Unexpected event"),
3911 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3912 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3913 assert_eq!(events_4.len(), 1);
3914 let (_, bs_update) = match events_4[0] {
3915 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3916 (msg.clone(), update_msg.clone())
3918 _ => panic!("Unexpected event"),
3921 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3922 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3923 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3925 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3926 let logger = test_utils::TestLogger::new();
3927 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();
3928 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3929 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3933 fn test_drop_messages_peer_disconnect_dual_htlc() {
3934 // Test that we can handle reconnecting when both sides of a channel have pending
3935 // commitment_updates when we disconnect.
3936 let chanmon_cfgs = create_chanmon_cfgs(2);
3937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3939 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3940 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3941 let logger = test_utils::TestLogger::new();
3943 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3945 // Now try to send a second payment which will fail to send
3946 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3947 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3948 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();
3949 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3950 check_added_monitors!(nodes[0], 1);
3952 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3953 assert_eq!(events_1.len(), 1);
3955 MessageSendEvent::UpdateHTLCs { .. } => {},
3956 _ => panic!("Unexpected event"),
3959 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3960 check_added_monitors!(nodes[1], 1);
3962 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3963 assert_eq!(events_2.len(), 1);
3965 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 } } => {
3966 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3967 assert!(update_add_htlcs.is_empty());
3968 assert_eq!(update_fulfill_htlcs.len(), 1);
3969 assert!(update_fail_htlcs.is_empty());
3970 assert!(update_fail_malformed_htlcs.is_empty());
3971 assert!(update_fee.is_none());
3973 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3974 let events_3 = nodes[0].node.get_and_clear_pending_events();
3975 assert_eq!(events_3.len(), 1);
3977 Event::PaymentSent { ref payment_preimage } => {
3978 assert_eq!(*payment_preimage, payment_preimage_1);
3980 _ => panic!("Unexpected event"),
3983 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3984 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3985 // No commitment_signed so get_event_msg's assert(len == 1) passes
3986 check_added_monitors!(nodes[0], 1);
3988 _ => panic!("Unexpected event"),
3991 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3992 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3994 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3995 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3996 assert_eq!(reestablish_1.len(), 1);
3997 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3998 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3999 assert_eq!(reestablish_2.len(), 1);
4001 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4002 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4003 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4004 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4006 assert!(as_resp.0.is_none());
4007 assert!(bs_resp.0.is_none());
4009 assert!(bs_resp.1.is_none());
4010 assert!(bs_resp.2.is_none());
4012 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4014 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4015 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4016 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4017 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4018 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4019 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4020 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4021 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4022 // No commitment_signed so get_event_msg's assert(len == 1) passes
4023 check_added_monitors!(nodes[1], 1);
4025 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4026 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4027 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4028 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4029 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4030 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4031 assert!(bs_second_commitment_signed.update_fee.is_none());
4032 check_added_monitors!(nodes[1], 1);
4034 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4035 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4036 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4037 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4038 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4039 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4040 assert!(as_commitment_signed.update_fee.is_none());
4041 check_added_monitors!(nodes[0], 1);
4043 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4044 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4045 // No commitment_signed so get_event_msg's assert(len == 1) passes
4046 check_added_monitors!(nodes[0], 1);
4048 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4049 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4050 // No commitment_signed so get_event_msg's assert(len == 1) passes
4051 check_added_monitors!(nodes[1], 1);
4053 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4054 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4055 check_added_monitors!(nodes[1], 1);
4057 expect_pending_htlcs_forwardable!(nodes[1]);
4059 let events_5 = nodes[1].node.get_and_clear_pending_events();
4060 assert_eq!(events_5.len(), 1);
4062 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4063 assert_eq!(payment_hash_2, *payment_hash);
4064 assert_eq!(*payment_secret, None);
4066 _ => panic!("Unexpected event"),
4069 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4070 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4071 check_added_monitors!(nodes[0], 1);
4073 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4076 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4077 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4078 // to avoid our counterparty failing the channel.
4079 let chanmon_cfgs = create_chanmon_cfgs(2);
4080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4082 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4084 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4085 let logger = test_utils::TestLogger::new();
4087 let our_payment_hash = if send_partial_mpp {
4088 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4089 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();
4090 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4091 let payment_secret = PaymentSecret([0xdb; 32]);
4092 // Use the utility function send_payment_along_path to send the payment with MPP data which
4093 // indicates there are more HTLCs coming.
4094 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4095 check_added_monitors!(nodes[0], 1);
4096 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4097 assert_eq!(events.len(), 1);
4098 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4099 // hop should *not* yet generate any PaymentReceived event(s).
4100 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4103 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4106 let mut block = Block {
4107 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4110 connect_block(&nodes[0], &block, 101);
4111 connect_block(&nodes[1], &block, 101);
4112 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4113 block.header.prev_blockhash = block.block_hash();
4114 connect_block(&nodes[0], &block, i);
4115 connect_block(&nodes[1], &block, i);
4118 expect_pending_htlcs_forwardable!(nodes[1]);
4120 check_added_monitors!(nodes[1], 1);
4121 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4122 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4123 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4124 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4125 assert!(htlc_timeout_updates.update_fee.is_none());
4127 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4128 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4129 // 100_000 msat as u64, followed by a height of 123 as u32
4130 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4131 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4132 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4136 fn test_htlc_timeout() {
4137 do_test_htlc_timeout(true);
4138 do_test_htlc_timeout(false);
4141 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4142 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4143 let chanmon_cfgs = create_chanmon_cfgs(3);
4144 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4145 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4146 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4147 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4148 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4149 let logger = test_utils::TestLogger::new();
4151 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4152 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4154 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4155 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();
4156 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4158 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4159 check_added_monitors!(nodes[1], 1);
4161 // Now attempt to route a second payment, which should be placed in the holding cell
4162 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4164 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4165 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();
4166 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4167 check_added_monitors!(nodes[0], 1);
4168 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4169 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4170 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4171 expect_pending_htlcs_forwardable!(nodes[1]);
4172 check_added_monitors!(nodes[1], 0);
4174 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4175 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();
4176 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4177 check_added_monitors!(nodes[1], 0);
4180 let mut block = Block {
4181 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4184 connect_block(&nodes[1], &block, 101);
4185 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4186 block.header.prev_blockhash = block.block_hash();
4187 connect_block(&nodes[1], &block, i);
4190 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4191 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4193 block.header.prev_blockhash = block.block_hash();
4194 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4197 expect_pending_htlcs_forwardable!(nodes[1]);
4198 check_added_monitors!(nodes[1], 1);
4199 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4200 assert_eq!(fail_commit.len(), 1);
4201 match fail_commit[0] {
4202 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4203 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4204 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4206 _ => unreachable!(),
4208 expect_payment_failed!(nodes[0], second_payment_hash, false);
4209 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4211 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4212 _ => panic!("Unexpected event"),
4215 panic!("Unexpected event");
4218 expect_payment_failed!(nodes[1], second_payment_hash, true);
4223 fn test_holding_cell_htlc_add_timeouts() {
4224 do_test_holding_cell_htlc_add_timeouts(false);
4225 do_test_holding_cell_htlc_add_timeouts(true);
4229 fn test_invalid_channel_announcement() {
4230 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4231 let secp_ctx = Secp256k1::new();
4232 let chanmon_cfgs = create_chanmon_cfgs(2);
4233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4237 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4239 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4240 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4241 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4242 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4244 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 } );
4246 let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4247 let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4249 let as_network_key = nodes[0].node.get_our_node_id();
4250 let bs_network_key = nodes[1].node.get_our_node_id();
4252 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4254 let mut chan_announcement;
4256 macro_rules! dummy_unsigned_msg {
4258 msgs::UnsignedChannelAnnouncement {
4259 features: ChannelFeatures::known(),
4260 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4261 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4262 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4263 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4264 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4265 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4266 excess_data: Vec::new(),
4271 macro_rules! sign_msg {
4272 ($unsigned_msg: expr) => {
4273 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4274 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4275 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4276 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4277 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4278 chan_announcement = msgs::ChannelAnnouncement {
4279 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4280 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4281 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4282 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4283 contents: $unsigned_msg
4288 let unsigned_msg = dummy_unsigned_msg!();
4289 sign_msg!(unsigned_msg);
4290 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4291 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 } );
4293 // Configured with Network::Testnet
4294 let mut unsigned_msg = dummy_unsigned_msg!();
4295 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4296 sign_msg!(unsigned_msg);
4297 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4299 let mut unsigned_msg = dummy_unsigned_msg!();
4300 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4301 sign_msg!(unsigned_msg);
4302 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4306 fn test_no_txn_manager_serialize_deserialize() {
4307 let chanmon_cfgs = create_chanmon_cfgs(2);
4308 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4309 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4310 let logger: test_utils::TestLogger;
4311 let fee_estimator: test_utils::TestFeeEstimator;
4312 let new_chan_monitor: test_utils::TestChannelMonitor;
4313 let keys_manager: test_utils::TestKeysInterface;
4314 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4315 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4317 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4319 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4321 let nodes_0_serialized = nodes[0].node.encode();
4322 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4323 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4325 logger = test_utils::TestLogger::new();
4326 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4327 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4328 nodes[0].chan_monitor = &new_chan_monitor;
4329 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4330 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4331 assert!(chan_0_monitor_read.is_empty());
4333 let mut nodes_0_read = &nodes_0_serialized[..];
4334 let config = UserConfig::default();
4335 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4336 let (_, nodes_0_deserialized_tmp) = {
4337 let mut channel_monitors = HashMap::new();
4338 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4339 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4340 default_config: config,
4341 keys_manager: &keys_manager,
4342 fee_estimator: &fee_estimator,
4343 monitor: nodes[0].chan_monitor,
4344 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4349 nodes_0_deserialized = nodes_0_deserialized_tmp;
4350 assert!(nodes_0_read.is_empty());
4352 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4353 nodes[0].node = &nodes_0_deserialized;
4354 nodes[0].block_notifier.register_listener(nodes[0].node);
4355 assert_eq!(nodes[0].node.list_channels().len(), 1);
4356 check_added_monitors!(nodes[0], 1);
4358 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4359 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4360 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4361 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4363 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4364 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4365 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4366 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4368 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4369 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4370 for node in nodes.iter() {
4371 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4372 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4373 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4376 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4380 fn test_manager_serialize_deserialize_events() {
4381 // This test makes sure the events field in ChannelManager survives de/serialization
4382 let chanmon_cfgs = create_chanmon_cfgs(2);
4383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4385 let fee_estimator: test_utils::TestFeeEstimator;
4386 let logger: test_utils::TestLogger;
4387 let new_chan_monitor: test_utils::TestChannelMonitor;
4388 let keys_manager: test_utils::TestKeysInterface;
4389 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4390 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4392 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4393 let channel_value = 100000;
4394 let push_msat = 10001;
4395 let a_flags = InitFeatures::known();
4396 let b_flags = InitFeatures::known();
4397 let node_a = nodes.pop().unwrap();
4398 let node_b = nodes.pop().unwrap();
4399 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4400 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()));
4401 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()));
4403 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4405 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4406 check_added_monitors!(node_a, 0);
4408 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()));
4410 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
4411 assert_eq!(added_monitors.len(), 1);
4412 assert_eq!(added_monitors[0].0, funding_output);
4413 added_monitors.clear();
4416 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()));
4418 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
4419 assert_eq!(added_monitors.len(), 1);
4420 assert_eq!(added_monitors[0].0, funding_output);
4421 added_monitors.clear();
4423 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4428 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4429 let nodes_0_serialized = nodes[0].node.encode();
4430 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4431 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4433 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4434 logger = test_utils::TestLogger::new();
4435 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4436 nodes[0].chan_monitor = &new_chan_monitor;
4437 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4438 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4439 assert!(chan_0_monitor_read.is_empty());
4441 let mut nodes_0_read = &nodes_0_serialized[..];
4442 let config = UserConfig::default();
4443 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4444 let (_, nodes_0_deserialized_tmp) = {
4445 let mut channel_monitors = HashMap::new();
4446 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4447 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4448 default_config: config,
4449 keys_manager: &keys_manager,
4450 fee_estimator: &fee_estimator,
4451 monitor: nodes[0].chan_monitor,
4452 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4457 nodes_0_deserialized = nodes_0_deserialized_tmp;
4458 assert!(nodes_0_read.is_empty());
4460 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4462 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4463 nodes[0].node = &nodes_0_deserialized;
4465 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4466 let events_4 = nodes[0].node.get_and_clear_pending_events();
4467 assert_eq!(events_4.len(), 1);
4469 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4470 assert_eq!(user_channel_id, 42);
4471 assert_eq!(*funding_txo, funding_output);
4473 _ => panic!("Unexpected event"),
4476 // Make sure the channel is functioning as though the de/serialization never happened
4477 nodes[0].block_notifier.register_listener(nodes[0].node);
4478 assert_eq!(nodes[0].node.list_channels().len(), 1);
4479 check_added_monitors!(nodes[0], 1);
4481 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4482 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4483 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4484 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4486 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4487 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4488 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4489 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4491 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4492 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4493 for node in nodes.iter() {
4494 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4495 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4496 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4499 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4503 fn test_simple_manager_serialize_deserialize() {
4504 let chanmon_cfgs = create_chanmon_cfgs(2);
4505 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4506 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4507 let logger: test_utils::TestLogger;
4508 let fee_estimator: test_utils::TestFeeEstimator;
4509 let new_chan_monitor: test_utils::TestChannelMonitor;
4510 let keys_manager: test_utils::TestKeysInterface;
4511 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4512 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4513 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4515 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4516 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4518 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4520 let nodes_0_serialized = nodes[0].node.encode();
4521 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4522 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4524 logger = test_utils::TestLogger::new();
4525 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4526 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4527 nodes[0].chan_monitor = &new_chan_monitor;
4528 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4529 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4530 assert!(chan_0_monitor_read.is_empty());
4532 let mut nodes_0_read = &nodes_0_serialized[..];
4533 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4534 let (_, nodes_0_deserialized_tmp) = {
4535 let mut channel_monitors = HashMap::new();
4536 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4537 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4538 default_config: UserConfig::default(),
4539 keys_manager: &keys_manager,
4540 fee_estimator: &fee_estimator,
4541 monitor: nodes[0].chan_monitor,
4542 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4547 nodes_0_deserialized = nodes_0_deserialized_tmp;
4548 assert!(nodes_0_read.is_empty());
4550 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4551 nodes[0].node = &nodes_0_deserialized;
4552 check_added_monitors!(nodes[0], 1);
4554 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4556 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4557 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4561 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4562 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4563 let chanmon_cfgs = create_chanmon_cfgs(4);
4564 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4565 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4566 let logger: test_utils::TestLogger;
4567 let fee_estimator: test_utils::TestFeeEstimator;
4568 let new_chan_monitor: test_utils::TestChannelMonitor;
4569 let keys_manager: test_utils::TestKeysInterface;
4570 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4571 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4572 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4573 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4574 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4576 let mut node_0_stale_monitors_serialized = Vec::new();
4577 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4578 let mut writer = test_utils::TestVecWriter(Vec::new());
4579 monitor.1.write_for_disk(&mut writer).unwrap();
4580 node_0_stale_monitors_serialized.push(writer.0);
4583 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4585 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4586 let nodes_0_serialized = nodes[0].node.encode();
4588 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4589 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4590 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4591 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4593 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4595 let mut node_0_monitors_serialized = Vec::new();
4596 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4597 let mut writer = test_utils::TestVecWriter(Vec::new());
4598 monitor.1.write_for_disk(&mut writer).unwrap();
4599 node_0_monitors_serialized.push(writer.0);
4602 logger = test_utils::TestLogger::new();
4603 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4604 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4605 nodes[0].chan_monitor = &new_chan_monitor;
4607 let mut node_0_stale_monitors = Vec::new();
4608 for serialized in node_0_stale_monitors_serialized.iter() {
4609 let mut read = &serialized[..];
4610 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4611 assert!(read.is_empty());
4612 node_0_stale_monitors.push(monitor);
4615 let mut node_0_monitors = Vec::new();
4616 for serialized in node_0_monitors_serialized.iter() {
4617 let mut read = &serialized[..];
4618 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4619 assert!(read.is_empty());
4620 node_0_monitors.push(monitor);
4623 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4625 let mut nodes_0_read = &nodes_0_serialized[..];
4626 if let Err(msgs::DecodeError::InvalidValue) =
4627 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4628 default_config: UserConfig::default(),
4629 keys_manager: &keys_manager,
4630 fee_estimator: &fee_estimator,
4631 monitor: nodes[0].chan_monitor,
4632 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4634 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4636 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4639 let mut nodes_0_read = &nodes_0_serialized[..];
4640 let (_, nodes_0_deserialized_tmp) =
4641 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4642 default_config: UserConfig::default(),
4643 keys_manager: &keys_manager,
4644 fee_estimator: &fee_estimator,
4645 monitor: nodes[0].chan_monitor,
4646 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4648 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4650 nodes_0_deserialized = nodes_0_deserialized_tmp;
4651 assert!(nodes_0_read.is_empty());
4653 { // Channel close should result in a commitment tx and an HTLC tx
4654 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4655 assert_eq!(txn.len(), 2);
4656 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4657 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4660 for monitor in node_0_monitors.drain(..) {
4661 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().0, monitor).is_ok());
4662 check_added_monitors!(nodes[0], 1);
4664 nodes[0].node = &nodes_0_deserialized;
4666 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4667 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4668 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4669 //... and we can even still claim the payment!
4670 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4672 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4673 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4674 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4675 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4676 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4677 assert_eq!(msg_events.len(), 1);
4678 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4680 &ErrorAction::SendErrorMessage { ref msg } => {
4681 assert_eq!(msg.channel_id, channel_id);
4683 _ => panic!("Unexpected event!"),
4688 macro_rules! check_spendable_outputs {
4689 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4691 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4692 let mut txn = Vec::new();
4693 for event in events {
4695 Event::SpendableOutputs { ref outputs } => {
4696 for outp in outputs {
4698 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4700 previous_output: outpoint.into_bitcoin_outpoint(),
4701 script_sig: Script::new(),
4703 witness: Vec::new(),
4706 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4707 value: output.value,
4709 let mut spend_tx = Transaction {
4715 let secp_ctx = Secp256k1::new();
4716 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4717 let remotepubkey = keys.pubkeys().payment_point;
4718 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4719 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4720 let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4721 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4722 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4723 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4726 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4728 previous_output: outpoint.into_bitcoin_outpoint(),
4729 script_sig: Script::new(),
4730 sequence: *to_self_delay as u32,
4731 witness: Vec::new(),
4734 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4735 value: output.value,
4737 let mut spend_tx = Transaction {
4743 let secp_ctx = Secp256k1::new();
4744 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4745 if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4747 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4748 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4749 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4750 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4751 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4752 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4753 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4754 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4758 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4759 let secp_ctx = Secp256k1::new();
4761 previous_output: outpoint.into_bitcoin_outpoint(),
4762 script_sig: Script::new(),
4764 witness: Vec::new(),
4767 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4768 value: output.value,
4770 let mut spend_tx = Transaction {
4774 output: vec![outp.clone()],
4777 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4779 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4781 Err(_) => panic!("Your RNG is busted"),
4784 Err(_) => panic!("Your rng is busted"),
4787 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4788 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4789 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4790 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4791 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4792 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4793 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4799 _ => panic!("Unexpected event"),
4808 fn test_claim_sizeable_push_msat() {
4809 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4810 let chanmon_cfgs = create_chanmon_cfgs(2);
4811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4813 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4815 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4816 nodes[1].node.force_close_channel(&chan.2);
4817 check_closed_broadcast!(nodes[1], false);
4818 check_added_monitors!(nodes[1], 1);
4819 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4820 assert_eq!(node_txn.len(), 1);
4821 check_spends!(node_txn[0], chan.3);
4822 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
4824 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4825 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4826 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4828 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4829 assert_eq!(spend_txn.len(), 1);
4830 check_spends!(spend_txn[0], node_txn[0]);
4834 fn test_claim_on_remote_sizeable_push_msat() {
4835 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4836 // to_remote output is encumbered by a P2WPKH
4837 let chanmon_cfgs = create_chanmon_cfgs(2);
4838 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4839 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4840 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4842 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4843 nodes[0].node.force_close_channel(&chan.2);
4844 check_closed_broadcast!(nodes[0], false);
4845 check_added_monitors!(nodes[0], 1);
4847 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4848 assert_eq!(node_txn.len(), 1);
4849 check_spends!(node_txn[0], chan.3);
4850 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
4852 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4853 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4854 check_closed_broadcast!(nodes[1], false);
4855 check_added_monitors!(nodes[1], 1);
4856 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4858 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4859 assert_eq!(spend_txn.len(), 2);
4860 assert_eq!(spend_txn[0], spend_txn[1]);
4861 check_spends!(spend_txn[0], node_txn[0]);
4865 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4866 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4867 // to_remote output is encumbered by a P2WPKH
4869 let chanmon_cfgs = create_chanmon_cfgs(2);
4870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4872 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4874 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4875 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4876 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4877 assert_eq!(revoked_local_txn[0].input.len(), 1);
4878 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4880 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4881 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4882 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4883 check_closed_broadcast!(nodes[1], false);
4884 check_added_monitors!(nodes[1], 1);
4886 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4887 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4888 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4889 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4891 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4892 assert_eq!(spend_txn.len(), 3);
4893 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4894 check_spends!(spend_txn[0], revoked_local_txn[0]);
4895 check_spends!(spend_txn[2], node_txn[0]);
4899 fn test_static_spendable_outputs_preimage_tx() {
4900 let chanmon_cfgs = create_chanmon_cfgs(2);
4901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4903 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4905 // Create some initial channels
4906 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4908 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4910 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4911 assert_eq!(commitment_tx[0].input.len(), 1);
4912 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4914 // Settle A's commitment tx on B's chain
4915 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4916 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4917 check_added_monitors!(nodes[1], 1);
4918 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4919 check_added_monitors!(nodes[1], 1);
4920 let events = nodes[1].node.get_and_clear_pending_msg_events();
4922 MessageSendEvent::UpdateHTLCs { .. } => {},
4923 _ => panic!("Unexpected event"),
4926 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4927 _ => panic!("Unexepected event"),
4930 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4931 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4932 assert_eq!(node_txn.len(), 3);
4933 check_spends!(node_txn[0], commitment_tx[0]);
4934 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4935 check_spends!(node_txn[1], chan_1.3);
4936 check_spends!(node_txn[2], node_txn[1]);
4938 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4939 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4940 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4942 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4943 assert_eq!(spend_txn.len(), 1);
4944 check_spends!(spend_txn[0], node_txn[0]);
4948 fn test_static_spendable_outputs_timeout_tx() {
4949 let chanmon_cfgs = create_chanmon_cfgs(2);
4950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4952 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4954 // Create some initial channels
4955 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4957 // Rebalance the network a bit by relaying one payment through all the channels ...
4958 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4960 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4962 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4963 assert_eq!(commitment_tx[0].input.len(), 1);
4964 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4966 // Settle A's commitment tx on B' chain
4967 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4968 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4969 check_added_monitors!(nodes[1], 1);
4970 let events = nodes[1].node.get_and_clear_pending_msg_events();
4972 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4973 _ => panic!("Unexpected event"),
4976 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4977 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4978 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4979 check_spends!(node_txn[0], commitment_tx[0].clone());
4980 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4981 check_spends!(node_txn[1], chan_1.3.clone());
4982 check_spends!(node_txn[2], node_txn[1]);
4984 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4985 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4986 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4987 expect_payment_failed!(nodes[1], our_payment_hash, true);
4989 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4990 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4991 check_spends!(spend_txn[2], node_txn[0].clone());
4995 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4996 let chanmon_cfgs = create_chanmon_cfgs(2);
4997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5001 // Create some initial channels
5002 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5004 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5005 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5006 assert_eq!(revoked_local_txn[0].input.len(), 1);
5007 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5009 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5011 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5012 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
5013 check_closed_broadcast!(nodes[1], false);
5014 check_added_monitors!(nodes[1], 1);
5016 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5017 assert_eq!(node_txn.len(), 2);
5018 assert_eq!(node_txn[0].input.len(), 2);
5019 check_spends!(node_txn[0], revoked_local_txn[0]);
5021 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5022 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
5023 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5025 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5026 assert_eq!(spend_txn.len(), 1);
5027 check_spends!(spend_txn[0], node_txn[0]);
5031 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5032 let chanmon_cfgs = create_chanmon_cfgs(2);
5033 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5034 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5035 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5037 // Create some initial channels
5038 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5040 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5041 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5042 assert_eq!(revoked_local_txn[0].input.len(), 1);
5043 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5045 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5047 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5048 // A will generate HTLC-Timeout from revoked commitment tx
5049 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5050 check_closed_broadcast!(nodes[0], false);
5051 check_added_monitors!(nodes[0], 1);
5053 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5054 assert_eq!(revoked_htlc_txn.len(), 2);
5055 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5056 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5057 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5058 check_spends!(revoked_htlc_txn[1], chan_1.3);
5060 // B will generate justice tx from A's revoked commitment/HTLC tx
5061 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5062 check_closed_broadcast!(nodes[1], false);
5063 check_added_monitors!(nodes[1], 1);
5065 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5066 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5067 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5068 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5069 // transactions next...
5070 assert_eq!(node_txn[0].input.len(), 3);
5071 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5073 assert_eq!(node_txn[1].input.len(), 2);
5074 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5075 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5076 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5078 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5079 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5082 assert_eq!(node_txn[2].input.len(), 1);
5083 check_spends!(node_txn[2], chan_1.3);
5085 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5086 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5087 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5089 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5090 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5091 assert_eq!(spend_txn.len(), 1);
5092 assert_eq!(spend_txn[0].input.len(), 1);
5093 check_spends!(spend_txn[0], node_txn[1]);
5097 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5098 let chanmon_cfgs = create_chanmon_cfgs(2);
5099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5101 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5103 // Create some initial channels
5104 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5106 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5107 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5108 assert_eq!(revoked_local_txn[0].input.len(), 1);
5109 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5111 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5112 assert_eq!(revoked_local_txn[0].output.len(), 2);
5114 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5116 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5117 // B will generate HTLC-Success from revoked commitment tx
5118 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5119 check_closed_broadcast!(nodes[1], false);
5120 check_added_monitors!(nodes[1], 1);
5121 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5123 assert_eq!(revoked_htlc_txn.len(), 2);
5124 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5125 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5126 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5128 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5129 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5130 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5132 // A will generate justice tx from B's revoked commitment/HTLC tx
5133 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5134 check_closed_broadcast!(nodes[0], false);
5135 check_added_monitors!(nodes[0], 1);
5137 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5138 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5140 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5141 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5142 // transactions next...
5143 assert_eq!(node_txn[0].input.len(), 2);
5144 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5145 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5146 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5148 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5149 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5152 assert_eq!(node_txn[1].input.len(), 1);
5153 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5155 check_spends!(node_txn[2], chan_1.3);
5157 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5158 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5159 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5161 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5162 // didn't try to generate any new transactions.
5164 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5165 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5166 assert_eq!(spend_txn.len(), 3); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5167 assert_eq!(spend_txn[0], spend_txn[1]);
5168 assert_eq!(spend_txn[0].input.len(), 1);
5169 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5170 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5171 check_spends!(spend_txn[2], node_txn[1]); // spending justice tx output on the htlc success tx
5175 fn test_onchain_to_onchain_claim() {
5176 // Test that in case of channel closure, we detect the state of output and claim HTLC
5177 // on downstream peer's remote commitment tx.
5178 // First, have C claim an HTLC against its own latest commitment transaction.
5179 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5181 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5184 let chanmon_cfgs = create_chanmon_cfgs(3);
5185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5187 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5189 // Create some initial channels
5190 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5191 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5193 // Rebalance the network a bit by relaying one payment through all the channels ...
5194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5195 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5197 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5198 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5199 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5200 check_spends!(commitment_tx[0], chan_2.3);
5201 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5202 check_added_monitors!(nodes[2], 1);
5203 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5204 assert!(updates.update_add_htlcs.is_empty());
5205 assert!(updates.update_fail_htlcs.is_empty());
5206 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5207 assert!(updates.update_fail_malformed_htlcs.is_empty());
5209 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5210 check_closed_broadcast!(nodes[2], false);
5211 check_added_monitors!(nodes[2], 1);
5213 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5214 assert_eq!(c_txn.len(), 3);
5215 assert_eq!(c_txn[0], c_txn[2]);
5216 assert_eq!(commitment_tx[0], c_txn[1]);
5217 check_spends!(c_txn[1], chan_2.3);
5218 check_spends!(c_txn[2], c_txn[1]);
5219 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5220 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5221 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5222 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5224 // 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
5225 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5227 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5228 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5229 assert_eq!(b_txn.len(), 3);
5230 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5231 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5232 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5233 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5234 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5235 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5236 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5237 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5238 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5241 check_added_monitors!(nodes[1], 1);
5242 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5243 check_added_monitors!(nodes[1], 1);
5244 match msg_events[0] {
5245 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5246 _ => panic!("Unexpected event"),
5248 match msg_events[1] {
5249 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, .. } } => {
5250 assert!(update_add_htlcs.is_empty());
5251 assert!(update_fail_htlcs.is_empty());
5252 assert_eq!(update_fulfill_htlcs.len(), 1);
5253 assert!(update_fail_malformed_htlcs.is_empty());
5254 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5256 _ => panic!("Unexpected event"),
5258 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5259 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5260 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5261 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5262 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5263 assert_eq!(b_txn.len(), 3);
5264 check_spends!(b_txn[1], chan_1.3);
5265 check_spends!(b_txn[2], b_txn[1]);
5266 check_spends!(b_txn[0], commitment_tx[0]);
5267 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5268 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5269 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5271 check_closed_broadcast!(nodes[1], false);
5272 check_added_monitors!(nodes[1], 1);
5276 fn test_duplicate_payment_hash_one_failure_one_success() {
5277 // Topology : A --> B --> C
5278 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5279 let chanmon_cfgs = create_chanmon_cfgs(3);
5280 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5281 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5282 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5284 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5285 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5287 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5288 *nodes[0].network_payment_count.borrow_mut() -= 1;
5289 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5291 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5292 assert_eq!(commitment_txn[0].input.len(), 1);
5293 check_spends!(commitment_txn[0], chan_2.3);
5295 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5296 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5297 check_closed_broadcast!(nodes[1], false);
5298 check_added_monitors!(nodes[1], 1);
5300 let htlc_timeout_tx;
5301 { // Extract one of the two HTLC-Timeout transaction
5302 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5303 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5304 assert_eq!(node_txn.len(), 5);
5305 check_spends!(node_txn[0], commitment_txn[0]);
5306 assert_eq!(node_txn[0].input.len(), 1);
5307 check_spends!(node_txn[1], commitment_txn[0]);
5308 assert_eq!(node_txn[1].input.len(), 1);
5309 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5310 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5311 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5312 check_spends!(node_txn[2], chan_2.3);
5313 check_spends!(node_txn[3], node_txn[2]);
5314 check_spends!(node_txn[4], node_txn[2]);
5315 htlc_timeout_tx = node_txn[1].clone();
5318 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5319 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5320 check_added_monitors!(nodes[2], 3);
5321 let events = nodes[2].node.get_and_clear_pending_msg_events();
5323 MessageSendEvent::UpdateHTLCs { .. } => {},
5324 _ => panic!("Unexpected event"),
5327 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5328 _ => panic!("Unexepected event"),
5330 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5331 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)
5332 check_spends!(htlc_success_txn[2], chan_2.3);
5333 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5334 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5335 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5336 assert_eq!(htlc_success_txn[0].input.len(), 1);
5337 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5338 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5339 assert_eq!(htlc_success_txn[1].input.len(), 1);
5340 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5341 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5342 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5343 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5345 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5346 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5347 expect_pending_htlcs_forwardable!(nodes[1]);
5348 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5349 assert!(htlc_updates.update_add_htlcs.is_empty());
5350 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5351 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5352 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5353 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5354 check_added_monitors!(nodes[1], 1);
5356 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5357 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5359 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5360 let events = nodes[0].node.get_and_clear_pending_msg_events();
5361 assert_eq!(events.len(), 1);
5363 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5365 _ => { panic!("Unexpected event"); }
5368 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5370 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5371 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5372 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5373 assert!(updates.update_add_htlcs.is_empty());
5374 assert!(updates.update_fail_htlcs.is_empty());
5375 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5376 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5377 assert!(updates.update_fail_malformed_htlcs.is_empty());
5378 check_added_monitors!(nodes[1], 1);
5380 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5381 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5383 let events = nodes[0].node.get_and_clear_pending_events();
5385 Event::PaymentSent { ref payment_preimage } => {
5386 assert_eq!(*payment_preimage, our_payment_preimage);
5388 _ => panic!("Unexpected event"),
5393 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5394 let chanmon_cfgs = create_chanmon_cfgs(2);
5395 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5396 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5397 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5399 // Create some initial channels
5400 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5402 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5403 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5404 assert_eq!(local_txn[0].input.len(), 1);
5405 check_spends!(local_txn[0], chan_1.3);
5407 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5408 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5409 check_added_monitors!(nodes[1], 1);
5410 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5411 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5412 check_added_monitors!(nodes[1], 1);
5413 let events = nodes[1].node.get_and_clear_pending_msg_events();
5415 MessageSendEvent::UpdateHTLCs { .. } => {},
5416 _ => panic!("Unexpected event"),
5419 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5420 _ => panic!("Unexepected event"),
5423 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5424 assert_eq!(node_txn[0].input.len(), 1);
5425 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5426 check_spends!(node_txn[0], local_txn[0]);
5427 vec![node_txn[0].clone(), node_txn[2].clone()]
5430 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5431 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5432 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5434 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5435 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5436 assert_eq!(spend_txn.len(), 2);
5437 check_spends!(spend_txn[0], node_txn[0]);
5438 check_spends!(spend_txn[1], node_txn[1]);
5441 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5442 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5443 // unrevoked commitment transaction.
5444 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5445 // a remote RAA before they could be failed backwards (and combinations thereof).
5446 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5447 // use the same payment hashes.
5448 // Thus, we use a six-node network:
5453 // And test where C fails back to A/B when D announces its latest commitment transaction
5454 let chanmon_cfgs = create_chanmon_cfgs(6);
5455 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5456 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5457 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5458 let logger = test_utils::TestLogger::new();
5460 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5461 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5462 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5463 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5464 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5466 // Rebalance and check output sanity...
5467 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5468 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5469 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5471 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5473 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
5475 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
5476 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5477 let our_node_id = &nodes[1].node.get_our_node_id();
5478 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();
5480 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
5482 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
5484 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5486 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5487 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();
5489 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5491 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5494 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5496 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();
5497 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
5500 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
5502 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();
5503 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5505 // Double-check that six of the new HTLC were added
5506 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5507 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5508 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5509 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5511 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5512 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5513 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5514 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5515 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5516 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5517 check_added_monitors!(nodes[4], 0);
5518 expect_pending_htlcs_forwardable!(nodes[4]);
5519 check_added_monitors!(nodes[4], 1);
5521 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5522 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5523 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5524 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5525 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5526 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5528 // Fail 3rd below-dust and 7th above-dust HTLCs
5529 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5530 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5531 check_added_monitors!(nodes[5], 0);
5532 expect_pending_htlcs_forwardable!(nodes[5]);
5533 check_added_monitors!(nodes[5], 1);
5535 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5536 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5537 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5538 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5540 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5542 expect_pending_htlcs_forwardable!(nodes[3]);
5543 check_added_monitors!(nodes[3], 1);
5544 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5545 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5546 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5547 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5548 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5549 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5550 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5551 if deliver_last_raa {
5552 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5554 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5557 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5558 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5559 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5560 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5562 // We now broadcast the latest commitment transaction, which *should* result in failures for
5563 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5564 // the non-broadcast above-dust HTLCs.
5566 // Alternatively, we may broadcast the previous commitment transaction, which should only
5567 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5568 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5570 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5571 if announce_latest {
5572 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5574 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5576 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5577 check_closed_broadcast!(nodes[2], false);
5578 expect_pending_htlcs_forwardable!(nodes[2]);
5579 check_added_monitors!(nodes[2], 3);
5581 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5582 assert_eq!(cs_msgs.len(), 2);
5583 let mut a_done = false;
5584 for msg in cs_msgs {
5586 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5587 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5588 // should be failed-backwards here.
5589 let target = if *node_id == nodes[0].node.get_our_node_id() {
5590 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5591 for htlc in &updates.update_fail_htlcs {
5592 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 });
5594 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5599 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5600 for htlc in &updates.update_fail_htlcs {
5601 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5603 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5604 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5607 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5608 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5609 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5610 if announce_latest {
5611 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5612 if *node_id == nodes[0].node.get_our_node_id() {
5613 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5616 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5618 _ => panic!("Unexpected event"),
5622 let as_events = nodes[0].node.get_and_clear_pending_events();
5623 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5624 let mut as_failds = HashSet::new();
5625 for event in as_events.iter() {
5626 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5627 assert!(as_failds.insert(*payment_hash));
5628 if *payment_hash != payment_hash_2 {
5629 assert_eq!(*rejected_by_dest, deliver_last_raa);
5631 assert!(!rejected_by_dest);
5633 } else { panic!("Unexpected event"); }
5635 assert!(as_failds.contains(&payment_hash_1));
5636 assert!(as_failds.contains(&payment_hash_2));
5637 if announce_latest {
5638 assert!(as_failds.contains(&payment_hash_3));
5639 assert!(as_failds.contains(&payment_hash_5));
5641 assert!(as_failds.contains(&payment_hash_6));
5643 let bs_events = nodes[1].node.get_and_clear_pending_events();
5644 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5645 let mut bs_failds = HashSet::new();
5646 for event in bs_events.iter() {
5647 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5648 assert!(bs_failds.insert(*payment_hash));
5649 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5650 assert_eq!(*rejected_by_dest, deliver_last_raa);
5652 assert!(!rejected_by_dest);
5654 } else { panic!("Unexpected event"); }
5656 assert!(bs_failds.contains(&payment_hash_1));
5657 assert!(bs_failds.contains(&payment_hash_2));
5658 if announce_latest {
5659 assert!(bs_failds.contains(&payment_hash_4));
5661 assert!(bs_failds.contains(&payment_hash_5));
5663 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5664 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5665 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5666 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5667 // PaymentFailureNetworkUpdates.
5668 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5669 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5670 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5671 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5672 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5674 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5675 _ => panic!("Unexpected event"),
5681 fn test_fail_backwards_latest_remote_announce_a() {
5682 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5686 fn test_fail_backwards_latest_remote_announce_b() {
5687 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5691 fn test_fail_backwards_previous_remote_announce() {
5692 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5693 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5694 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5698 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5699 let chanmon_cfgs = create_chanmon_cfgs(2);
5700 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5701 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5702 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5704 // Create some initial channels
5705 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5707 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5708 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5709 assert_eq!(local_txn[0].input.len(), 1);
5710 check_spends!(local_txn[0], chan_1.3);
5712 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5713 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5714 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5715 check_closed_broadcast!(nodes[0], false);
5716 check_added_monitors!(nodes[0], 1);
5718 let htlc_timeout = {
5719 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5720 assert_eq!(node_txn[0].input.len(), 1);
5721 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5722 check_spends!(node_txn[0], local_txn[0]);
5726 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5727 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5728 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5729 expect_payment_failed!(nodes[0], our_payment_hash, true);
5731 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5732 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5733 assert_eq!(spend_txn.len(), 3);
5734 assert_eq!(spend_txn[0], spend_txn[1]);
5735 check_spends!(spend_txn[0], local_txn[0]);
5736 check_spends!(spend_txn[2], htlc_timeout);
5740 fn test_key_derivation_params() {
5741 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5742 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5743 // let us re-derive the channel key set to then derive a delayed_payment_key.
5745 let chanmon_cfgs = create_chanmon_cfgs(3);
5747 // We manually create the node configuration to backup the seed.
5748 let seed = [42; 32];
5749 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5750 let chan_monitor = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5751 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, chan_monitor, keys_manager, node_seed: seed };
5752 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5753 node_cfgs.remove(0);
5754 node_cfgs.insert(0, node);
5756 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5757 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5759 // Create some initial channels
5760 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5762 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5763 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5764 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5766 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5767 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5768 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5769 assert_eq!(local_txn_1[0].input.len(), 1);
5770 check_spends!(local_txn_1[0], chan_1.3);
5772 // We check funding pubkey are unique
5773 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]));
5774 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]));
5775 if from_0_funding_key_0 == from_1_funding_key_0
5776 || from_0_funding_key_0 == from_1_funding_key_1
5777 || from_0_funding_key_1 == from_1_funding_key_0
5778 || from_0_funding_key_1 == from_1_funding_key_1 {
5779 panic!("Funding pubkeys aren't unique");
5782 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5783 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5784 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5785 check_closed_broadcast!(nodes[0], false);
5786 check_added_monitors!(nodes[0], 1);
5788 let htlc_timeout = {
5789 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5790 assert_eq!(node_txn[0].input.len(), 1);
5791 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5792 check_spends!(node_txn[0], local_txn_1[0]);
5796 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5797 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5798 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5799 expect_payment_failed!(nodes[0], our_payment_hash, true);
5801 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5802 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5803 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5804 assert_eq!(spend_txn.len(), 3);
5805 assert_eq!(spend_txn[0], spend_txn[1]);
5806 check_spends!(spend_txn[0], local_txn_1[0]);
5807 check_spends!(spend_txn[2], htlc_timeout);
5811 fn test_static_output_closing_tx() {
5812 let chanmon_cfgs = create_chanmon_cfgs(2);
5813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5815 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5817 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5819 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5820 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5822 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5823 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5824 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5826 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5827 assert_eq!(spend_txn.len(), 1);
5828 check_spends!(spend_txn[0], closing_tx);
5830 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5831 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5833 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5834 assert_eq!(spend_txn.len(), 1);
5835 check_spends!(spend_txn[0], closing_tx);
5838 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5839 let chanmon_cfgs = create_chanmon_cfgs(2);
5840 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5841 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5842 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5843 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5845 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5847 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5848 // present in B's local commitment transaction, but none of A's commitment transactions.
5849 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5850 check_added_monitors!(nodes[1], 1);
5852 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5853 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5854 let events = nodes[0].node.get_and_clear_pending_events();
5855 assert_eq!(events.len(), 1);
5857 Event::PaymentSent { payment_preimage } => {
5858 assert_eq!(payment_preimage, our_payment_preimage);
5860 _ => panic!("Unexpected event"),
5863 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5864 check_added_monitors!(nodes[0], 1);
5865 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5866 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5867 check_added_monitors!(nodes[1], 1);
5869 let mut block = Block {
5870 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5873 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5874 connect_block(&nodes[1], &block, i);
5875 block.header.prev_blockhash = block.block_hash();
5877 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5878 check_closed_broadcast!(nodes[1], false);
5879 check_added_monitors!(nodes[1], 1);
5882 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5883 let chanmon_cfgs = create_chanmon_cfgs(2);
5884 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5885 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5886 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5887 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5888 let logger = test_utils::TestLogger::new();
5890 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5891 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5892 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();
5893 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5894 check_added_monitors!(nodes[0], 1);
5896 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5898 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5899 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5900 // to "time out" the HTLC.
5902 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5904 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5905 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5906 header.prev_blockhash = header.block_hash();
5908 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5909 check_closed_broadcast!(nodes[0], false);
5910 check_added_monitors!(nodes[0], 1);
5913 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5914 let chanmon_cfgs = create_chanmon_cfgs(3);
5915 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5916 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5917 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5918 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5920 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5921 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5922 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5923 // actually revoked.
5924 let htlc_value = if use_dust { 50000 } else { 3000000 };
5925 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5926 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5927 expect_pending_htlcs_forwardable!(nodes[1]);
5928 check_added_monitors!(nodes[1], 1);
5930 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5931 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5932 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5933 check_added_monitors!(nodes[0], 1);
5934 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5935 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5936 check_added_monitors!(nodes[1], 1);
5937 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5938 check_added_monitors!(nodes[1], 1);
5939 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5941 if check_revoke_no_close {
5942 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5943 check_added_monitors!(nodes[0], 1);
5946 let mut block = Block {
5947 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5950 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5951 connect_block(&nodes[0], &block, i);
5952 block.header.prev_blockhash = block.block_hash();
5954 if !check_revoke_no_close {
5955 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5956 check_closed_broadcast!(nodes[0], false);
5957 check_added_monitors!(nodes[0], 1);
5959 expect_payment_failed!(nodes[0], our_payment_hash, true);
5963 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5964 // There are only a few cases to test here:
5965 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5966 // broadcastable commitment transactions result in channel closure,
5967 // * its included in an unrevoked-but-previous remote commitment transaction,
5968 // * its included in the latest remote or local commitment transactions.
5969 // We test each of the three possible commitment transactions individually and use both dust and
5971 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5972 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5973 // tested for at least one of the cases in other tests.
5975 fn htlc_claim_single_commitment_only_a() {
5976 do_htlc_claim_local_commitment_only(true);
5977 do_htlc_claim_local_commitment_only(false);
5979 do_htlc_claim_current_remote_commitment_only(true);
5980 do_htlc_claim_current_remote_commitment_only(false);
5984 fn htlc_claim_single_commitment_only_b() {
5985 do_htlc_claim_previous_remote_commitment_only(true, false);
5986 do_htlc_claim_previous_remote_commitment_only(false, false);
5987 do_htlc_claim_previous_remote_commitment_only(true, true);
5988 do_htlc_claim_previous_remote_commitment_only(false, true);
5993 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5994 let chanmon_cfgs = create_chanmon_cfgs(2);
5995 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5996 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5997 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5998 //Force duplicate channel ids
5999 for node in nodes.iter() {
6000 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6003 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6004 let channel_value_satoshis=10000;
6005 let push_msat=10001;
6006 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6007 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6008 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6010 //Create a second channel with a channel_id collision
6011 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6015 fn bolt2_open_channel_sending_node_checks_part2() {
6016 let chanmon_cfgs = create_chanmon_cfgs(2);
6017 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6018 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6019 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6021 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6022 let channel_value_satoshis=2^24;
6023 let push_msat=10001;
6024 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6026 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6027 let channel_value_satoshis=10000;
6028 // Test when push_msat is equal to 1000 * funding_satoshis.
6029 let push_msat=1000*channel_value_satoshis+1;
6030 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6032 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6033 let channel_value_satoshis=10000;
6034 let push_msat=10001;
6035 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
6036 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6037 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6039 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6040 // 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
6041 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6043 // 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.
6044 assert!(BREAKDOWN_TIMEOUT>0);
6045 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6047 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6048 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6049 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6051 // 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.
6052 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6053 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6054 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6055 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6056 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6059 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6060 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6061 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6062 // is no longer affordable once it's freed.
6064 fn test_fail_holding_cell_htlc_upon_free() {
6065 let chanmon_cfgs = create_chanmon_cfgs(2);
6066 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6067 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6068 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6069 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6070 let logger = test_utils::TestLogger::new();
6072 // First nodes[0] generates an update_fee, setting the channel's
6073 // pending_update_fee.
6074 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6075 check_added_monitors!(nodes[0], 1);
6077 let events = nodes[0].node.get_and_clear_pending_msg_events();
6078 assert_eq!(events.len(), 1);
6079 let (update_msg, commitment_signed) = match events[0] {
6080 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6081 (update_fee.as_ref(), commitment_signed)
6083 _ => panic!("Unexpected event"),
6086 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6088 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6089 let channel_reserve = chan_stat.channel_reserve_msat;
6090 let feerate = get_feerate!(nodes[0], chan.2);
6092 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6093 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6094 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6095 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6096 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();
6098 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6099 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6100 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6101 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6103 // Flush the pending fee update.
6104 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6105 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6106 check_added_monitors!(nodes[1], 1);
6107 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6108 check_added_monitors!(nodes[0], 1);
6110 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6111 // HTLC, but now that the fee has been raised the payment will now fail, causing
6112 // us to surface its failure to the user.
6113 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6114 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6115 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6116 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);
6117 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6119 // Check that the payment failed to be sent out.
6120 let events = nodes[0].node.get_and_clear_pending_events();
6121 assert_eq!(events.len(), 1);
6123 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6124 assert_eq!(our_payment_hash.clone(), *payment_hash);
6125 assert_eq!(*rejected_by_dest, false);
6126 assert_eq!(*error_code, None);
6127 assert_eq!(*error_data, None);
6129 _ => panic!("Unexpected event"),
6133 // Test that if multiple HTLCs are released from the holding cell and one is
6134 // valid but the other is no longer valid upon release, the valid HTLC can be
6135 // successfully completed while the other one fails as expected.
6137 fn test_free_and_fail_holding_cell_htlcs() {
6138 let chanmon_cfgs = create_chanmon_cfgs(2);
6139 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6140 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6141 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6142 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6143 let logger = test_utils::TestLogger::new();
6145 // First nodes[0] generates an update_fee, setting the channel's
6146 // pending_update_fee.
6147 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6148 check_added_monitors!(nodes[0], 1);
6150 let events = nodes[0].node.get_and_clear_pending_msg_events();
6151 assert_eq!(events.len(), 1);
6152 let (update_msg, commitment_signed) = match events[0] {
6153 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6154 (update_fee.as_ref(), commitment_signed)
6156 _ => panic!("Unexpected event"),
6159 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6161 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6162 let channel_reserve = chan_stat.channel_reserve_msat;
6163 let feerate = get_feerate!(nodes[0], chan.2);
6165 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6166 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6168 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6169 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6170 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6171 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();
6172 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();
6174 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6175 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6176 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6177 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6178 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6179 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6180 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6182 // Flush the pending fee update.
6183 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6184 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6185 check_added_monitors!(nodes[1], 1);
6186 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6187 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6188 check_added_monitors!(nodes[0], 2);
6190 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6191 // but now that the fee has been raised the second payment will now fail, causing us
6192 // to surface its failure to the user. The first payment should succeed.
6193 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6194 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6195 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6196 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);
6197 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6199 // Check that the second payment failed to be sent out.
6200 let events = nodes[0].node.get_and_clear_pending_events();
6201 assert_eq!(events.len(), 1);
6203 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6204 assert_eq!(payment_hash_2.clone(), *payment_hash);
6205 assert_eq!(*rejected_by_dest, false);
6206 assert_eq!(*error_code, None);
6207 assert_eq!(*error_data, None);
6209 _ => panic!("Unexpected event"),
6212 // Complete the first payment and the RAA from the fee update.
6213 let (payment_event, send_raa_event) = {
6214 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6215 assert_eq!(msgs.len(), 2);
6216 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6218 let raa = match send_raa_event {
6219 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6220 _ => panic!("Unexpected event"),
6222 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6223 check_added_monitors!(nodes[1], 1);
6224 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6225 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6226 let events = nodes[1].node.get_and_clear_pending_events();
6227 assert_eq!(events.len(), 1);
6229 Event::PendingHTLCsForwardable { .. } => {},
6230 _ => panic!("Unexpected event"),
6232 nodes[1].node.process_pending_htlc_forwards();
6233 let events = nodes[1].node.get_and_clear_pending_events();
6234 assert_eq!(events.len(), 1);
6236 Event::PaymentReceived { .. } => {},
6237 _ => panic!("Unexpected event"),
6239 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6240 check_added_monitors!(nodes[1], 1);
6241 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6242 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6243 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6244 let events = nodes[0].node.get_and_clear_pending_events();
6245 assert_eq!(events.len(), 1);
6247 Event::PaymentSent { ref payment_preimage } => {
6248 assert_eq!(*payment_preimage, payment_preimage_1);
6250 _ => panic!("Unexpected event"),
6254 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6255 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6256 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6259 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6260 let chanmon_cfgs = create_chanmon_cfgs(3);
6261 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6262 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6263 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6264 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6265 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6266 let logger = test_utils::TestLogger::new();
6268 // First nodes[1] generates an update_fee, setting the channel's
6269 // pending_update_fee.
6270 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6271 check_added_monitors!(nodes[1], 1);
6273 let events = nodes[1].node.get_and_clear_pending_msg_events();
6274 assert_eq!(events.len(), 1);
6275 let (update_msg, commitment_signed) = match events[0] {
6276 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6277 (update_fee.as_ref(), commitment_signed)
6279 _ => panic!("Unexpected event"),
6282 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6284 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6285 let channel_reserve = chan_stat.channel_reserve_msat;
6286 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6288 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6290 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6291 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6292 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6293 let payment_event = {
6294 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6295 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();
6296 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6297 check_added_monitors!(nodes[0], 1);
6299 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6300 assert_eq!(events.len(), 1);
6302 SendEvent::from_event(events.remove(0))
6304 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6305 check_added_monitors!(nodes[1], 0);
6306 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6307 expect_pending_htlcs_forwardable!(nodes[1]);
6309 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6310 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6312 // Flush the pending fee update.
6313 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6314 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6315 check_added_monitors!(nodes[2], 1);
6316 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6317 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6318 check_added_monitors!(nodes[1], 2);
6320 // A final RAA message is generated to finalize the fee update.
6321 let events = nodes[1].node.get_and_clear_pending_msg_events();
6322 assert_eq!(events.len(), 1);
6324 let raa_msg = match &events[0] {
6325 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6328 _ => panic!("Unexpected event"),
6331 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6332 check_added_monitors!(nodes[2], 1);
6333 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6335 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6336 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6337 assert_eq!(process_htlc_forwards_event.len(), 1);
6338 match &process_htlc_forwards_event[0] {
6339 &Event::PendingHTLCsForwardable { .. } => {},
6340 _ => panic!("Unexpected event"),
6343 // In response, we call ChannelManager's process_pending_htlc_forwards
6344 nodes[1].node.process_pending_htlc_forwards();
6345 check_added_monitors!(nodes[1], 1);
6347 // This causes the HTLC to be failed backwards.
6348 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6349 assert_eq!(fail_event.len(), 1);
6350 let (fail_msg, commitment_signed) = match &fail_event[0] {
6351 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6352 assert_eq!(updates.update_add_htlcs.len(), 0);
6353 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6354 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6355 assert_eq!(updates.update_fail_htlcs.len(), 1);
6356 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6358 _ => panic!("Unexpected event"),
6361 // Pass the failure messages back to nodes[0].
6362 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6363 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6365 // Complete the HTLC failure+removal process.
6366 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6367 check_added_monitors!(nodes[0], 1);
6368 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6369 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6370 check_added_monitors!(nodes[1], 2);
6371 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6372 assert_eq!(final_raa_event.len(), 1);
6373 let raa = match &final_raa_event[0] {
6374 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6375 _ => panic!("Unexpected event"),
6377 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6378 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6379 assert_eq!(fail_msg_event.len(), 1);
6380 match &fail_msg_event[0] {
6381 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6382 _ => panic!("Unexpected event"),
6384 let failure_event = nodes[0].node.get_and_clear_pending_events();
6385 assert_eq!(failure_event.len(), 1);
6386 match &failure_event[0] {
6387 &Event::PaymentFailed { rejected_by_dest, .. } => {
6388 assert!(!rejected_by_dest);
6390 _ => panic!("Unexpected event"),
6392 check_added_monitors!(nodes[0], 1);
6395 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6396 // 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.
6397 //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.
6400 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6401 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6402 let chanmon_cfgs = create_chanmon_cfgs(2);
6403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6405 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6406 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6408 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6409 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6410 let logger = test_utils::TestLogger::new();
6411 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();
6412 route.paths[0][0].fee_msat = 100;
6414 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6415 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6416 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6417 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6421 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6422 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6423 let chanmon_cfgs = create_chanmon_cfgs(2);
6424 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6425 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6426 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6427 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6428 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6430 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6431 let logger = test_utils::TestLogger::new();
6432 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();
6433 route.paths[0][0].fee_msat = 0;
6434 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6435 assert_eq!(err, "Cannot send 0-msat HTLC"));
6437 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6438 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6442 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6443 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6444 let chanmon_cfgs = create_chanmon_cfgs(2);
6445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6447 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6448 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6450 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6451 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6452 let logger = test_utils::TestLogger::new();
6453 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();
6454 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6455 check_added_monitors!(nodes[0], 1);
6456 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6457 updates.update_add_htlcs[0].amount_msat = 0;
6459 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6460 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6461 check_closed_broadcast!(nodes[1], true).unwrap();
6462 check_added_monitors!(nodes[1], 1);
6466 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6467 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6468 //It is enforced when constructing a route.
6469 let chanmon_cfgs = create_chanmon_cfgs(2);
6470 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6471 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6473 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6474 let logger = test_utils::TestLogger::new();
6476 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6478 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6479 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();
6480 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6481 assert_eq!(err, &"Channel CLTV overflowed?"));
6485 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6486 //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.
6487 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6488 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6489 let chanmon_cfgs = create_chanmon_cfgs(2);
6490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6492 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6493 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6494 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6496 let logger = test_utils::TestLogger::new();
6497 for i in 0..max_accepted_htlcs {
6498 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6499 let payment_event = {
6500 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6501 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();
6502 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6503 check_added_monitors!(nodes[0], 1);
6505 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6506 assert_eq!(events.len(), 1);
6507 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6508 assert_eq!(htlcs[0].htlc_id, i);
6512 SendEvent::from_event(events.remove(0))
6514 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6515 check_added_monitors!(nodes[1], 0);
6516 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6518 expect_pending_htlcs_forwardable!(nodes[1]);
6519 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6521 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6522 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6523 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();
6524 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6525 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6527 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6528 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6532 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6533 //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.
6534 let chanmon_cfgs = create_chanmon_cfgs(2);
6535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6537 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6538 let channel_value = 100000;
6539 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6540 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6542 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6544 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6545 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6546 let logger = test_utils::TestLogger::new();
6547 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();
6548 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6549 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)));
6551 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6552 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);
6554 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6557 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6559 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6560 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6561 let chanmon_cfgs = create_chanmon_cfgs(2);
6562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6566 let htlc_minimum_msat: u64;
6568 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6569 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6570 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6573 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6574 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6575 let logger = test_utils::TestLogger::new();
6576 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();
6577 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6578 check_added_monitors!(nodes[0], 1);
6579 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6580 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6581 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6582 assert!(nodes[1].node.list_channels().is_empty());
6583 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6584 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()));
6585 check_added_monitors!(nodes[1], 1);
6589 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6590 //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
6591 let chanmon_cfgs = create_chanmon_cfgs(2);
6592 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6593 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6594 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6595 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6596 let logger = test_utils::TestLogger::new();
6598 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6599 let channel_reserve = chan_stat.channel_reserve_msat;
6600 let feerate = get_feerate!(nodes[0], chan.2);
6601 // The 2* and +1 are for the fee spike reserve.
6602 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6604 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6605 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6606 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6607 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();
6608 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6609 check_added_monitors!(nodes[0], 1);
6610 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6612 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6613 // at this time channel-initiatee receivers are not required to enforce that senders
6614 // respect the fee_spike_reserve.
6615 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6616 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6618 assert!(nodes[1].node.list_channels().is_empty());
6619 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6620 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6621 check_added_monitors!(nodes[1], 1);
6625 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6626 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6627 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6628 let chanmon_cfgs = create_chanmon_cfgs(2);
6629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6631 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6632 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6633 let logger = test_utils::TestLogger::new();
6635 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6636 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6638 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6639 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();
6641 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6642 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6643 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6644 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6646 let mut msg = msgs::UpdateAddHTLC {
6650 payment_hash: our_payment_hash,
6651 cltv_expiry: htlc_cltv,
6652 onion_routing_packet: onion_packet.clone(),
6655 for i in 0..super::channel::OUR_MAX_HTLCS {
6656 msg.htlc_id = i as u64;
6657 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6659 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6660 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6662 assert!(nodes[1].node.list_channels().is_empty());
6663 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6664 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6665 check_added_monitors!(nodes[1], 1);
6669 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6670 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6671 let chanmon_cfgs = create_chanmon_cfgs(2);
6672 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6673 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6674 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6675 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6676 let logger = test_utils::TestLogger::new();
6678 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6679 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6680 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();
6681 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6682 check_added_monitors!(nodes[0], 1);
6683 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6684 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6685 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6687 assert!(nodes[1].node.list_channels().is_empty());
6688 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6689 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6690 check_added_monitors!(nodes[1], 1);
6694 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6695 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6696 let chanmon_cfgs = create_chanmon_cfgs(2);
6697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6699 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6700 let logger = test_utils::TestLogger::new();
6702 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6703 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6704 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6705 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();
6706 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6707 check_added_monitors!(nodes[0], 1);
6708 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6709 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6712 assert!(nodes[1].node.list_channels().is_empty());
6713 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6714 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6715 check_added_monitors!(nodes[1], 1);
6719 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6720 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6721 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6722 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6723 let chanmon_cfgs = create_chanmon_cfgs(2);
6724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6726 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6727 let logger = test_utils::TestLogger::new();
6729 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6730 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6731 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6732 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6733 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6734 check_added_monitors!(nodes[0], 1);
6735 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6736 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6738 //Disconnect and Reconnect
6739 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6740 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6741 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6742 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6743 assert_eq!(reestablish_1.len(), 1);
6744 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6745 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6746 assert_eq!(reestablish_2.len(), 1);
6747 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6748 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6749 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6750 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6753 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6754 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6755 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6756 check_added_monitors!(nodes[1], 1);
6757 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6759 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6761 assert!(nodes[1].node.list_channels().is_empty());
6762 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6763 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6764 check_added_monitors!(nodes[1], 1);
6768 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6769 //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.
6771 let chanmon_cfgs = create_chanmon_cfgs(2);
6772 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6773 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6774 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6775 let logger = test_utils::TestLogger::new();
6776 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6777 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6778 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6779 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();
6780 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6782 check_added_monitors!(nodes[0], 1);
6783 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6786 let update_msg = msgs::UpdateFulfillHTLC{
6789 payment_preimage: our_payment_preimage,
6792 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6794 assert!(nodes[0].node.list_channels().is_empty());
6795 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6796 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()));
6797 check_added_monitors!(nodes[0], 1);
6801 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6802 //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.
6804 let chanmon_cfgs = create_chanmon_cfgs(2);
6805 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6806 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6807 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6808 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6809 let logger = test_utils::TestLogger::new();
6811 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6812 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6813 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();
6814 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6815 check_added_monitors!(nodes[0], 1);
6816 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6817 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6819 let update_msg = msgs::UpdateFailHTLC{
6822 reason: msgs::OnionErrorPacket { data: Vec::new()},
6825 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6827 assert!(nodes[0].node.list_channels().is_empty());
6828 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6829 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()));
6830 check_added_monitors!(nodes[0], 1);
6834 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6835 //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.
6837 let chanmon_cfgs = create_chanmon_cfgs(2);
6838 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6839 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6840 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6841 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6842 let logger = test_utils::TestLogger::new();
6844 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6845 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6846 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();
6847 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6848 check_added_monitors!(nodes[0], 1);
6849 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6850 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6852 let update_msg = msgs::UpdateFailMalformedHTLC{
6855 sha256_of_onion: [1; 32],
6856 failure_code: 0x8000,
6859 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6861 assert!(nodes[0].node.list_channels().is_empty());
6862 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6863 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()));
6864 check_added_monitors!(nodes[0], 1);
6868 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6869 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6871 let chanmon_cfgs = create_chanmon_cfgs(2);
6872 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6873 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6874 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6875 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6877 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6879 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6880 check_added_monitors!(nodes[1], 1);
6882 let events = nodes[1].node.get_and_clear_pending_msg_events();
6883 assert_eq!(events.len(), 1);
6884 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6886 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, .. } } => {
6887 assert!(update_add_htlcs.is_empty());
6888 assert_eq!(update_fulfill_htlcs.len(), 1);
6889 assert!(update_fail_htlcs.is_empty());
6890 assert!(update_fail_malformed_htlcs.is_empty());
6891 assert!(update_fee.is_none());
6892 update_fulfill_htlcs[0].clone()
6894 _ => panic!("Unexpected event"),
6898 update_fulfill_msg.htlc_id = 1;
6900 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6902 assert!(nodes[0].node.list_channels().is_empty());
6903 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6904 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6905 check_added_monitors!(nodes[0], 1);
6909 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6910 //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.
6912 let chanmon_cfgs = create_chanmon_cfgs(2);
6913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6916 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6918 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6920 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6921 check_added_monitors!(nodes[1], 1);
6923 let events = nodes[1].node.get_and_clear_pending_msg_events();
6924 assert_eq!(events.len(), 1);
6925 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6927 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, .. } } => {
6928 assert!(update_add_htlcs.is_empty());
6929 assert_eq!(update_fulfill_htlcs.len(), 1);
6930 assert!(update_fail_htlcs.is_empty());
6931 assert!(update_fail_malformed_htlcs.is_empty());
6932 assert!(update_fee.is_none());
6933 update_fulfill_htlcs[0].clone()
6935 _ => panic!("Unexpected event"),
6939 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6941 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6943 assert!(nodes[0].node.list_channels().is_empty());
6944 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6945 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6946 check_added_monitors!(nodes[0], 1);
6950 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6951 //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.
6953 let chanmon_cfgs = create_chanmon_cfgs(2);
6954 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6955 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6956 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6957 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6958 let logger = test_utils::TestLogger::new();
6960 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6961 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6962 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();
6963 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6964 check_added_monitors!(nodes[0], 1);
6966 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6967 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6969 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6970 check_added_monitors!(nodes[1], 0);
6971 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6973 let events = nodes[1].node.get_and_clear_pending_msg_events();
6975 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6977 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6978 assert!(update_add_htlcs.is_empty());
6979 assert!(update_fulfill_htlcs.is_empty());
6980 assert!(update_fail_htlcs.is_empty());
6981 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6982 assert!(update_fee.is_none());
6983 update_fail_malformed_htlcs[0].clone()
6985 _ => panic!("Unexpected event"),
6988 update_msg.failure_code &= !0x8000;
6989 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6991 assert!(nodes[0].node.list_channels().is_empty());
6992 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6993 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6994 check_added_monitors!(nodes[0], 1);
6998 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6999 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7000 // * 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.
7002 let chanmon_cfgs = create_chanmon_cfgs(3);
7003 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7004 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7005 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7006 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7007 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7008 let logger = test_utils::TestLogger::new();
7010 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7013 let mut payment_event = {
7014 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7015 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();
7016 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7017 check_added_monitors!(nodes[0], 1);
7018 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7019 assert_eq!(events.len(), 1);
7020 SendEvent::from_event(events.remove(0))
7022 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7023 check_added_monitors!(nodes[1], 0);
7024 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7025 expect_pending_htlcs_forwardable!(nodes[1]);
7026 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7027 assert_eq!(events_2.len(), 1);
7028 check_added_monitors!(nodes[1], 1);
7029 payment_event = SendEvent::from_event(events_2.remove(0));
7030 assert_eq!(payment_event.msgs.len(), 1);
7033 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7034 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7035 check_added_monitors!(nodes[2], 0);
7036 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7038 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7039 assert_eq!(events_3.len(), 1);
7040 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7042 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 } } => {
7043 assert!(update_add_htlcs.is_empty());
7044 assert!(update_fulfill_htlcs.is_empty());
7045 assert!(update_fail_htlcs.is_empty());
7046 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7047 assert!(update_fee.is_none());
7048 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7050 _ => panic!("Unexpected event"),
7054 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7056 check_added_monitors!(nodes[1], 0);
7057 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7058 expect_pending_htlcs_forwardable!(nodes[1]);
7059 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7060 assert_eq!(events_4.len(), 1);
7062 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7064 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, .. } } => {
7065 assert!(update_add_htlcs.is_empty());
7066 assert!(update_fulfill_htlcs.is_empty());
7067 assert_eq!(update_fail_htlcs.len(), 1);
7068 assert!(update_fail_malformed_htlcs.is_empty());
7069 assert!(update_fee.is_none());
7071 _ => panic!("Unexpected event"),
7074 check_added_monitors!(nodes[1], 1);
7077 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7078 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7079 // 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
7080 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7082 let chanmon_cfgs = create_chanmon_cfgs(2);
7083 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7084 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7085 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7086 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7088 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7090 // We route 2 dust-HTLCs between A and B
7091 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7092 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7093 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7095 // Cache one local commitment tx as previous
7096 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7098 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7099 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7100 check_added_monitors!(nodes[1], 0);
7101 expect_pending_htlcs_forwardable!(nodes[1]);
7102 check_added_monitors!(nodes[1], 1);
7104 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7105 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7106 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7107 check_added_monitors!(nodes[0], 1);
7109 // Cache one local commitment tx as lastest
7110 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7112 let events = nodes[0].node.get_and_clear_pending_msg_events();
7114 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7115 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7117 _ => panic!("Unexpected event"),
7120 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7121 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7123 _ => panic!("Unexpected event"),
7126 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7127 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7128 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7130 if announce_latest {
7131 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7133 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7136 check_closed_broadcast!(nodes[0], false);
7137 check_added_monitors!(nodes[0], 1);
7139 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7140 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7141 let events = nodes[0].node.get_and_clear_pending_events();
7142 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7143 assert_eq!(events.len(), 2);
7144 let mut first_failed = false;
7145 for event in events {
7147 Event::PaymentFailed { payment_hash, .. } => {
7148 if payment_hash == payment_hash_1 {
7149 assert!(!first_failed);
7150 first_failed = true;
7152 assert_eq!(payment_hash, payment_hash_2);
7155 _ => panic!("Unexpected event"),
7161 fn test_failure_delay_dust_htlc_local_commitment() {
7162 do_test_failure_delay_dust_htlc_local_commitment(true);
7163 do_test_failure_delay_dust_htlc_local_commitment(false);
7167 fn test_no_failure_dust_htlc_local_commitment() {
7168 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7169 // prone to error, we test here that a dummy transaction don't fail them.
7171 let chanmon_cfgs = create_chanmon_cfgs(2);
7172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7174 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7175 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7178 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7180 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7181 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7183 // We route 2 dust-HTLCs between A and B
7184 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7185 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7187 // Build a dummy invalid transaction trying to spend a commitment tx
7189 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7190 script_sig: Script::new(),
7192 witness: Vec::new(),
7196 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7200 let dummy_tx = Transaction {
7207 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7208 nodes[0].chan_monitor.simple_monitor.block_connected(&header, &[(0, &dummy_tx)], 1);
7209 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7210 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7211 // We broadcast a few more block to check everything is all right
7212 connect_blocks(&nodes[0], 20, 1, true, header.block_hash());
7213 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7214 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7216 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7217 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7220 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7221 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7222 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7223 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7224 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7225 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7226 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7228 let chanmon_cfgs = create_chanmon_cfgs(3);
7229 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7230 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7231 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7232 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7234 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7236 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7237 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7239 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7240 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7242 // We revoked bs_commitment_tx
7244 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7245 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7248 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7249 let mut timeout_tx = Vec::new();
7251 // We fail dust-HTLC 1 by broadcast of local commitment tx
7252 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7253 check_closed_broadcast!(nodes[0], false);
7254 check_added_monitors!(nodes[0], 1);
7255 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7256 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7257 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7258 expect_payment_failed!(nodes[0], dust_hash, true);
7259 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7260 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7261 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7262 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7263 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7264 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7265 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7266 expect_payment_failed!(nodes[0], non_dust_hash, true);
7268 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7269 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7270 check_closed_broadcast!(nodes[0], false);
7271 check_added_monitors!(nodes[0], 1);
7272 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7273 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7274 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7275 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7277 expect_payment_failed!(nodes[0], dust_hash, true);
7278 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7279 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7280 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7281 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7282 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7283 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7284 expect_payment_failed!(nodes[0], non_dust_hash, true);
7286 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7288 let events = nodes[0].node.get_and_clear_pending_events();
7289 assert_eq!(events.len(), 2);
7292 Event::PaymentFailed { payment_hash, .. } => {
7293 if payment_hash == dust_hash { first = true; }
7294 else { first = false; }
7296 _ => panic!("Unexpected event"),
7299 Event::PaymentFailed { payment_hash, .. } => {
7300 if first { assert_eq!(payment_hash, non_dust_hash); }
7301 else { assert_eq!(payment_hash, dust_hash); }
7303 _ => panic!("Unexpected event"),
7310 fn test_sweep_outbound_htlc_failure_update() {
7311 do_test_sweep_outbound_htlc_failure_update(false, true);
7312 do_test_sweep_outbound_htlc_failure_update(false, false);
7313 do_test_sweep_outbound_htlc_failure_update(true, false);
7317 fn test_upfront_shutdown_script() {
7318 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7319 // enforce it at shutdown message
7321 let mut config = UserConfig::default();
7322 config.channel_options.announced_channel = true;
7323 config.peer_channel_config_limits.force_announced_channel_preference = false;
7324 config.channel_options.commit_upfront_shutdown_pubkey = false;
7325 let user_cfgs = [None, Some(config), None];
7326 let chanmon_cfgs = create_chanmon_cfgs(3);
7327 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7328 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7329 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7331 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7332 let flags = InitFeatures::known();
7333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7334 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7335 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7336 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7337 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7338 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7339 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()));
7340 check_added_monitors!(nodes[2], 1);
7342 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7343 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7344 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7345 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7346 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7347 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7348 let events = nodes[2].node.get_and_clear_pending_msg_events();
7349 assert_eq!(events.len(), 1);
7351 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7352 _ => panic!("Unexpected event"),
7355 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7356 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7358 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7359 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7360 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7361 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7362 let events = nodes[1].node.get_and_clear_pending_msg_events();
7363 assert_eq!(events.len(), 1);
7365 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7366 _ => panic!("Unexpected event"),
7369 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7370 // channel smoothly, opt-out is from channel initiator here
7371 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7372 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7373 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7374 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7375 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7376 let events = nodes[0].node.get_and_clear_pending_msg_events();
7377 assert_eq!(events.len(), 1);
7379 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7380 _ => panic!("Unexpected event"),
7383 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7384 //// channel smoothly
7385 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7386 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7387 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7388 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7389 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7390 let events = nodes[0].node.get_and_clear_pending_msg_events();
7391 assert_eq!(events.len(), 2);
7393 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7394 _ => panic!("Unexpected event"),
7397 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7398 _ => panic!("Unexpected event"),
7403 fn test_user_configurable_csv_delay() {
7404 // We test our channel constructors yield errors when we pass them absurd csv delay
7406 let mut low_our_to_self_config = UserConfig::default();
7407 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7408 let mut high_their_to_self_config = UserConfig::default();
7409 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7410 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7411 let chanmon_cfgs = create_chanmon_cfgs(2);
7412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7414 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7416 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7417 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7418 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) {
7420 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())); },
7421 _ => panic!("Unexpected event"),
7423 } else { assert!(false) }
7425 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7426 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7427 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7428 open_channel.to_self_delay = 200;
7429 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) {
7431 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())); },
7432 _ => panic!("Unexpected event"),
7434 } else { assert!(false); }
7436 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7437 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7438 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()));
7439 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7440 accept_channel.to_self_delay = 200;
7441 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7442 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7444 &ErrorAction::SendErrorMessage { ref msg } => {
7445 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()));
7447 _ => { assert!(false); }
7449 } else { assert!(false); }
7451 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7452 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7453 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7454 open_channel.to_self_delay = 200;
7455 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) {
7457 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())); },
7458 _ => panic!("Unexpected event"),
7460 } else { assert!(false); }
7464 fn test_data_loss_protect() {
7465 // We want to be sure that :
7466 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7467 // * we close channel in case of detecting other being fallen behind
7468 // * we are able to claim our own outputs thanks to to_remote being static
7476 let chanmon_cfgs = create_chanmon_cfgs(2);
7477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7481 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7483 // Cache node A state before any channel update
7484 let previous_node_state = nodes[0].node.encode();
7485 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7486 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7488 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7489 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7491 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7492 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7494 // Restore node A from previous state
7495 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7496 let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7497 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7498 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7499 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7500 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7501 monitor = test_utils::TestChannelMonitor::new(&tx_broadcaster, &logger, &fee_estimator);
7503 let mut channel_monitors = HashMap::new();
7504 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7505 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7506 keys_manager: &keys_manager,
7507 fee_estimator: &fee_estimator,
7510 tx_broadcaster: &tx_broadcaster,
7511 default_config: UserConfig::default(),
7515 nodes[0].node = &node_state_0;
7516 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7517 nodes[0].chan_monitor = &monitor;
7518 nodes[0].chain_source = &chain_source;
7520 nodes[0].block_notifier = BlockNotifier::new();
7521 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7522 nodes[0].block_notifier.register_listener(nodes[0].node);
7524 check_added_monitors!(nodes[0], 1);
7526 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7527 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7529 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7531 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7532 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7533 check_added_monitors!(nodes[0], 1);
7536 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7537 assert_eq!(node_txn.len(), 0);
7540 let mut reestablish_1 = Vec::with_capacity(1);
7541 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7542 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7543 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7544 reestablish_1.push(msg.clone());
7545 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7546 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7548 &ErrorAction::SendErrorMessage { ref msg } => {
7549 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");
7551 _ => panic!("Unexpected event!"),
7554 panic!("Unexpected event")
7558 // Check we close channel detecting A is fallen-behind
7559 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7560 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7561 check_added_monitors!(nodes[1], 1);
7564 // Check A is able to claim to_remote output
7565 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7566 assert_eq!(node_txn.len(), 1);
7567 check_spends!(node_txn[0], chan.3);
7568 assert_eq!(node_txn[0].output.len(), 2);
7569 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7570 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7571 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7572 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7573 assert_eq!(spend_txn.len(), 1);
7574 check_spends!(spend_txn[0], node_txn[0]);
7578 fn test_check_htlc_underpaying() {
7579 // Send payment through A -> B but A is maliciously
7580 // sending a probe payment (i.e less than expected value0
7581 // to B, B should refuse payment.
7583 let chanmon_cfgs = create_chanmon_cfgs(2);
7584 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7585 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7586 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7588 // Create some initial channels
7589 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7591 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7593 // Node 3 is expecting payment of 100_000 but receive 10_000,
7594 // fail htlc like we didn't know the preimage.
7595 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7596 nodes[1].node.process_pending_htlc_forwards();
7598 let events = nodes[1].node.get_and_clear_pending_msg_events();
7599 assert_eq!(events.len(), 1);
7600 let (update_fail_htlc, commitment_signed) = match events[0] {
7601 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 } } => {
7602 assert!(update_add_htlcs.is_empty());
7603 assert!(update_fulfill_htlcs.is_empty());
7604 assert_eq!(update_fail_htlcs.len(), 1);
7605 assert!(update_fail_malformed_htlcs.is_empty());
7606 assert!(update_fee.is_none());
7607 (update_fail_htlcs[0].clone(), commitment_signed)
7609 _ => panic!("Unexpected event"),
7611 check_added_monitors!(nodes[1], 1);
7613 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7614 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7616 // 10_000 msat as u64, followed by a height of 99 as u32
7617 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7618 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7619 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7620 nodes[1].node.get_and_clear_pending_events();
7624 fn test_announce_disable_channels() {
7625 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7626 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7628 let chanmon_cfgs = create_chanmon_cfgs(2);
7629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7631 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7633 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7634 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7635 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7638 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7639 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7641 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7642 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7643 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7644 assert_eq!(msg_events.len(), 3);
7645 for e in msg_events {
7647 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7648 let short_id = msg.contents.short_channel_id;
7649 // Check generated channel_update match list in PendingChannelUpdate
7650 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7651 panic!("Generated ChannelUpdate for wrong chan!");
7654 _ => panic!("Unexpected event"),
7658 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7659 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7660 assert_eq!(reestablish_1.len(), 3);
7661 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7662 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7663 assert_eq!(reestablish_2.len(), 3);
7665 // Reestablish chan_1
7666 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7667 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7668 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7669 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7670 // Reestablish chan_2
7671 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7672 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7673 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7674 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7675 // Reestablish chan_3
7676 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7677 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7678 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7679 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7681 nodes[0].node.timer_chan_freshness_every_min();
7682 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7686 fn test_bump_penalty_txn_on_revoked_commitment() {
7687 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7688 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7690 let chanmon_cfgs = create_chanmon_cfgs(2);
7691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7693 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7695 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7696 let logger = test_utils::TestLogger::new();
7699 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7700 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7701 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();
7702 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7704 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7705 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7706 assert_eq!(revoked_txn[0].output.len(), 4);
7707 assert_eq!(revoked_txn[0].input.len(), 1);
7708 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7709 let revoked_txid = revoked_txn[0].txid();
7711 let mut penalty_sum = 0;
7712 for outp in revoked_txn[0].output.iter() {
7713 if outp.script_pubkey.is_v0_p2wsh() {
7714 penalty_sum += outp.value;
7718 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7719 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7721 // Actually revoke tx by claiming a HTLC
7722 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7723 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7724 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7725 check_added_monitors!(nodes[1], 1);
7727 // One or more justice tx should have been broadcast, check it
7731 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7732 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7733 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7734 assert_eq!(node_txn[0].output.len(), 1);
7735 check_spends!(node_txn[0], revoked_txn[0]);
7736 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7737 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7738 penalty_1 = node_txn[0].txid();
7742 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7743 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7744 let mut penalty_2 = penalty_1;
7745 let mut feerate_2 = 0;
7747 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7748 assert_eq!(node_txn.len(), 1);
7749 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7750 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7751 assert_eq!(node_txn[0].output.len(), 1);
7752 check_spends!(node_txn[0], revoked_txn[0]);
7753 penalty_2 = node_txn[0].txid();
7754 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7755 assert_ne!(penalty_2, penalty_1);
7756 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7757 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7758 // Verify 25% bump heuristic
7759 assert!(feerate_2 * 100 >= feerate_1 * 125);
7763 assert_ne!(feerate_2, 0);
7765 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7766 connect_blocks(&nodes[1], 3, 118, true, header);
7768 let mut feerate_3 = 0;
7770 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7771 assert_eq!(node_txn.len(), 1);
7772 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7773 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7774 assert_eq!(node_txn[0].output.len(), 1);
7775 check_spends!(node_txn[0], revoked_txn[0]);
7776 penalty_3 = node_txn[0].txid();
7777 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7778 assert_ne!(penalty_3, penalty_2);
7779 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7780 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7781 // Verify 25% bump heuristic
7782 assert!(feerate_3 * 100 >= feerate_2 * 125);
7786 assert_ne!(feerate_3, 0);
7788 nodes[1].node.get_and_clear_pending_events();
7789 nodes[1].node.get_and_clear_pending_msg_events();
7793 fn test_bump_penalty_txn_on_revoked_htlcs() {
7794 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7795 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7797 let chanmon_cfgs = create_chanmon_cfgs(2);
7798 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7799 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7800 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7802 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7803 // Lock HTLC in both directions
7804 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7805 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7807 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7808 assert_eq!(revoked_local_txn[0].input.len(), 1);
7809 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7811 // Revoke local commitment tx
7812 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7814 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7815 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7816 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7817 check_closed_broadcast!(nodes[1], false);
7818 check_added_monitors!(nodes[1], 1);
7820 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7821 assert_eq!(revoked_htlc_txn.len(), 4);
7822 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7823 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7824 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7825 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7826 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7827 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7828 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7829 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7830 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7831 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7832 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7833 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7834 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7835 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7838 // Broadcast set of revoked txn on A
7839 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7840 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7841 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7842 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7843 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7848 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7849 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7850 // Verify claim tx are spending revoked HTLC txn
7852 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7853 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7854 // which are included in the same block (they are broadcasted because we scan the
7855 // transactions linearly and generate claims as we go, they likely should be removed in the
7857 assert_eq!(node_txn[0].input.len(), 1);
7858 check_spends!(node_txn[0], revoked_local_txn[0]);
7859 assert_eq!(node_txn[1].input.len(), 1);
7860 check_spends!(node_txn[1], revoked_local_txn[0]);
7861 assert_eq!(node_txn[2].input.len(), 1);
7862 check_spends!(node_txn[2], revoked_local_txn[0]);
7864 // Each of the three justice transactions claim a separate (single) output of the three
7865 // available, which we check here:
7866 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7867 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7868 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7870 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7871 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7873 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7874 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7875 // a remote commitment tx has already been confirmed).
7876 check_spends!(node_txn[3], chan.3);
7878 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7879 // output, checked above).
7880 assert_eq!(node_txn[4].input.len(), 2);
7881 assert_eq!(node_txn[4].output.len(), 1);
7882 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7884 first = node_txn[4].txid();
7885 // Store both feerates for later comparison
7886 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7887 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7888 penalty_txn = vec![node_txn[2].clone()];
7892 // Connect one more block to see if bumped penalty are issued for HTLC txn
7893 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7894 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7895 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7896 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7898 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7899 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7901 check_spends!(node_txn[0], revoked_local_txn[0]);
7902 check_spends!(node_txn[1], revoked_local_txn[0]);
7903 // Note that these are both bogus - they spend outputs already claimed in block 129:
7904 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7905 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7907 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7908 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7914 // Few more blocks to confirm penalty txn
7915 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7916 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7917 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7919 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7920 assert_eq!(node_txn.len(), 1);
7922 assert_eq!(node_txn[0].input.len(), 2);
7923 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7924 // Verify bumped tx is different and 25% bump heuristic
7925 assert_ne!(first, node_txn[0].txid());
7926 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7927 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7928 assert!(feerate_2 * 100 > feerate_1 * 125);
7929 let txn = vec![node_txn[0].clone()];
7933 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7934 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7935 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7936 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7938 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7939 // We verify than no new transaction has been broadcast because previously
7940 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7941 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7942 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7943 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7944 // up bumped justice generation.
7945 assert_eq!(node_txn.len(), 0);
7948 check_closed_broadcast!(nodes[0], false);
7949 check_added_monitors!(nodes[0], 1);
7953 fn test_bump_penalty_txn_on_remote_commitment() {
7954 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7955 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7958 // Provide preimage for one
7959 // Check aggregation
7961 let chanmon_cfgs = create_chanmon_cfgs(2);
7962 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7963 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7964 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7966 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7967 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7968 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7970 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7971 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7972 assert_eq!(remote_txn[0].output.len(), 4);
7973 assert_eq!(remote_txn[0].input.len(), 1);
7974 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7976 // Claim a HTLC without revocation (provide B monitor with preimage)
7977 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7978 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7979 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7980 check_added_monitors!(nodes[1], 2);
7982 // One or more claim tx should have been broadcast, check it
7985 let feerate_timeout;
7986 let feerate_preimage;
7988 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7989 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7990 assert_eq!(node_txn[0].input.len(), 1);
7991 assert_eq!(node_txn[1].input.len(), 1);
7992 check_spends!(node_txn[0], remote_txn[0]);
7993 check_spends!(node_txn[1], remote_txn[0]);
7994 check_spends!(node_txn[2], chan.3);
7995 check_spends!(node_txn[3], node_txn[2]);
7996 check_spends!(node_txn[4], node_txn[2]);
7997 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7998 timeout = node_txn[0].txid();
7999 let index = node_txn[0].input[0].previous_output.vout;
8000 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8001 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
8003 preimage = node_txn[1].txid();
8004 let index = node_txn[1].input[0].previous_output.vout;
8005 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8006 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
8008 timeout = node_txn[1].txid();
8009 let index = node_txn[1].input[0].previous_output.vout;
8010 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8011 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8013 preimage = node_txn[0].txid();
8014 let index = node_txn[0].input[0].previous_output.vout;
8015 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8016 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8020 assert_ne!(feerate_timeout, 0);
8021 assert_ne!(feerate_preimage, 0);
8023 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8024 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
8026 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8027 assert_eq!(node_txn.len(), 2);
8028 assert_eq!(node_txn[0].input.len(), 1);
8029 assert_eq!(node_txn[1].input.len(), 1);
8030 check_spends!(node_txn[0], remote_txn[0]);
8031 check_spends!(node_txn[1], remote_txn[0]);
8032 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8033 let index = node_txn[0].input[0].previous_output.vout;
8034 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8035 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8036 assert!(new_feerate * 100 > feerate_timeout * 125);
8037 assert_ne!(timeout, node_txn[0].txid());
8039 let index = node_txn[1].input[0].previous_output.vout;
8040 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8041 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8042 assert!(new_feerate * 100 > feerate_preimage * 125);
8043 assert_ne!(preimage, node_txn[1].txid());
8045 let index = node_txn[1].input[0].previous_output.vout;
8046 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8047 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8048 assert!(new_feerate * 100 > feerate_timeout * 125);
8049 assert_ne!(timeout, node_txn[1].txid());
8051 let index = node_txn[0].input[0].previous_output.vout;
8052 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8053 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8054 assert!(new_feerate * 100 > feerate_preimage * 125);
8055 assert_ne!(preimage, node_txn[0].txid());
8060 nodes[1].node.get_and_clear_pending_events();
8061 nodes[1].node.get_and_clear_pending_msg_events();
8065 fn test_set_outpoints_partial_claiming() {
8066 // - remote party claim tx, new bump tx
8067 // - disconnect remote claiming tx, new bump
8068 // - disconnect tx, see no tx anymore
8069 let chanmon_cfgs = create_chanmon_cfgs(2);
8070 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8071 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8072 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8074 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8075 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8076 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8078 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8079 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8080 assert_eq!(remote_txn.len(), 3);
8081 assert_eq!(remote_txn[0].output.len(), 4);
8082 assert_eq!(remote_txn[0].input.len(), 1);
8083 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8084 check_spends!(remote_txn[1], remote_txn[0]);
8085 check_spends!(remote_txn[2], remote_txn[0]);
8087 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8088 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8089 // Provide node A with both preimage
8090 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8091 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8092 check_added_monitors!(nodes[0], 2);
8093 nodes[0].node.get_and_clear_pending_events();
8094 nodes[0].node.get_and_clear_pending_msg_events();
8096 // Connect blocks on node A commitment transaction
8097 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8098 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8099 check_closed_broadcast!(nodes[0], false);
8100 check_added_monitors!(nodes[0], 1);
8101 // Verify node A broadcast tx claiming both HTLCs
8103 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8104 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8105 assert_eq!(node_txn.len(), 4);
8106 check_spends!(node_txn[0], remote_txn[0]);
8107 check_spends!(node_txn[1], chan.3);
8108 check_spends!(node_txn[2], node_txn[1]);
8109 check_spends!(node_txn[3], node_txn[1]);
8110 assert_eq!(node_txn[0].input.len(), 2);
8114 // Connect blocks on node B
8115 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8116 check_closed_broadcast!(nodes[1], false);
8117 check_added_monitors!(nodes[1], 1);
8118 // Verify node B broadcast 2 HTLC-timeout txn
8119 let partial_claim_tx = {
8120 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8121 assert_eq!(node_txn.len(), 3);
8122 check_spends!(node_txn[1], node_txn[0]);
8123 check_spends!(node_txn[2], node_txn[0]);
8124 assert_eq!(node_txn[1].input.len(), 1);
8125 assert_eq!(node_txn[2].input.len(), 1);
8129 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8130 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8131 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8133 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8134 assert_eq!(node_txn.len(), 1);
8135 check_spends!(node_txn[0], remote_txn[0]);
8136 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8139 nodes[0].node.get_and_clear_pending_msg_events();
8141 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8142 disconnect_block(&nodes[0], &header, 102);
8144 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8145 assert_eq!(node_txn.len(), 1);
8146 check_spends!(node_txn[0], remote_txn[0]);
8147 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8151 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8152 disconnect_block(&nodes[0], &header, 101);
8153 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8155 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8156 assert_eq!(node_txn.len(), 0);
8162 fn test_counterparty_raa_skip_no_crash() {
8163 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8164 // commitment transaction, we would have happily carried on and provided them the next
8165 // commitment transaction based on one RAA forward. This would probably eventually have led to
8166 // channel closure, but it would not have resulted in funds loss. Still, our
8167 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8168 // check simply that the channel is closed in response to such an RAA, but don't check whether
8169 // we decide to punish our counterparty for revoking their funds (as we don't currently
8171 let chanmon_cfgs = create_chanmon_cfgs(2);
8172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8174 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8175 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8177 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8178 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8179 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8180 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8181 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8182 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8184 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8185 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8186 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8187 check_added_monitors!(nodes[1], 1);
8191 fn test_bump_txn_sanitize_tracking_maps() {
8192 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8193 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8195 let chanmon_cfgs = create_chanmon_cfgs(2);
8196 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8197 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8198 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8200 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8201 // Lock HTLC in both directions
8202 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8203 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8205 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8206 assert_eq!(revoked_local_txn[0].input.len(), 1);
8207 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8209 // Revoke local commitment tx
8210 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8212 // Broadcast set of revoked txn on A
8213 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8214 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8216 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8217 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8218 check_closed_broadcast!(nodes[0], false);
8219 check_added_monitors!(nodes[0], 1);
8221 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8222 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8223 check_spends!(node_txn[0], revoked_local_txn[0]);
8224 check_spends!(node_txn[1], revoked_local_txn[0]);
8225 check_spends!(node_txn[2], revoked_local_txn[0]);
8226 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8230 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8231 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8232 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8234 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8235 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8236 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8237 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8243 fn test_override_channel_config() {
8244 let chanmon_cfgs = create_chanmon_cfgs(2);
8245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8249 // Node0 initiates a channel to node1 using the override config.
8250 let mut override_config = UserConfig::default();
8251 override_config.own_channel_config.our_to_self_delay = 200;
8253 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8255 // Assert the channel created by node0 is using the override config.
8256 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8257 assert_eq!(res.channel_flags, 0);
8258 assert_eq!(res.to_self_delay, 200);
8262 fn test_override_0msat_htlc_minimum() {
8263 let mut zero_config = UserConfig::default();
8264 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8265 let chanmon_cfgs = create_chanmon_cfgs(2);
8266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8270 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8271 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8272 assert_eq!(res.htlc_minimum_msat, 1);
8274 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8275 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8276 assert_eq!(res.htlc_minimum_msat, 1);
8280 fn test_simple_payment_secret() {
8281 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8282 // features, however.
8283 let chanmon_cfgs = create_chanmon_cfgs(3);
8284 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8285 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8286 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8288 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8289 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8290 let logger = test_utils::TestLogger::new();
8292 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8293 let payment_secret = PaymentSecret([0xdb; 32]);
8294 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8295 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8296 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8297 // Claiming with all the correct values but the wrong secret should result in nothing...
8298 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8299 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8300 // ...but with the right secret we should be able to claim all the way back
8301 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8305 fn test_simple_mpp() {
8306 // Simple test of sending a multi-path payment.
8307 let chanmon_cfgs = create_chanmon_cfgs(4);
8308 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8309 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8310 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8312 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8313 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8314 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8315 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8316 let logger = test_utils::TestLogger::new();
8318 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8319 let payment_secret = PaymentSecret([0xdb; 32]);
8320 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8321 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8322 let path = route.paths[0].clone();
8323 route.paths.push(path);
8324 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8325 route.paths[0][0].short_channel_id = chan_1_id;
8326 route.paths[0][1].short_channel_id = chan_3_id;
8327 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8328 route.paths[1][0].short_channel_id = chan_2_id;
8329 route.paths[1][1].short_channel_id = chan_4_id;
8330 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8331 // Claiming with all the correct values but the wrong secret should result in nothing...
8332 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8333 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8334 // ...but with the right secret we should be able to claim all the way back
8335 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8339 fn test_update_err_monitor_lockdown() {
8340 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8341 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8342 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8344 // This scenario may happen in a watchtower setup, where watchtower process a block height
8345 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8346 // commitment at same time.
8348 let chanmon_cfgs = create_chanmon_cfgs(2);
8349 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8350 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8351 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8353 // Create some initial channel
8354 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8355 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8357 // Rebalance the network to generate htlc in the two directions
8358 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8360 // Route a HTLC from node 0 to node 1 (but don't settle)
8361 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8363 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8364 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8366 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8367 let monitor = monitors.get(&outpoint).unwrap();
8368 let mut w = test_utils::TestVecWriter(Vec::new());
8369 monitor.write_for_disk(&mut w).unwrap();
8370 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8371 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8372 assert!(new_monitor == *monitor);
8373 let watchtower = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8374 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8377 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8378 watchtower.simple_monitor.block_connected(&header, &[], 200);
8380 // Try to update ChannelMonitor
8381 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8382 check_added_monitors!(nodes[1], 1);
8383 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8384 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8385 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8386 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8387 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8388 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8389 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8390 } else { assert!(false); }
8391 } else { assert!(false); };
8392 // Our local monitor is in-sync and hasn't processed yet timeout
8393 check_added_monitors!(nodes[0], 1);
8394 let events = nodes[0].node.get_and_clear_pending_events();
8395 assert_eq!(events.len(), 1);
8399 fn test_concurrent_monitor_claim() {
8400 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8401 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8402 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8403 // state N+1 confirms. Alice claims output from state N+1.
8405 let chanmon_cfgs = create_chanmon_cfgs(2);
8406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8408 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8410 // Create some initial channel
8411 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8412 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8414 // Rebalance the network to generate htlc in the two directions
8415 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8417 // Route a HTLC from node 0 to node 1 (but don't settle)
8418 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8420 // Copy SimpleManyChannelMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8421 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8422 let watchtower_alice = {
8423 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8424 let monitor = monitors.get(&outpoint).unwrap();
8425 let mut w = test_utils::TestVecWriter(Vec::new());
8426 monitor.write_for_disk(&mut w).unwrap();
8427 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8428 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8429 assert!(new_monitor == *monitor);
8430 let watchtower = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8431 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8434 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8435 watchtower_alice.simple_monitor.block_connected(&header, &vec![], 135);
8437 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8439 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8440 assert_eq!(txn.len(), 2);
8444 // Copy SimpleManyChannelMonitor to simulate watchtower Bob and make it receive a commitment update first.
8445 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8446 let watchtower_bob = {
8447 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8448 let monitor = monitors.get(&outpoint).unwrap();
8449 let mut w = test_utils::TestVecWriter(Vec::new());
8450 monitor.write_for_disk(&mut w).unwrap();
8451 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8452 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8453 assert!(new_monitor == *monitor);
8454 let watchtower = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8455 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8458 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8459 watchtower_bob.simple_monitor.block_connected(&header, &vec![], 134);
8461 // Route another payment to generate another update with still previous HTLC pending
8462 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8464 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8465 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();
8466 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8468 check_added_monitors!(nodes[1], 1);
8470 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8471 assert_eq!(updates.update_add_htlcs.len(), 1);
8472 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8473 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8474 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8475 // Watchtower Alice should already have seen the block and reject the update
8476 if let Err(_) = watchtower_alice.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8477 if let Ok(_) = watchtower_bob.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8478 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8479 } else { assert!(false); }
8480 } else { assert!(false); };
8481 // Our local monitor is in-sync and hasn't processed yet timeout
8482 check_added_monitors!(nodes[0], 1);
8484 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8485 watchtower_bob.simple_monitor.block_connected(&header, &vec![], 135);
8487 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8490 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8491 assert_eq!(txn.len(), 2);
8492 bob_state_y = txn[0].clone();
8496 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8497 watchtower_alice.simple_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8499 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8500 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8501 // the onchain detection of the HTLC output
8502 assert_eq!(htlc_txn.len(), 2);
8503 check_spends!(htlc_txn[0], bob_state_y);
8504 check_spends!(htlc_txn[1], bob_state_y);