1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::transaction::OutPoint;
16 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
17 use chain::chaininterface::ChainListener;
18 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
19 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
20 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
21 use ln::channelmonitor;
22 use ln::channel::{Channel, ChannelError};
23 use ln::{chan_utils, onion_utils};
24 use routing::router::{Route, RouteHop, get_route};
25 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
27 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
28 use util::enforcing_trait_impls::EnforcingChannelKeys;
29 use util::{byte_utils, test_utils};
30 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
31 use util::errors::APIError;
32 use util::ser::{Writeable, ReadableArgs, Readable};
33 use util::config::UserConfig;
35 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
36 use bitcoin::hashes::HashEngine;
37 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
38 use bitcoin::util::bip143;
39 use bitcoin::util::address::Address;
40 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
41 use bitcoin::blockdata::block::{Block, BlockHeader};
42 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
43 use bitcoin::blockdata::script::{Builder, Script};
44 use bitcoin::blockdata::opcodes;
45 use bitcoin::blockdata::constants::genesis_block;
46 use bitcoin::network::constants::Network;
48 use bitcoin::hashes::sha256::Hash as Sha256;
49 use bitcoin::hashes::Hash;
51 use bitcoin::secp256k1::{Secp256k1, Message};
52 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
56 use std::collections::{BTreeSet, HashMap, HashSet};
57 use std::default::Default;
58 use std::sync::{Arc, Mutex};
59 use std::sync::atomic::Ordering;
62 use ln::functional_test_utils::*;
63 use ln::chan_utils::PreCalculatedTxCreationKeys;
66 fn test_insane_channel_opens() {
67 // Stand up a network of 2 nodes
68 let chanmon_cfgs = create_chanmon_cfgs(2);
69 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
70 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
71 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
73 // Instantiate channel parameters where we push the maximum msats given our
75 let channel_value_sat = 31337; // same as funding satoshis
76 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
77 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
79 // Have node0 initiate a channel to node1 with aforementioned parameters
80 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
82 // Extract the channel open message from node0 to node1
83 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
85 // Test helper that asserts we get the correct error string given a mutator
86 // that supposedly makes the channel open message insane
87 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
88 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
89 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
90 assert_eq!(msg_events.len(), 1);
91 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
92 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
94 &ErrorAction::SendErrorMessage { .. } => {
95 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
97 _ => panic!("unexpected event!"),
99 } else { assert!(false); }
102 use ln::channel::MAX_FUNDING_SATOSHIS;
103 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
105 // Test all mutations that would make the channel open message insane
106 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 });
108 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
110 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 });
112 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
114 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 });
116 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 });
118 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 });
120 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
122 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 fn test_async_inbound_update_fee() {
127 let chanmon_cfgs = create_chanmon_cfgs(2);
128 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
129 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
130 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
131 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
132 let logger = test_utils::TestLogger::new();
133 let channel_id = chan.2;
136 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
140 // send (1) commitment_signed -.
141 // <- update_add_htlc/commitment_signed
142 // send (2) RAA (awaiting remote revoke) -.
143 // (1) commitment_signed is delivered ->
144 // .- send (3) RAA (awaiting remote revoke)
145 // (2) RAA is delivered ->
146 // .- send (4) commitment_signed
147 // <- (3) RAA is delivered
148 // send (5) commitment_signed -.
149 // <- (4) commitment_signed is delivered
151 // (5) commitment_signed is delivered ->
153 // (6) RAA is delivered ->
155 // First nodes[0] generates an update_fee
156 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
157 check_added_monitors!(nodes[0], 1);
159 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
160 assert_eq!(events_0.len(), 1);
161 let (update_msg, commitment_signed) = match events_0[0] { // (1)
162 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
163 (update_fee.as_ref(), commitment_signed)
165 _ => panic!("Unexpected event"),
168 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
170 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
171 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
172 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
173 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();
174 check_added_monitors!(nodes[1], 1);
176 let payment_event = {
177 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
178 assert_eq!(events_1.len(), 1);
179 SendEvent::from_event(events_1.remove(0))
181 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
182 assert_eq!(payment_event.msgs.len(), 1);
184 // ...now when the messages get delivered everyone should be happy
185 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
186 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
187 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
188 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
189 check_added_monitors!(nodes[0], 1);
191 // deliver(1), generate (3):
192 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
193 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
194 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
195 check_added_monitors!(nodes[1], 1);
197 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
198 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
199 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
202 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
203 assert!(bs_update.update_fee.is_none()); // (4)
204 check_added_monitors!(nodes[1], 1);
206 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
207 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
208 assert!(as_update.update_add_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
211 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
212 assert!(as_update.update_fee.is_none()); // (5)
213 check_added_monitors!(nodes[0], 1);
215 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
216 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
217 // only (6) so get_event_msg's assert(len == 1) passes
218 check_added_monitors!(nodes[0], 1);
220 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
221 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
222 check_added_monitors!(nodes[1], 1);
224 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
225 check_added_monitors!(nodes[0], 1);
227 let events_2 = nodes[0].node.get_and_clear_pending_events();
228 assert_eq!(events_2.len(), 1);
230 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
231 _ => panic!("Unexpected event"),
234 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
235 check_added_monitors!(nodes[1], 1);
239 fn test_update_fee_unordered_raa() {
240 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
241 // crash in an earlier version of the update_fee patch)
242 let chanmon_cfgs = create_chanmon_cfgs(2);
243 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
244 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
245 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
246 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
247 let channel_id = chan.2;
248 let logger = test_utils::TestLogger::new();
251 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
253 // First nodes[0] generates an update_fee
254 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
255 check_added_monitors!(nodes[0], 1);
257 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
258 assert_eq!(events_0.len(), 1);
259 let update_msg = match events_0[0] { // (1)
260 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
263 _ => panic!("Unexpected event"),
266 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
268 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
269 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
270 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
271 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();
272 check_added_monitors!(nodes[1], 1);
274 let payment_event = {
275 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
276 assert_eq!(events_1.len(), 1);
277 SendEvent::from_event(events_1.remove(0))
279 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
280 assert_eq!(payment_event.msgs.len(), 1);
282 // ...now when the messages get delivered everyone should be happy
283 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
284 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
285 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
286 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
287 check_added_monitors!(nodes[0], 1);
289 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
290 check_added_monitors!(nodes[1], 1);
292 // We can't continue, sadly, because our (1) now has a bogus signature
296 fn test_multi_flight_update_fee() {
297 let chanmon_cfgs = create_chanmon_cfgs(2);
298 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
299 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
300 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
301 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
302 let channel_id = chan.2;
305 // update_fee/commitment_signed ->
306 // .- send (1) RAA and (2) commitment_signed
307 // update_fee (never committed) ->
309 // We have to manually generate the above update_fee, it is allowed by the protocol but we
310 // don't track which updates correspond to which revoke_and_ack responses so we're in
311 // AwaitingRAA mode and will not generate the update_fee yet.
312 // <- (1) RAA delivered
313 // (3) is generated and send (4) CS -.
314 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
315 // know the per_commitment_point to use for it.
316 // <- (2) commitment_signed delivered
318 // B should send no response here
319 // (4) commitment_signed delivered ->
320 // <- RAA/commitment_signed delivered
323 // First nodes[0] generates an update_fee
324 let initial_feerate = get_feerate!(nodes[0], channel_id);
325 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
326 check_added_monitors!(nodes[0], 1);
328 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
329 assert_eq!(events_0.len(), 1);
330 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
331 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
332 (update_fee.as_ref().unwrap(), commitment_signed)
334 _ => panic!("Unexpected event"),
337 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
338 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
339 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
340 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
341 check_added_monitors!(nodes[1], 1);
343 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
345 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
346 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
347 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
349 // Create the (3) update_fee message that nodes[0] will generate before it does...
350 let mut update_msg_2 = msgs::UpdateFee {
351 channel_id: update_msg_1.channel_id.clone(),
352 feerate_per_kw: (initial_feerate + 30) as u32,
355 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
357 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
359 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
361 // Deliver (1), generating (3) and (4)
362 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
363 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
364 check_added_monitors!(nodes[0], 1);
365 assert!(as_second_update.update_add_htlcs.is_empty());
366 assert!(as_second_update.update_fulfill_htlcs.is_empty());
367 assert!(as_second_update.update_fail_htlcs.is_empty());
368 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
369 // Check that the update_fee newly generated matches what we delivered:
370 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
371 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
373 // Deliver (2) commitment_signed
374 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
375 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
376 check_added_monitors!(nodes[0], 1);
377 // No commitment_signed so get_event_msg's assert(len == 1) passes
379 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
380 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
381 check_added_monitors!(nodes[1], 1);
384 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
385 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
386 check_added_monitors!(nodes[1], 1);
388 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
389 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
390 check_added_monitors!(nodes[0], 1);
392 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
393 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
394 // No commitment_signed so get_event_msg's assert(len == 1) passes
395 check_added_monitors!(nodes[0], 1);
397 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
398 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
399 check_added_monitors!(nodes[1], 1);
403 fn test_1_conf_open() {
404 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
405 // tests that we properly send one in that case.
406 let mut alice_config = UserConfig::default();
407 alice_config.own_channel_config.minimum_depth = 1;
408 alice_config.channel_options.announced_channel = true;
409 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
410 let mut bob_config = UserConfig::default();
411 bob_config.own_channel_config.minimum_depth = 1;
412 bob_config.channel_options.announced_channel = true;
413 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
414 let chanmon_cfgs = create_chanmon_cfgs(2);
415 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
416 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
417 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
419 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
421 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
424 connect_block(&nodes[1], &block, 1);
425 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()));
427 connect_block(&nodes[0], &block, 1);
428 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
429 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
432 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
433 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
434 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
438 fn do_test_sanity_on_in_flight_opens(steps: u8) {
439 // Previously, we had issues deserializing channels when we hadn't connected the first block
440 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
441 // serialization round-trips and simply do steps towards opening a channel and then drop the
444 let chanmon_cfgs = create_chanmon_cfgs(2);
445 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
446 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
447 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
449 if steps & 0b1000_0000 != 0{
451 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
454 connect_block(&nodes[0], &block, 1);
455 connect_block(&nodes[1], &block, 1);
458 if steps & 0x0f == 0 { return; }
459 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
460 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
462 if steps & 0x0f == 1 { return; }
463 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
464 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
466 if steps & 0x0f == 2 { return; }
467 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
469 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
471 if steps & 0x0f == 3 { return; }
472 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
473 check_added_monitors!(nodes[0], 0);
474 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
476 if steps & 0x0f == 4 { return; }
477 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
479 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
480 assert_eq!(added_monitors.len(), 1);
481 assert_eq!(added_monitors[0].0, funding_output);
482 added_monitors.clear();
484 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
486 if steps & 0x0f == 5 { return; }
487 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
489 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
490 assert_eq!(added_monitors.len(), 1);
491 assert_eq!(added_monitors[0].0, funding_output);
492 added_monitors.clear();
495 let events_4 = nodes[0].node.get_and_clear_pending_events();
496 assert_eq!(events_4.len(), 1);
498 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
499 assert_eq!(user_channel_id, 42);
500 assert_eq!(*funding_txo, funding_output);
502 _ => panic!("Unexpected event"),
505 if steps & 0x0f == 6 { return; }
506 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
508 if steps & 0x0f == 7 { return; }
509 confirm_transaction(&nodes[0], &tx);
510 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
514 fn test_sanity_on_in_flight_opens() {
515 do_test_sanity_on_in_flight_opens(0);
516 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
517 do_test_sanity_on_in_flight_opens(1);
518 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
519 do_test_sanity_on_in_flight_opens(2);
520 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
521 do_test_sanity_on_in_flight_opens(3);
522 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
523 do_test_sanity_on_in_flight_opens(4);
524 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
525 do_test_sanity_on_in_flight_opens(5);
526 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
527 do_test_sanity_on_in_flight_opens(6);
528 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
529 do_test_sanity_on_in_flight_opens(7);
530 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
531 do_test_sanity_on_in_flight_opens(8);
532 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
536 fn test_update_fee_vanilla() {
537 let chanmon_cfgs = create_chanmon_cfgs(2);
538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
540 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
541 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
542 let channel_id = chan.2;
544 let feerate = get_feerate!(nodes[0], channel_id);
545 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
546 check_added_monitors!(nodes[0], 1);
548 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
549 assert_eq!(events_0.len(), 1);
550 let (update_msg, commitment_signed) = match events_0[0] {
551 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 } } => {
552 (update_fee.as_ref(), commitment_signed)
554 _ => panic!("Unexpected event"),
556 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
558 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
559 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
560 check_added_monitors!(nodes[1], 1);
562 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
563 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
564 check_added_monitors!(nodes[0], 1);
566 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
567 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
568 // No commitment_signed so get_event_msg's assert(len == 1) passes
569 check_added_monitors!(nodes[0], 1);
571 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
572 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
573 check_added_monitors!(nodes[1], 1);
577 fn test_update_fee_that_funder_cannot_afford() {
578 let chanmon_cfgs = create_chanmon_cfgs(2);
579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
582 let channel_value = 1888;
583 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
584 let channel_id = chan.2;
587 nodes[0].node.update_fee(channel_id, feerate).unwrap();
588 check_added_monitors!(nodes[0], 1);
589 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
591 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
593 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
595 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
596 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
598 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
600 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
601 let num_htlcs = commitment_tx.output.len() - 2;
602 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
603 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
604 actual_fee = channel_value - actual_fee;
605 assert_eq!(total_fee, actual_fee);
608 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
609 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
610 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
611 check_added_monitors!(nodes[0], 1);
613 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
615 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
617 //While producing the commitment_signed response after handling a received update_fee request the
618 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
619 //Should produce and error.
620 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
621 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
622 check_added_monitors!(nodes[1], 1);
623 check_closed_broadcast!(nodes[1], true);
627 fn test_update_fee_with_fundee_update_add_htlc() {
628 let chanmon_cfgs = create_chanmon_cfgs(2);
629 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
630 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
631 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
632 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
633 let channel_id = chan.2;
634 let logger = test_utils::TestLogger::new();
637 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
639 let feerate = get_feerate!(nodes[0], channel_id);
640 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
641 check_added_monitors!(nodes[0], 1);
643 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
644 assert_eq!(events_0.len(), 1);
645 let (update_msg, commitment_signed) = match events_0[0] {
646 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 } } => {
647 (update_fee.as_ref(), commitment_signed)
649 _ => panic!("Unexpected event"),
651 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
652 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
653 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
654 check_added_monitors!(nodes[1], 1);
656 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
657 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
658 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();
660 // nothing happens since node[1] is in AwaitingRemoteRevoke
661 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
663 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
664 assert_eq!(added_monitors.len(), 0);
665 added_monitors.clear();
667 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
668 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
669 // node[1] has nothing to do
671 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
672 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
673 check_added_monitors!(nodes[0], 1);
675 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
676 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
677 // No commitment_signed so get_event_msg's assert(len == 1) passes
678 check_added_monitors!(nodes[0], 1);
679 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
680 check_added_monitors!(nodes[1], 1);
681 // AwaitingRemoteRevoke ends here
683 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
684 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
685 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
686 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
687 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
688 assert_eq!(commitment_update.update_fee.is_none(), true);
690 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
691 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
692 check_added_monitors!(nodes[0], 1);
693 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
695 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
696 check_added_monitors!(nodes[1], 1);
697 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
699 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
700 check_added_monitors!(nodes[1], 1);
701 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
702 // No commitment_signed so get_event_msg's assert(len == 1) passes
704 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
705 check_added_monitors!(nodes[0], 1);
706 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
708 expect_pending_htlcs_forwardable!(nodes[0]);
710 let events = nodes[0].node.get_and_clear_pending_events();
711 assert_eq!(events.len(), 1);
713 Event::PaymentReceived { .. } => { },
714 _ => panic!("Unexpected event"),
717 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
719 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
720 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
721 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
725 fn test_update_fee() {
726 let chanmon_cfgs = create_chanmon_cfgs(2);
727 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
728 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
729 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
730 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
731 let channel_id = chan.2;
734 // (1) update_fee/commitment_signed ->
735 // <- (2) revoke_and_ack
736 // .- send (3) commitment_signed
737 // (4) update_fee/commitment_signed ->
738 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
739 // <- (3) commitment_signed delivered
740 // send (6) revoke_and_ack -.
741 // <- (5) deliver revoke_and_ack
742 // (6) deliver revoke_and_ack ->
743 // .- send (7) commitment_signed in response to (4)
744 // <- (7) deliver commitment_signed
747 // Create and deliver (1)...
748 let feerate = get_feerate!(nodes[0], channel_id);
749 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
750 check_added_monitors!(nodes[0], 1);
752 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
753 assert_eq!(events_0.len(), 1);
754 let (update_msg, commitment_signed) = match events_0[0] {
755 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 } } => {
756 (update_fee.as_ref(), commitment_signed)
758 _ => panic!("Unexpected event"),
760 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
762 // Generate (2) and (3):
763 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
764 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
765 check_added_monitors!(nodes[1], 1);
768 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
769 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
770 check_added_monitors!(nodes[0], 1);
772 // Create and deliver (4)...
773 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
774 check_added_monitors!(nodes[0], 1);
775 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
776 assert_eq!(events_0.len(), 1);
777 let (update_msg, commitment_signed) = match events_0[0] {
778 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 } } => {
779 (update_fee.as_ref(), commitment_signed)
781 _ => panic!("Unexpected event"),
784 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
785 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
786 check_added_monitors!(nodes[1], 1);
788 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
789 // No commitment_signed so get_event_msg's assert(len == 1) passes
791 // Handle (3), creating (6):
792 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
793 check_added_monitors!(nodes[0], 1);
794 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
795 // No commitment_signed so get_event_msg's assert(len == 1) passes
798 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
799 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
800 check_added_monitors!(nodes[0], 1);
802 // Deliver (6), creating (7):
803 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
804 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
805 assert!(commitment_update.update_add_htlcs.is_empty());
806 assert!(commitment_update.update_fulfill_htlcs.is_empty());
807 assert!(commitment_update.update_fail_htlcs.is_empty());
808 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
809 assert!(commitment_update.update_fee.is_none());
810 check_added_monitors!(nodes[1], 1);
813 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
814 check_added_monitors!(nodes[0], 1);
815 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
816 // No commitment_signed so get_event_msg's assert(len == 1) passes
818 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
819 check_added_monitors!(nodes[1], 1);
820 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
822 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
823 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
824 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
828 fn pre_funding_lock_shutdown_test() {
829 // Test sending a shutdown prior to funding_locked after funding generation
830 let chanmon_cfgs = create_chanmon_cfgs(2);
831 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
832 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
833 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
834 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
835 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
836 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
837 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
839 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
840 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
841 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
842 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
843 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
845 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
846 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
847 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
848 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
849 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
850 assert!(node_0_none.is_none());
852 assert!(nodes[0].node.list_channels().is_empty());
853 assert!(nodes[1].node.list_channels().is_empty());
857 fn updates_shutdown_wait() {
858 // Test sending a shutdown with outstanding updates pending
859 let chanmon_cfgs = create_chanmon_cfgs(3);
860 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
861 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
862 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
863 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
864 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
865 let logger = test_utils::TestLogger::new();
867 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
869 nodes[0].node.close_channel(&chan_1.2).unwrap();
870 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
871 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
872 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
873 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
876 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
878 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
880 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
881 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
882 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();
883 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();
884 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
885 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
887 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
888 check_added_monitors!(nodes[2], 1);
889 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
890 assert!(updates.update_add_htlcs.is_empty());
891 assert!(updates.update_fail_htlcs.is_empty());
892 assert!(updates.update_fail_malformed_htlcs.is_empty());
893 assert!(updates.update_fee.is_none());
894 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
895 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
896 check_added_monitors!(nodes[1], 1);
897 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
898 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
900 assert!(updates_2.update_add_htlcs.is_empty());
901 assert!(updates_2.update_fail_htlcs.is_empty());
902 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
903 assert!(updates_2.update_fee.is_none());
904 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
905 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
906 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
908 let events = nodes[0].node.get_and_clear_pending_events();
909 assert_eq!(events.len(), 1);
911 Event::PaymentSent { ref payment_preimage } => {
912 assert_eq!(our_payment_preimage, *payment_preimage);
914 _ => panic!("Unexpected event"),
917 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
918 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
919 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
920 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
921 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
922 assert!(node_0_none.is_none());
924 assert!(nodes[0].node.list_channels().is_empty());
926 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
927 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
928 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
929 assert!(nodes[1].node.list_channels().is_empty());
930 assert!(nodes[2].node.list_channels().is_empty());
934 fn htlc_fail_async_shutdown() {
935 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
936 let chanmon_cfgs = create_chanmon_cfgs(3);
937 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
938 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
939 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
940 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
941 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
942 let logger = test_utils::TestLogger::new();
944 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
945 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
946 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();
947 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
948 check_added_monitors!(nodes[0], 1);
949 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
950 assert_eq!(updates.update_add_htlcs.len(), 1);
951 assert!(updates.update_fulfill_htlcs.is_empty());
952 assert!(updates.update_fail_htlcs.is_empty());
953 assert!(updates.update_fail_malformed_htlcs.is_empty());
954 assert!(updates.update_fee.is_none());
956 nodes[1].node.close_channel(&chan_1.2).unwrap();
957 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
958 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
959 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
961 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
962 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
963 check_added_monitors!(nodes[1], 1);
964 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
965 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
967 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
968 assert!(updates_2.update_add_htlcs.is_empty());
969 assert!(updates_2.update_fulfill_htlcs.is_empty());
970 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
971 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
972 assert!(updates_2.update_fee.is_none());
974 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
975 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
977 expect_payment_failed!(nodes[0], our_payment_hash, false);
979 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
980 assert_eq!(msg_events.len(), 2);
981 let node_0_closing_signed = match msg_events[0] {
982 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
983 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
986 _ => panic!("Unexpected event"),
988 match msg_events[1] {
989 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
990 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
992 _ => panic!("Unexpected event"),
995 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
996 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
997 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
998 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
999 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1000 assert!(node_0_none.is_none());
1002 assert!(nodes[0].node.list_channels().is_empty());
1004 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1005 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1006 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1007 assert!(nodes[1].node.list_channels().is_empty());
1008 assert!(nodes[2].node.list_channels().is_empty());
1011 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1012 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1013 // messages delivered prior to disconnect
1014 let chanmon_cfgs = create_chanmon_cfgs(3);
1015 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1016 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1017 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1018 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1019 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1021 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1023 nodes[1].node.close_channel(&chan_1.2).unwrap();
1024 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1026 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1027 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1029 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1033 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1034 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1036 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1037 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1038 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1039 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1041 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1042 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1043 assert!(node_1_shutdown == node_1_2nd_shutdown);
1045 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1046 let node_0_2nd_shutdown = if recv_count > 0 {
1047 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1048 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1051 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1052 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1053 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1055 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1057 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1058 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1060 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1061 check_added_monitors!(nodes[2], 1);
1062 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1063 assert!(updates.update_add_htlcs.is_empty());
1064 assert!(updates.update_fail_htlcs.is_empty());
1065 assert!(updates.update_fail_malformed_htlcs.is_empty());
1066 assert!(updates.update_fee.is_none());
1067 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1068 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1069 check_added_monitors!(nodes[1], 1);
1070 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1071 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1073 assert!(updates_2.update_add_htlcs.is_empty());
1074 assert!(updates_2.update_fail_htlcs.is_empty());
1075 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1076 assert!(updates_2.update_fee.is_none());
1077 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1078 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1079 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1081 let events = nodes[0].node.get_and_clear_pending_events();
1082 assert_eq!(events.len(), 1);
1084 Event::PaymentSent { ref payment_preimage } => {
1085 assert_eq!(our_payment_preimage, *payment_preimage);
1087 _ => panic!("Unexpected event"),
1090 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1092 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1093 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1094 assert!(node_1_closing_signed.is_some());
1097 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1098 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1100 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1101 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1102 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1103 if recv_count == 0 {
1104 // If all closing_signeds weren't delivered we can just resume where we left off...
1105 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1107 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1108 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1109 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1111 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1112 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1113 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1115 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1116 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1118 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1119 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1120 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1122 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1123 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1124 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1125 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1126 assert!(node_0_none.is_none());
1128 // If one node, however, received + responded with an identical closing_signed we end
1129 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1130 // There isn't really anything better we can do simply, but in the future we might
1131 // explore storing a set of recently-closed channels that got disconnected during
1132 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1133 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1135 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1137 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1138 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1139 assert_eq!(msg_events.len(), 1);
1140 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1142 &ErrorAction::SendErrorMessage { ref msg } => {
1143 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1144 assert_eq!(msg.channel_id, chan_1.2);
1146 _ => panic!("Unexpected event!"),
1148 } else { panic!("Needed SendErrorMessage close"); }
1150 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1151 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1152 // closing_signed so we do it ourselves
1153 check_closed_broadcast!(nodes[0], false);
1154 check_added_monitors!(nodes[0], 1);
1157 assert!(nodes[0].node.list_channels().is_empty());
1159 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1160 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1161 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1162 assert!(nodes[1].node.list_channels().is_empty());
1163 assert!(nodes[2].node.list_channels().is_empty());
1167 fn test_shutdown_rebroadcast() {
1168 do_test_shutdown_rebroadcast(0);
1169 do_test_shutdown_rebroadcast(1);
1170 do_test_shutdown_rebroadcast(2);
1174 fn fake_network_test() {
1175 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1176 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1177 let chanmon_cfgs = create_chanmon_cfgs(4);
1178 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1179 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1180 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1182 // Create some initial channels
1183 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1184 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1185 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1187 // Rebalance the network a bit by relaying one payment through all the channels...
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);
1191 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1193 // Send some more payments
1194 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1195 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1196 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1198 // Test failure packets
1199 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1200 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1202 // Add a new channel that skips 3
1203 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1205 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1206 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_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);
1211 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1213 // Do some rebalance loop payments, simultaneously
1214 let mut hops = Vec::with_capacity(3);
1215 hops.push(RouteHop {
1216 pubkey: nodes[2].node.get_our_node_id(),
1217 node_features: NodeFeatures::empty(),
1218 short_channel_id: chan_2.0.contents.short_channel_id,
1219 channel_features: ChannelFeatures::empty(),
1221 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1223 hops.push(RouteHop {
1224 pubkey: nodes[3].node.get_our_node_id(),
1225 node_features: NodeFeatures::empty(),
1226 short_channel_id: chan_3.0.contents.short_channel_id,
1227 channel_features: ChannelFeatures::empty(),
1229 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1231 hops.push(RouteHop {
1232 pubkey: nodes[1].node.get_our_node_id(),
1233 node_features: NodeFeatures::empty(),
1234 short_channel_id: chan_4.0.contents.short_channel_id,
1235 channel_features: ChannelFeatures::empty(),
1237 cltv_expiry_delta: TEST_FINAL_CLTV,
1239 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;
1240 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;
1241 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1243 let mut hops = Vec::with_capacity(3);
1244 hops.push(RouteHop {
1245 pubkey: nodes[3].node.get_our_node_id(),
1246 node_features: NodeFeatures::empty(),
1247 short_channel_id: chan_4.0.contents.short_channel_id,
1248 channel_features: ChannelFeatures::empty(),
1250 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1252 hops.push(RouteHop {
1253 pubkey: nodes[2].node.get_our_node_id(),
1254 node_features: NodeFeatures::empty(),
1255 short_channel_id: chan_3.0.contents.short_channel_id,
1256 channel_features: ChannelFeatures::empty(),
1258 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1260 hops.push(RouteHop {
1261 pubkey: nodes[1].node.get_our_node_id(),
1262 node_features: NodeFeatures::empty(),
1263 short_channel_id: chan_2.0.contents.short_channel_id,
1264 channel_features: ChannelFeatures::empty(),
1266 cltv_expiry_delta: TEST_FINAL_CLTV,
1268 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;
1269 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;
1270 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1272 // Claim the rebalances...
1273 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1274 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1276 // Add a duplicate new channel from 2 to 4
1277 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1279 // Send some payments across both channels
1280 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1281 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1282 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1285 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1286 let events = nodes[0].node.get_and_clear_pending_msg_events();
1287 assert_eq!(events.len(), 0);
1288 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);
1290 //TODO: Test that routes work again here as we've been notified that the channel is full
1292 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1293 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1294 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1296 // Close down the channels...
1297 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1298 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1299 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1300 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1301 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1305 fn holding_cell_htlc_counting() {
1306 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1307 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1308 // commitment dance rounds.
1309 let chanmon_cfgs = create_chanmon_cfgs(3);
1310 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1311 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1312 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1313 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1314 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1315 let logger = test_utils::TestLogger::new();
1317 let mut payments = Vec::new();
1318 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1319 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1320 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1321 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();
1322 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1323 payments.push((payment_preimage, payment_hash));
1325 check_added_monitors!(nodes[1], 1);
1327 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1328 assert_eq!(events.len(), 1);
1329 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1330 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1332 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1333 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1335 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1337 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1338 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();
1339 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1340 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1341 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1342 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1345 // This should also be true if we try to forward a payment.
1346 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1348 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1349 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();
1350 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1351 check_added_monitors!(nodes[0], 1);
1354 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1355 assert_eq!(events.len(), 1);
1356 let payment_event = SendEvent::from_event(events.pop().unwrap());
1357 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1359 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1360 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1361 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1362 // fails), the second will process the resulting failure and fail the HTLC backward.
1363 expect_pending_htlcs_forwardable!(nodes[1]);
1364 expect_pending_htlcs_forwardable!(nodes[1]);
1365 check_added_monitors!(nodes[1], 1);
1367 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1368 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1369 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1371 let events = nodes[0].node.get_and_clear_pending_msg_events();
1372 assert_eq!(events.len(), 1);
1374 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1375 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1377 _ => panic!("Unexpected event"),
1380 expect_payment_failed!(nodes[0], payment_hash_2, false);
1382 // Now forward all the pending HTLCs and claim them back
1383 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1384 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1385 check_added_monitors!(nodes[2], 1);
1387 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1388 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1389 check_added_monitors!(nodes[1], 1);
1390 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1392 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1393 check_added_monitors!(nodes[1], 1);
1394 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1396 for ref update in as_updates.update_add_htlcs.iter() {
1397 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1399 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1400 check_added_monitors!(nodes[2], 1);
1401 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1402 check_added_monitors!(nodes[2], 1);
1403 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1405 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1406 check_added_monitors!(nodes[1], 1);
1407 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1408 check_added_monitors!(nodes[1], 1);
1409 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1411 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1412 check_added_monitors!(nodes[2], 1);
1414 expect_pending_htlcs_forwardable!(nodes[2]);
1416 let events = nodes[2].node.get_and_clear_pending_events();
1417 assert_eq!(events.len(), payments.len());
1418 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1420 &Event::PaymentReceived { ref payment_hash, .. } => {
1421 assert_eq!(*payment_hash, *hash);
1423 _ => panic!("Unexpected event"),
1427 for (preimage, _) in payments.drain(..) {
1428 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1431 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1435 fn duplicate_htlc_test() {
1436 // Test that we accept duplicate payment_hash HTLCs across the network and that
1437 // claiming/failing them are all separate and don't affect each other
1438 let chanmon_cfgs = create_chanmon_cfgs(6);
1439 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1440 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1441 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1443 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1444 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1445 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1446 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1447 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1448 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1450 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1452 *nodes[0].network_payment_count.borrow_mut() -= 1;
1453 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1455 *nodes[0].network_payment_count.borrow_mut() -= 1;
1456 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1458 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1459 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1460 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1464 fn test_duplicate_htlc_different_direction_onchain() {
1465 // Test that ChannelMonitor doesn't generate 2 preimage txn
1466 // when we have 2 HTLCs with same preimage that go across a node
1467 // in opposite directions.
1468 let chanmon_cfgs = create_chanmon_cfgs(2);
1469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1471 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1473 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1474 let logger = test_utils::TestLogger::new();
1477 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1479 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1481 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1482 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();
1483 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1485 // Provide preimage to node 0 by claiming payment
1486 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1487 check_added_monitors!(nodes[0], 1);
1489 // Broadcast node 1 commitment txn
1490 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1492 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1493 let mut has_both_htlcs = 0; // check htlcs match ones committed
1494 for outp in remote_txn[0].output.iter() {
1495 if outp.value == 800_000 / 1000 {
1496 has_both_htlcs += 1;
1497 } else if outp.value == 900_000 / 1000 {
1498 has_both_htlcs += 1;
1501 assert_eq!(has_both_htlcs, 2);
1503 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1504 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1505 check_added_monitors!(nodes[0], 1);
1507 // Check we only broadcast 1 timeout tx
1508 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1509 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()) };
1510 assert_eq!(claim_txn.len(), 5);
1511 check_spends!(claim_txn[2], chan_1.3);
1512 check_spends!(claim_txn[3], claim_txn[2]);
1513 assert_eq!(htlc_pair.0.input.len(), 1);
1514 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1515 check_spends!(htlc_pair.0, remote_txn[0]);
1516 assert_eq!(htlc_pair.1.input.len(), 1);
1517 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1518 check_spends!(htlc_pair.1, remote_txn[0]);
1520 let events = nodes[0].node.get_and_clear_pending_msg_events();
1521 assert_eq!(events.len(), 2);
1524 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1525 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, .. } } => {
1526 assert!(update_add_htlcs.is_empty());
1527 assert!(update_fail_htlcs.is_empty());
1528 assert_eq!(update_fulfill_htlcs.len(), 1);
1529 assert!(update_fail_malformed_htlcs.is_empty());
1530 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1532 _ => panic!("Unexpected event"),
1538 fn test_basic_channel_reserve() {
1539 let chanmon_cfgs = create_chanmon_cfgs(2);
1540 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1541 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1542 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1543 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1544 let logger = test_utils::TestLogger::new();
1546 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1547 let channel_reserve = chan_stat.channel_reserve_msat;
1549 // The 2* and +1 are for the fee spike reserve.
1550 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1551 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1552 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1553 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1554 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();
1555 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1557 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1559 &APIError::ChannelUnavailable{ref err} =>
1560 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1561 _ => panic!("Unexpected error variant"),
1564 _ => panic!("Unexpected error variant"),
1566 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1567 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);
1569 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1573 fn test_fee_spike_violation_fails_htlc() {
1574 let chanmon_cfgs = create_chanmon_cfgs(2);
1575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1577 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1578 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1579 let logger = test_utils::TestLogger::new();
1581 macro_rules! get_route_and_payment_hash {
1582 ($recv_value: expr) => {{
1583 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1584 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1585 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();
1586 (route, payment_hash, payment_preimage)
1590 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1591 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1592 let secp_ctx = Secp256k1::new();
1593 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1595 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1597 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1598 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1599 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1600 let msg = msgs::UpdateAddHTLC {
1603 amount_msat: htlc_msat,
1604 payment_hash: payment_hash,
1605 cltv_expiry: htlc_cltv,
1606 onion_routing_packet: onion_packet,
1609 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1611 // Now manually create the commitment_signed message corresponding to the update_add
1612 // nodes[0] just sent. In the code for construction of this message, "local" refers
1613 // to the sender of the message, and "remote" refers to the receiver.
1615 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1617 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1619 // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1620 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1621 let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1622 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1623 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1624 let chan_keys = local_chan.get_keys();
1625 let pubkeys = chan_keys.pubkeys();
1626 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1627 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1629 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1630 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1631 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1632 let chan_keys = remote_chan.get_keys();
1633 let pubkeys = chan_keys.pubkeys();
1634 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1635 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1638 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1639 let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1640 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1641 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1642 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1644 // Build the remote commitment transaction so we can sign it, and then later use the
1645 // signature for the commitment_signed message.
1646 let local_chan_balance = 1313;
1647 let static_payment_pk = local_payment_point.serialize();
1648 let remote_commit_tx_output = TxOut {
1649 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1650 .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1652 value: local_chan_balance as u64
1655 let local_commit_tx_output = TxOut {
1656 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1658 &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1662 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1664 amount_msat: 3460001,
1665 cltv_expiry: htlc_cltv,
1666 payment_hash: payment_hash,
1667 transaction_output_index: Some(1),
1670 let htlc_output = TxOut {
1671 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1672 value: 3460001 / 1000
1675 let commit_tx_obscure_factor = {
1676 let mut sha = Sha256::engine();
1677 let remote_payment_point = &remote_payment_point.serialize();
1678 sha.input(&local_payment_point.serialize());
1679 sha.input(remote_payment_point);
1680 let res = Sha256::from_engine(sha).into_inner();
1682 ((res[26] as u64) << 5*8) |
1683 ((res[27] as u64) << 4*8) |
1684 ((res[28] as u64) << 3*8) |
1685 ((res[29] as u64) << 2*8) |
1686 ((res[30] as u64) << 1*8) |
1687 ((res[31] as u64) << 0*8)
1689 let commitment_number = 1;
1690 let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1691 let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1693 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1694 script_sig: Script::new(),
1695 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1696 witness: Vec::new(),
1699 let commit_tx = Transaction {
1703 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1706 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1707 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1708 let local_chan_keys = local_chan.get_keys();
1709 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1710 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1713 let commit_signed_msg = msgs::CommitmentSigned {
1716 htlc_signatures: res.1
1719 // Send the commitment_signed message to the nodes[1].
1720 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1721 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1723 // Send the RAA to nodes[1].
1724 let per_commitment_secret = local_secret;
1725 let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1726 let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1727 let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1728 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1730 let events = nodes[1].node.get_and_clear_pending_msg_events();
1731 assert_eq!(events.len(), 1);
1732 // Make sure the HTLC failed in the way we expect.
1734 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1735 assert_eq!(update_fail_htlcs.len(), 1);
1736 update_fail_htlcs[0].clone()
1738 _ => panic!("Unexpected event"),
1740 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1742 check_added_monitors!(nodes[1], 2);
1746 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1747 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1748 // Set the fee rate for the channel very high, to the point where the fundee
1749 // sending any amount would result in a channel reserve violation. In this test
1750 // we check that we would be prevented from sending an HTLC in this situation.
1751 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1752 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1753 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1754 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1755 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1756 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1757 let logger = test_utils::TestLogger::new();
1759 macro_rules! get_route_and_payment_hash {
1760 ($recv_value: expr) => {{
1761 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1762 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1763 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();
1764 (route, payment_hash, payment_preimage)
1768 let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1769 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1770 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1771 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1772 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);
1776 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1777 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1778 // Set the fee rate for the channel very high, to the point where the funder
1779 // receiving 1 update_add_htlc would result in them closing the channel due
1780 // to channel reserve violation. This close could also happen if the fee went
1781 // up a more realistic amount, but many HTLCs were outstanding at the time of
1782 // the update_add_htlc.
1783 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1784 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1787 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1788 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1789 let logger = test_utils::TestLogger::new();
1791 macro_rules! get_route_and_payment_hash {
1792 ($recv_value: expr) => {{
1793 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1794 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1795 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();
1796 (route, payment_hash, payment_preimage)
1800 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1801 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1802 let secp_ctx = Secp256k1::new();
1803 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1804 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1805 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1806 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1807 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1808 let msg = msgs::UpdateAddHTLC {
1811 amount_msat: htlc_msat + 1,
1812 payment_hash: payment_hash,
1813 cltv_expiry: htlc_cltv,
1814 onion_routing_packet: onion_packet,
1817 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1818 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1819 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);
1820 assert_eq!(nodes[0].node.list_channels().len(), 0);
1821 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1822 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1823 check_added_monitors!(nodes[0], 1);
1827 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1828 let chanmon_cfgs = create_chanmon_cfgs(3);
1829 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1830 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1831 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1832 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1833 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1834 let logger = test_utils::TestLogger::new();
1836 macro_rules! get_route_and_payment_hash {
1837 ($recv_value: expr) => {{
1838 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1839 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1840 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();
1841 (route, payment_hash, payment_preimage)
1846 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1847 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1848 let feerate = get_feerate!(nodes[0], chan.2);
1850 // Add a 2* and +1 for the fee spike reserve.
1851 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1852 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;
1853 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1855 // Add a pending HTLC.
1856 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1857 let payment_event_1 = {
1858 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1859 check_added_monitors!(nodes[0], 1);
1861 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1862 assert_eq!(events.len(), 1);
1863 SendEvent::from_event(events.remove(0))
1865 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1867 // Attempt to trigger a channel reserve violation --> payment failure.
1868 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1869 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;
1870 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1871 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1873 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1874 let secp_ctx = Secp256k1::new();
1875 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1876 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1877 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1878 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1879 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1880 let msg = msgs::UpdateAddHTLC {
1883 amount_msat: htlc_msat + 1,
1884 payment_hash: our_payment_hash_1,
1885 cltv_expiry: htlc_cltv,
1886 onion_routing_packet: onion_packet,
1889 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1890 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1891 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1892 assert_eq!(nodes[1].node.list_channels().len(), 1);
1893 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1894 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1895 check_added_monitors!(nodes[1], 1);
1899 fn test_inbound_outbound_capacity_is_not_zero() {
1900 let chanmon_cfgs = create_chanmon_cfgs(2);
1901 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1902 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1903 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1904 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1905 let channels0 = node_chanmgrs[0].list_channels();
1906 let channels1 = node_chanmgrs[1].list_channels();
1907 assert_eq!(channels0.len(), 1);
1908 assert_eq!(channels1.len(), 1);
1910 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1911 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1913 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1914 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1917 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1918 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1922 fn test_channel_reserve_holding_cell_htlcs() {
1923 let chanmon_cfgs = create_chanmon_cfgs(3);
1924 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1925 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1926 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1927 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1928 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1929 let logger = test_utils::TestLogger::new();
1931 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1932 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1934 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1935 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1937 macro_rules! get_route_and_payment_hash {
1938 ($recv_value: expr) => {{
1939 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1940 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1941 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();
1942 (route, payment_hash, payment_preimage)
1946 macro_rules! expect_forward {
1948 let mut events = $node.node.get_and_clear_pending_msg_events();
1949 assert_eq!(events.len(), 1);
1950 check_added_monitors!($node, 1);
1951 let payment_event = SendEvent::from_event(events.remove(0));
1956 let feemsat = 239; // somehow we know?
1957 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1958 let feerate = get_feerate!(nodes[0], chan_1.2);
1960 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1962 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1964 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1965 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1966 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1967 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)));
1968 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1969 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);
1972 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1973 // nodes[0]'s wealth
1975 let amt_msat = recv_value_0 + total_fee_msat;
1976 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1977 // Also, ensure that each payment has enough to be over the dust limit to
1978 // ensure it'll be included in each commit tx fee calculation.
1979 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1980 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1981 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1984 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1986 let (stat01_, stat11_, stat12_, stat22_) = (
1987 get_channel_value_stat!(nodes[0], chan_1.2),
1988 get_channel_value_stat!(nodes[1], chan_1.2),
1989 get_channel_value_stat!(nodes[1], chan_2.2),
1990 get_channel_value_stat!(nodes[2], chan_2.2),
1993 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1994 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1995 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1996 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1997 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2000 // adding pending output.
2001 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2002 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2003 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2004 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2005 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2006 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2007 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2008 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2009 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2011 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2012 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2013 let amt_msat_1 = recv_value_1 + total_fee_msat;
2015 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2016 let payment_event_1 = {
2017 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2018 check_added_monitors!(nodes[0], 1);
2020 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2021 assert_eq!(events.len(), 1);
2022 SendEvent::from_event(events.remove(0))
2024 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2026 // channel reserve test with htlc pending output > 0
2027 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2029 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2030 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2031 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2032 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2035 // split the rest to test holding cell
2036 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2037 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2038 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2039 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2041 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2042 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);
2045 // now see if they go through on both sides
2046 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2047 // but this will stuck in the holding cell
2048 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2049 check_added_monitors!(nodes[0], 0);
2050 let events = nodes[0].node.get_and_clear_pending_events();
2051 assert_eq!(events.len(), 0);
2053 // test with outbound holding cell amount > 0
2055 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2056 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2057 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2058 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2059 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);
2062 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2063 // this will also stuck in the holding cell
2064 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2065 check_added_monitors!(nodes[0], 0);
2066 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2067 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2069 // flush the pending htlc
2070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2071 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2072 check_added_monitors!(nodes[1], 1);
2074 // the pending htlc should be promoted to committed
2075 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2076 check_added_monitors!(nodes[0], 1);
2077 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2079 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2080 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2081 // No commitment_signed so get_event_msg's assert(len == 1) passes
2082 check_added_monitors!(nodes[0], 1);
2084 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2085 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2086 check_added_monitors!(nodes[1], 1);
2088 expect_pending_htlcs_forwardable!(nodes[1]);
2090 let ref payment_event_11 = expect_forward!(nodes[1]);
2091 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2092 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2094 expect_pending_htlcs_forwardable!(nodes[2]);
2095 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2097 // flush the htlcs in the holding cell
2098 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2099 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2100 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2101 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2102 expect_pending_htlcs_forwardable!(nodes[1]);
2104 let ref payment_event_3 = expect_forward!(nodes[1]);
2105 assert_eq!(payment_event_3.msgs.len(), 2);
2106 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2107 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2109 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2110 expect_pending_htlcs_forwardable!(nodes[2]);
2112 let events = nodes[2].node.get_and_clear_pending_events();
2113 assert_eq!(events.len(), 2);
2115 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2116 assert_eq!(our_payment_hash_21, *payment_hash);
2117 assert_eq!(*payment_secret, None);
2118 assert_eq!(recv_value_21, amt);
2120 _ => panic!("Unexpected event"),
2123 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2124 assert_eq!(our_payment_hash_22, *payment_hash);
2125 assert_eq!(None, *payment_secret);
2126 assert_eq!(recv_value_22, amt);
2128 _ => panic!("Unexpected event"),
2131 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2132 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2133 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2135 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2136 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2138 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2139 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2141 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2143 &APIError::ChannelUnavailable{ref err} =>
2144 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2145 _ => panic!("Unexpected error variant"),
2148 _ => panic!("Unexpected error variant"),
2150 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2151 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);
2154 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2156 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2157 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);
2158 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2159 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2160 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2162 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2163 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2167 fn channel_reserve_in_flight_removes() {
2168 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2169 // can send to its counterparty, but due to update ordering, the other side may not yet have
2170 // considered those HTLCs fully removed.
2171 // This tests that we don't count HTLCs which will not be included in the next remote
2172 // commitment transaction towards the reserve value (as it implies no commitment transaction
2173 // will be generated which violates the remote reserve value).
2174 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2176 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2177 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2178 // you only consider the value of the first HTLC, it may not),
2179 // * start routing a third HTLC from A to B,
2180 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2181 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2182 // * deliver the first fulfill from B
2183 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2185 // * deliver A's response CS and RAA.
2186 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2187 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2188 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2189 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2190 let chanmon_cfgs = create_chanmon_cfgs(2);
2191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2193 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2194 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2195 let logger = test_utils::TestLogger::new();
2197 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2198 // Route the first two HTLCs.
2199 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2200 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2202 // Start routing the third HTLC (this is just used to get everyone in the right state).
2203 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2205 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2206 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();
2207 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2208 check_added_monitors!(nodes[0], 1);
2209 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2210 assert_eq!(events.len(), 1);
2211 SendEvent::from_event(events.remove(0))
2214 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2215 // initial fulfill/CS.
2216 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2217 check_added_monitors!(nodes[1], 1);
2218 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2220 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2221 // remove the second HTLC when we send the HTLC back from B to A.
2222 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2223 check_added_monitors!(nodes[1], 1);
2224 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2226 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2227 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2228 check_added_monitors!(nodes[0], 1);
2229 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2230 expect_payment_sent!(nodes[0], payment_preimage_1);
2232 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2233 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2234 check_added_monitors!(nodes[1], 1);
2235 // B is already AwaitingRAA, so cant generate a CS here
2236 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2238 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2239 check_added_monitors!(nodes[1], 1);
2240 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2242 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2243 check_added_monitors!(nodes[0], 1);
2244 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2246 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2247 check_added_monitors!(nodes[1], 1);
2248 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2250 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2251 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2252 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2253 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2254 // on-chain as necessary).
2255 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2256 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2257 check_added_monitors!(nodes[0], 1);
2258 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2259 expect_payment_sent!(nodes[0], payment_preimage_2);
2261 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2262 check_added_monitors!(nodes[1], 1);
2263 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2265 expect_pending_htlcs_forwardable!(nodes[1]);
2266 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2268 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2269 // resolve the second HTLC from A's point of view.
2270 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2271 check_added_monitors!(nodes[0], 1);
2272 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2274 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2275 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2276 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2278 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2279 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();
2280 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2281 check_added_monitors!(nodes[1], 1);
2282 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2283 assert_eq!(events.len(), 1);
2284 SendEvent::from_event(events.remove(0))
2287 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2288 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2289 check_added_monitors!(nodes[0], 1);
2290 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2292 // Now just resolve all the outstanding messages/HTLCs for completeness...
2294 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2295 check_added_monitors!(nodes[1], 1);
2296 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2298 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2299 check_added_monitors!(nodes[1], 1);
2301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2302 check_added_monitors!(nodes[0], 1);
2303 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2305 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2306 check_added_monitors!(nodes[1], 1);
2307 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2309 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2310 check_added_monitors!(nodes[0], 1);
2312 expect_pending_htlcs_forwardable!(nodes[0]);
2313 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2315 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2316 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2320 fn channel_monitor_network_test() {
2321 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2322 // tests that ChannelMonitor is able to recover from various states.
2323 let chanmon_cfgs = create_chanmon_cfgs(5);
2324 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2325 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2326 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2328 // Create some initial channels
2329 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2330 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2331 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2332 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2334 // Rebalance the network a bit by relaying one payment through all the channels...
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);
2338 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2340 // Simple case with no pending HTLCs:
2341 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2342 check_added_monitors!(nodes[1], 1);
2344 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2345 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2346 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2347 check_added_monitors!(nodes[0], 1);
2348 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2350 get_announce_close_broadcast_events(&nodes, 0, 1);
2351 assert_eq!(nodes[0].node.list_channels().len(), 0);
2352 assert_eq!(nodes[1].node.list_channels().len(), 1);
2354 // One pending HTLC is discarded by the force-close:
2355 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2357 // Simple case of one pending HTLC to HTLC-Timeout
2358 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2359 check_added_monitors!(nodes[1], 1);
2361 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2362 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2363 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2364 check_added_monitors!(nodes[2], 1);
2365 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2367 get_announce_close_broadcast_events(&nodes, 1, 2);
2368 assert_eq!(nodes[1].node.list_channels().len(), 0);
2369 assert_eq!(nodes[2].node.list_channels().len(), 1);
2371 macro_rules! claim_funds {
2372 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2374 assert!($node.node.claim_funds($preimage, &None, $amount));
2375 check_added_monitors!($node, 1);
2377 let events = $node.node.get_and_clear_pending_msg_events();
2378 assert_eq!(events.len(), 1);
2380 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2381 assert!(update_add_htlcs.is_empty());
2382 assert!(update_fail_htlcs.is_empty());
2383 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2385 _ => panic!("Unexpected event"),
2391 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2392 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2393 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2394 check_added_monitors!(nodes[2], 1);
2395 let node2_commitment_txid;
2397 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2398 node2_commitment_txid = node_txn[0].txid();
2400 // Claim the payment on nodes[3], giving it knowledge of the preimage
2401 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2404 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2405 check_added_monitors!(nodes[3], 1);
2407 check_preimage_claim(&nodes[3], &node_txn);
2409 get_announce_close_broadcast_events(&nodes, 2, 3);
2410 assert_eq!(nodes[2].node.list_channels().len(), 0);
2411 assert_eq!(nodes[3].node.list_channels().len(), 1);
2413 { // Cheat and reset nodes[4]'s height to 1
2414 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2415 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2418 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2419 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2420 // One pending HTLC to time out:
2421 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2422 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2425 let (close_chan_update_1, close_chan_update_2) = {
2426 let mut block = Block {
2427 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2430 connect_block(&nodes[3], &block, 2);
2431 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2433 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2436 connect_block(&nodes[3], &block, i);
2438 let events = nodes[3].node.get_and_clear_pending_msg_events();
2439 assert_eq!(events.len(), 1);
2440 let close_chan_update_1 = match events[0] {
2441 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2444 _ => panic!("Unexpected event"),
2446 check_added_monitors!(nodes[3], 1);
2448 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2450 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2451 node_txn.retain(|tx| {
2452 if tx.input[0].previous_output.txid == node2_commitment_txid {
2458 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2460 // Claim the payment on nodes[4], giving it knowledge of the preimage
2461 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2464 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2468 connect_block(&nodes[4], &block, 2);
2469 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2471 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2474 connect_block(&nodes[4], &block, i);
2476 let events = nodes[4].node.get_and_clear_pending_msg_events();
2477 assert_eq!(events.len(), 1);
2478 let close_chan_update_2 = match events[0] {
2479 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2482 _ => panic!("Unexpected event"),
2484 check_added_monitors!(nodes[4], 1);
2485 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2488 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2489 txdata: vec![node_txn[0].clone()],
2491 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2493 check_preimage_claim(&nodes[4], &node_txn);
2494 (close_chan_update_1, close_chan_update_2)
2496 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2497 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2498 assert_eq!(nodes[3].node.list_channels().len(), 0);
2499 assert_eq!(nodes[4].node.list_channels().len(), 0);
2503 fn test_justice_tx() {
2504 // Test justice txn built on revoked HTLC-Success tx, against both sides
2505 let mut alice_config = UserConfig::default();
2506 alice_config.channel_options.announced_channel = true;
2507 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2508 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2509 let mut bob_config = UserConfig::default();
2510 bob_config.channel_options.announced_channel = true;
2511 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2512 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2513 let user_cfgs = [Some(alice_config), Some(bob_config)];
2514 let chanmon_cfgs = create_chanmon_cfgs(2);
2515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2518 // Create some new channels:
2519 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2521 // A pending HTLC which will be revoked:
2522 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2523 // Get the will-be-revoked local txn from nodes[0]
2524 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2525 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2526 assert_eq!(revoked_local_txn[0].input.len(), 1);
2527 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2528 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2529 assert_eq!(revoked_local_txn[1].input.len(), 1);
2530 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2531 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2532 // Revoke the old state
2533 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2536 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2537 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2539 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2540 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2541 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2543 check_spends!(node_txn[0], revoked_local_txn[0]);
2544 node_txn.swap_remove(0);
2545 node_txn.truncate(1);
2547 check_added_monitors!(nodes[1], 1);
2548 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2550 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2551 // Verify broadcast of revoked HTLC-timeout
2552 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2553 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2554 check_added_monitors!(nodes[0], 1);
2555 // Broadcast revoked HTLC-timeout on node 1
2556 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2557 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2559 get_announce_close_broadcast_events(&nodes, 0, 1);
2561 assert_eq!(nodes[0].node.list_channels().len(), 0);
2562 assert_eq!(nodes[1].node.list_channels().len(), 0);
2564 // We test justice_tx build by A on B's revoked HTLC-Success tx
2565 // Create some new channels:
2566 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2568 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2572 // A pending HTLC which will be revoked:
2573 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2574 // Get the will-be-revoked local txn from B
2575 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2576 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2577 assert_eq!(revoked_local_txn[0].input.len(), 1);
2578 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2579 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2580 // Revoke the old state
2581 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2583 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2584 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2586 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2587 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2588 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2590 check_spends!(node_txn[0], revoked_local_txn[0]);
2591 node_txn.swap_remove(0);
2593 check_added_monitors!(nodes[0], 1);
2594 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2596 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2597 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2598 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2599 check_added_monitors!(nodes[1], 1);
2600 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2601 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2603 get_announce_close_broadcast_events(&nodes, 0, 1);
2604 assert_eq!(nodes[0].node.list_channels().len(), 0);
2605 assert_eq!(nodes[1].node.list_channels().len(), 0);
2609 fn revoked_output_claim() {
2610 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2611 // transaction is broadcast by its counterparty
2612 let chanmon_cfgs = create_chanmon_cfgs(2);
2613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2616 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2617 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2618 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2619 assert_eq!(revoked_local_txn.len(), 1);
2620 // Only output is the full channel value back to nodes[0]:
2621 assert_eq!(revoked_local_txn[0].output.len(), 1);
2622 // Send a payment through, updating everyone's latest commitment txn
2623 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2625 // Inform nodes[1] that nodes[0] broadcast a stale tx
2626 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2627 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2628 check_added_monitors!(nodes[1], 1);
2629 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2630 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2632 check_spends!(node_txn[0], revoked_local_txn[0]);
2633 check_spends!(node_txn[1], chan_1.3);
2635 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2636 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2637 get_announce_close_broadcast_events(&nodes, 0, 1);
2638 check_added_monitors!(nodes[0], 1)
2642 fn claim_htlc_outputs_shared_tx() {
2643 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2644 let chanmon_cfgs = create_chanmon_cfgs(2);
2645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2649 // Create some new channel:
2650 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2652 // Rebalance the network to generate htlc in the two directions
2653 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2654 // 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
2655 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2656 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2658 // Get the will-be-revoked local txn from node[0]
2659 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2660 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2661 assert_eq!(revoked_local_txn[0].input.len(), 1);
2662 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2663 assert_eq!(revoked_local_txn[1].input.len(), 1);
2664 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2665 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2666 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2668 //Revoke the old state
2669 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2672 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2673 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2674 check_added_monitors!(nodes[0], 1);
2675 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2676 check_added_monitors!(nodes[1], 1);
2677 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2678 expect_payment_failed!(nodes[1], payment_hash_2, true);
2680 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2681 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2683 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2684 check_spends!(node_txn[0], revoked_local_txn[0]);
2686 let mut witness_lens = BTreeSet::new();
2687 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2688 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2689 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2690 assert_eq!(witness_lens.len(), 3);
2691 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2692 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2693 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2695 // Next nodes[1] broadcasts its current local tx state:
2696 assert_eq!(node_txn[1].input.len(), 1);
2697 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2699 assert_eq!(node_txn[2].input.len(), 1);
2700 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2701 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2702 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2703 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2704 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2706 get_announce_close_broadcast_events(&nodes, 0, 1);
2707 assert_eq!(nodes[0].node.list_channels().len(), 0);
2708 assert_eq!(nodes[1].node.list_channels().len(), 0);
2712 fn claim_htlc_outputs_single_tx() {
2713 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2714 let chanmon_cfgs = create_chanmon_cfgs(2);
2715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2717 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2719 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2721 // Rebalance the network to generate htlc in the two directions
2722 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2723 // 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
2724 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2725 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2726 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2728 // Get the will-be-revoked local txn from node[0]
2729 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2731 //Revoke the old state
2732 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2735 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2736 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2737 check_added_monitors!(nodes[0], 1);
2738 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2739 check_added_monitors!(nodes[1], 1);
2740 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2742 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2743 expect_payment_failed!(nodes[1], payment_hash_2, true);
2745 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2746 assert_eq!(node_txn.len(), 9);
2747 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2748 // ChannelManager: local commmitment + local HTLC-timeout (2)
2749 // 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)
2750 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2752 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2753 assert_eq!(node_txn[2].input.len(), 1);
2754 check_spends!(node_txn[2], chan_1.3);
2755 assert_eq!(node_txn[3].input.len(), 1);
2756 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2757 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2758 check_spends!(node_txn[3], node_txn[2]);
2760 // Justice transactions are indices 1-2-4
2761 assert_eq!(node_txn[0].input.len(), 1);
2762 assert_eq!(node_txn[1].input.len(), 1);
2763 assert_eq!(node_txn[4].input.len(), 1);
2765 check_spends!(node_txn[0], revoked_local_txn[0]);
2766 check_spends!(node_txn[1], revoked_local_txn[0]);
2767 check_spends!(node_txn[4], revoked_local_txn[0]);
2769 let mut witness_lens = BTreeSet::new();
2770 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2771 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2772 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2773 assert_eq!(witness_lens.len(), 3);
2774 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2775 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2776 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2778 get_announce_close_broadcast_events(&nodes, 0, 1);
2779 assert_eq!(nodes[0].node.list_channels().len(), 0);
2780 assert_eq!(nodes[1].node.list_channels().len(), 0);
2784 fn test_htlc_on_chain_success() {
2785 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2786 // the preimage backward accordingly. So here we test that ChannelManager is
2787 // broadcasting the right event to other nodes in payment path.
2788 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2789 // A --------------------> B ----------------------> C (preimage)
2790 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2791 // commitment transaction was broadcast.
2792 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2794 // B should be able to claim via preimage if A then broadcasts its local tx.
2795 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2796 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2797 // PaymentSent event).
2799 let chanmon_cfgs = create_chanmon_cfgs(3);
2800 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2801 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2802 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2804 // Create some initial channels
2805 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2806 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2808 // Rebalance the network a bit by relaying one payment through all the channels...
2809 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2810 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2812 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2813 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2814 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2816 // Broadcast legit commitment tx from C on B's chain
2817 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2818 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2819 assert_eq!(commitment_tx.len(), 1);
2820 check_spends!(commitment_tx[0], chan_2.3);
2821 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2822 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2823 check_added_monitors!(nodes[2], 2);
2824 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2825 assert!(updates.update_add_htlcs.is_empty());
2826 assert!(updates.update_fail_htlcs.is_empty());
2827 assert!(updates.update_fail_malformed_htlcs.is_empty());
2828 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2830 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2831 check_closed_broadcast!(nodes[2], false);
2832 check_added_monitors!(nodes[2], 1);
2833 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)
2834 assert_eq!(node_txn.len(), 5);
2835 assert_eq!(node_txn[0], node_txn[3]);
2836 assert_eq!(node_txn[1], node_txn[4]);
2837 assert_eq!(node_txn[2], commitment_tx[0]);
2838 check_spends!(node_txn[0], commitment_tx[0]);
2839 check_spends!(node_txn[1], commitment_tx[0]);
2840 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2844 assert_eq!(node_txn[0].lock_time, 0);
2845 assert_eq!(node_txn[1].lock_time, 0);
2847 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2848 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2850 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2851 assert_eq!(added_monitors.len(), 1);
2852 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2853 added_monitors.clear();
2855 let events = nodes[1].node.get_and_clear_pending_msg_events();
2857 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2858 assert_eq!(added_monitors.len(), 2);
2859 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2860 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2861 added_monitors.clear();
2863 assert_eq!(events.len(), 2);
2865 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2866 _ => panic!("Unexpected event"),
2869 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, .. } } => {
2870 assert!(update_add_htlcs.is_empty());
2871 assert!(update_fail_htlcs.is_empty());
2872 assert_eq!(update_fulfill_htlcs.len(), 1);
2873 assert!(update_fail_malformed_htlcs.is_empty());
2874 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2876 _ => panic!("Unexpected event"),
2878 macro_rules! check_tx_local_broadcast {
2879 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2880 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2881 assert_eq!(node_txn.len(), 5);
2882 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2883 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2884 check_spends!(node_txn[0], $commitment_tx);
2885 check_spends!(node_txn[1], $commitment_tx);
2886 assert_ne!(node_txn[0].lock_time, 0);
2887 assert_ne!(node_txn[1].lock_time, 0);
2889 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2890 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2891 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2892 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2894 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2895 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2896 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2897 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2899 check_spends!(node_txn[2], $chan_tx);
2900 check_spends!(node_txn[3], node_txn[2]);
2901 check_spends!(node_txn[4], node_txn[2]);
2902 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2903 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2904 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2905 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2906 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2907 assert_ne!(node_txn[3].lock_time, 0);
2908 assert_ne!(node_txn[4].lock_time, 0);
2912 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2913 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2914 // timeout-claim of the output that nodes[2] just claimed via success.
2915 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2917 // Broadcast legit commitment tx from A on B's chain
2918 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2919 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2920 check_spends!(commitment_tx[0], chan_1.3);
2921 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2922 check_closed_broadcast!(nodes[1], false);
2923 check_added_monitors!(nodes[1], 1);
2924 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2925 assert_eq!(node_txn.len(), 4);
2926 check_spends!(node_txn[0], commitment_tx[0]);
2927 assert_eq!(node_txn[0].input.len(), 2);
2928 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2929 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2930 assert_eq!(node_txn[0].lock_time, 0);
2931 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2932 check_spends!(node_txn[1], chan_1.3);
2933 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2934 check_spends!(node_txn[2], node_txn[1]);
2935 check_spends!(node_txn[3], node_txn[1]);
2936 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2937 // we already checked the same situation with A.
2939 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2940 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2941 check_closed_broadcast!(nodes[0], false);
2942 check_added_monitors!(nodes[0], 1);
2943 let events = nodes[0].node.get_and_clear_pending_events();
2944 assert_eq!(events.len(), 2);
2945 let mut first_claimed = false;
2946 for event in events {
2948 Event::PaymentSent { payment_preimage } => {
2949 if payment_preimage == our_payment_preimage {
2950 assert!(!first_claimed);
2951 first_claimed = true;
2953 assert_eq!(payment_preimage, our_payment_preimage_2);
2956 _ => panic!("Unexpected event"),
2959 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2963 fn test_htlc_on_chain_timeout() {
2964 // Test that in case of a unilateral close onchain, we detect the state of output and
2965 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2966 // broadcasting the right event to other nodes in payment path.
2967 // A ------------------> B ----------------------> C (timeout)
2968 // B's commitment tx C's commitment tx
2970 // B's HTLC timeout tx B's timeout tx
2972 let chanmon_cfgs = create_chanmon_cfgs(3);
2973 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2974 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2975 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2977 // Create some intial channels
2978 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2979 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2981 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2982 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2983 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2985 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2986 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2988 // Broadcast legit commitment tx from C on B's chain
2989 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2990 check_spends!(commitment_tx[0], chan_2.3);
2991 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2992 check_added_monitors!(nodes[2], 0);
2993 expect_pending_htlcs_forwardable!(nodes[2]);
2994 check_added_monitors!(nodes[2], 1);
2996 let events = nodes[2].node.get_and_clear_pending_msg_events();
2997 assert_eq!(events.len(), 1);
2999 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, .. } } => {
3000 assert!(update_add_htlcs.is_empty());
3001 assert!(!update_fail_htlcs.is_empty());
3002 assert!(update_fulfill_htlcs.is_empty());
3003 assert!(update_fail_malformed_htlcs.is_empty());
3004 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3006 _ => panic!("Unexpected event"),
3008 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3009 check_closed_broadcast!(nodes[2], false);
3010 check_added_monitors!(nodes[2], 1);
3011 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3012 assert_eq!(node_txn.len(), 1);
3013 check_spends!(node_txn[0], chan_2.3);
3014 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3016 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3017 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3018 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3021 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3022 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3023 assert_eq!(node_txn[1], node_txn[3]);
3024 assert_eq!(node_txn[2], node_txn[4]);
3026 check_spends!(node_txn[0], commitment_tx[0]);
3027 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3029 check_spends!(node_txn[1], chan_2.3);
3030 check_spends!(node_txn[2], node_txn[1]);
3031 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3032 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3034 timeout_tx = node_txn[0].clone();
3038 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3039 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3040 check_added_monitors!(nodes[1], 1);
3041 check_closed_broadcast!(nodes[1], false);
3043 expect_pending_htlcs_forwardable!(nodes[1]);
3044 check_added_monitors!(nodes[1], 1);
3045 let events = nodes[1].node.get_and_clear_pending_msg_events();
3046 assert_eq!(events.len(), 1);
3048 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, .. } } => {
3049 assert!(update_add_htlcs.is_empty());
3050 assert!(!update_fail_htlcs.is_empty());
3051 assert!(update_fulfill_htlcs.is_empty());
3052 assert!(update_fail_malformed_htlcs.is_empty());
3053 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3055 _ => panic!("Unexpected event"),
3057 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
3058 assert_eq!(node_txn.len(), 0);
3060 // Broadcast legit commitment tx from B on A's chain
3061 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3062 check_spends!(commitment_tx[0], chan_1.3);
3064 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3065 check_closed_broadcast!(nodes[0], false);
3066 check_added_monitors!(nodes[0], 1);
3067 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3068 assert_eq!(node_txn.len(), 3);
3069 check_spends!(node_txn[0], commitment_tx[0]);
3070 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3071 check_spends!(node_txn[1], chan_1.3);
3072 check_spends!(node_txn[2], node_txn[1]);
3073 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3074 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3078 fn test_simple_commitment_revoked_fail_backward() {
3079 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3080 // and fail backward accordingly.
3082 let chanmon_cfgs = create_chanmon_cfgs(3);
3083 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3084 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3085 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3087 // Create some initial channels
3088 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3089 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3091 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3092 // Get the will-be-revoked local txn from nodes[2]
3093 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3094 // Revoke the old state
3095 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3097 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3099 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3100 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3101 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3102 check_added_monitors!(nodes[1], 1);
3103 check_closed_broadcast!(nodes[1], false);
3105 expect_pending_htlcs_forwardable!(nodes[1]);
3106 check_added_monitors!(nodes[1], 1);
3107 let events = nodes[1].node.get_and_clear_pending_msg_events();
3108 assert_eq!(events.len(), 1);
3110 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, .. } } => {
3111 assert!(update_add_htlcs.is_empty());
3112 assert_eq!(update_fail_htlcs.len(), 1);
3113 assert!(update_fulfill_htlcs.is_empty());
3114 assert!(update_fail_malformed_htlcs.is_empty());
3115 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3117 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3118 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3120 let events = nodes[0].node.get_and_clear_pending_msg_events();
3121 assert_eq!(events.len(), 1);
3123 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3124 _ => panic!("Unexpected event"),
3126 expect_payment_failed!(nodes[0], payment_hash, false);
3128 _ => panic!("Unexpected event"),
3132 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3133 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3134 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3135 // commitment transaction anymore.
3136 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3137 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3138 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3139 // technically disallowed and we should probably handle it reasonably.
3140 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3141 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3143 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3144 // commitment_signed (implying it will be in the latest remote commitment transaction).
3145 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3146 // and once they revoke the previous commitment transaction (allowing us to send a new
3147 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3148 let chanmon_cfgs = create_chanmon_cfgs(3);
3149 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3150 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3151 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3153 // Create some initial channels
3154 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3155 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3157 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3158 // Get the will-be-revoked local txn from nodes[2]
3159 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3160 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3161 // Revoke the old state
3162 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3164 let value = if use_dust {
3165 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3166 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3167 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3170 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3171 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3172 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3174 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3175 expect_pending_htlcs_forwardable!(nodes[2]);
3176 check_added_monitors!(nodes[2], 1);
3177 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3178 assert!(updates.update_add_htlcs.is_empty());
3179 assert!(updates.update_fulfill_htlcs.is_empty());
3180 assert!(updates.update_fail_malformed_htlcs.is_empty());
3181 assert_eq!(updates.update_fail_htlcs.len(), 1);
3182 assert!(updates.update_fee.is_none());
3183 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3184 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3185 // Drop the last RAA from 3 -> 2
3187 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3188 expect_pending_htlcs_forwardable!(nodes[2]);
3189 check_added_monitors!(nodes[2], 1);
3190 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3191 assert!(updates.update_add_htlcs.is_empty());
3192 assert!(updates.update_fulfill_htlcs.is_empty());
3193 assert!(updates.update_fail_malformed_htlcs.is_empty());
3194 assert_eq!(updates.update_fail_htlcs.len(), 1);
3195 assert!(updates.update_fee.is_none());
3196 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3197 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3198 check_added_monitors!(nodes[1], 1);
3199 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3200 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3201 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3202 check_added_monitors!(nodes[2], 1);
3204 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3205 expect_pending_htlcs_forwardable!(nodes[2]);
3206 check_added_monitors!(nodes[2], 1);
3207 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3208 assert!(updates.update_add_htlcs.is_empty());
3209 assert!(updates.update_fulfill_htlcs.is_empty());
3210 assert!(updates.update_fail_malformed_htlcs.is_empty());
3211 assert_eq!(updates.update_fail_htlcs.len(), 1);
3212 assert!(updates.update_fee.is_none());
3213 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3214 // At this point first_payment_hash has dropped out of the latest two commitment
3215 // transactions that nodes[1] is tracking...
3216 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3217 check_added_monitors!(nodes[1], 1);
3218 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3219 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3220 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3221 check_added_monitors!(nodes[2], 1);
3223 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3224 // on nodes[2]'s RAA.
3225 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3226 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3227 let logger = test_utils::TestLogger::new();
3228 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();
3229 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3230 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3231 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3232 check_added_monitors!(nodes[1], 0);
3235 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3236 // One monitor for the new revocation preimage, no second on as we won't generate a new
3237 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3238 check_added_monitors!(nodes[1], 1);
3239 let events = nodes[1].node.get_and_clear_pending_events();
3240 assert_eq!(events.len(), 1);
3242 Event::PendingHTLCsForwardable { .. } => { },
3243 _ => panic!("Unexpected event"),
3245 // Deliberately don't process the pending fail-back so they all fail back at once after
3246 // block connection just like the !deliver_bs_raa case
3249 let mut failed_htlcs = HashSet::new();
3250 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3252 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3253 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3254 check_added_monitors!(nodes[1], 1);
3255 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3257 let events = nodes[1].node.get_and_clear_pending_events();
3258 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3260 Event::PaymentFailed { ref payment_hash, .. } => {
3261 assert_eq!(*payment_hash, fourth_payment_hash);
3263 _ => panic!("Unexpected event"),
3265 if !deliver_bs_raa {
3267 Event::PendingHTLCsForwardable { .. } => { },
3268 _ => panic!("Unexpected event"),
3271 nodes[1].node.process_pending_htlc_forwards();
3272 check_added_monitors!(nodes[1], 1);
3274 let events = nodes[1].node.get_and_clear_pending_msg_events();
3275 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3276 match events[if deliver_bs_raa { 1 } else { 0 }] {
3277 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3278 _ => panic!("Unexpected event"),
3282 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, .. } } => {
3283 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3284 assert_eq!(update_add_htlcs.len(), 1);
3285 assert!(update_fulfill_htlcs.is_empty());
3286 assert!(update_fail_htlcs.is_empty());
3287 assert!(update_fail_malformed_htlcs.is_empty());
3289 _ => panic!("Unexpected event"),
3292 match events[if deliver_bs_raa { 2 } else { 1 }] {
3293 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, .. } } => {
3294 assert!(update_add_htlcs.is_empty());
3295 assert_eq!(update_fail_htlcs.len(), 3);
3296 assert!(update_fulfill_htlcs.is_empty());
3297 assert!(update_fail_malformed_htlcs.is_empty());
3298 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3300 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3301 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3304 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3306 let events = nodes[0].node.get_and_clear_pending_msg_events();
3307 // If we delivered B's RAA we got an unknown preimage error, not something
3308 // that we should update our routing table for.
3309 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3310 for event in events {
3312 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3313 _ => panic!("Unexpected event"),
3316 let events = nodes[0].node.get_and_clear_pending_events();
3317 assert_eq!(events.len(), 3);
3319 Event::PaymentFailed { ref payment_hash, .. } => {
3320 assert!(failed_htlcs.insert(payment_hash.0));
3322 _ => panic!("Unexpected event"),
3325 Event::PaymentFailed { ref payment_hash, .. } => {
3326 assert!(failed_htlcs.insert(payment_hash.0));
3328 _ => panic!("Unexpected event"),
3331 Event::PaymentFailed { ref payment_hash, .. } => {
3332 assert!(failed_htlcs.insert(payment_hash.0));
3334 _ => panic!("Unexpected event"),
3337 _ => panic!("Unexpected event"),
3340 assert!(failed_htlcs.contains(&first_payment_hash.0));
3341 assert!(failed_htlcs.contains(&second_payment_hash.0));
3342 assert!(failed_htlcs.contains(&third_payment_hash.0));
3346 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3347 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3348 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3349 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3350 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3354 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3355 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3356 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3357 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3358 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3362 fn fail_backward_pending_htlc_upon_channel_failure() {
3363 let chanmon_cfgs = create_chanmon_cfgs(2);
3364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3367 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3368 let logger = test_utils::TestLogger::new();
3370 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3372 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3373 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3374 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();
3375 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3376 check_added_monitors!(nodes[0], 1);
3378 let payment_event = {
3379 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3380 assert_eq!(events.len(), 1);
3381 SendEvent::from_event(events.remove(0))
3383 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3384 assert_eq!(payment_event.msgs.len(), 1);
3387 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3388 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3390 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3391 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();
3392 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3393 check_added_monitors!(nodes[0], 0);
3395 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3398 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3400 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3402 let secp_ctx = Secp256k1::new();
3403 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3404 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3405 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3406 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();
3407 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3408 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3409 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3411 // Send a 0-msat update_add_htlc to fail the channel.
3412 let update_add_htlc = msgs::UpdateAddHTLC {
3418 onion_routing_packet,
3420 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3423 // Check that Alice fails backward the pending HTLC from the second payment.
3424 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3425 check_closed_broadcast!(nodes[0], true);
3426 check_added_monitors!(nodes[0], 1);
3430 fn test_htlc_ignore_latest_remote_commitment() {
3431 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3432 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3433 let chanmon_cfgs = create_chanmon_cfgs(2);
3434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3436 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3437 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3439 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3440 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3441 check_closed_broadcast!(nodes[0], false);
3442 check_added_monitors!(nodes[0], 1);
3444 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3445 assert_eq!(node_txn.len(), 2);
3447 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3448 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3449 check_closed_broadcast!(nodes[1], false);
3450 check_added_monitors!(nodes[1], 1);
3452 // Duplicate the connect_block call since this may happen due to other listeners
3453 // registering new transactions
3454 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3458 fn test_force_close_fail_back() {
3459 // Check which HTLCs are failed-backwards on channel force-closure
3460 let chanmon_cfgs = create_chanmon_cfgs(3);
3461 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3462 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3463 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3464 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3465 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3466 let logger = test_utils::TestLogger::new();
3468 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3470 let mut payment_event = {
3471 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3472 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();
3473 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3474 check_added_monitors!(nodes[0], 1);
3476 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3477 assert_eq!(events.len(), 1);
3478 SendEvent::from_event(events.remove(0))
3481 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3482 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3484 expect_pending_htlcs_forwardable!(nodes[1]);
3486 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3487 assert_eq!(events_2.len(), 1);
3488 payment_event = SendEvent::from_event(events_2.remove(0));
3489 assert_eq!(payment_event.msgs.len(), 1);
3491 check_added_monitors!(nodes[1], 1);
3492 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3493 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3494 check_added_monitors!(nodes[2], 1);
3495 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3497 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3498 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3499 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3501 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3502 check_closed_broadcast!(nodes[2], false);
3503 check_added_monitors!(nodes[2], 1);
3505 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3506 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3507 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3508 // back to nodes[1] upon timeout otherwise.
3509 assert_eq!(node_txn.len(), 1);
3514 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3515 txdata: vec![tx.clone()],
3517 connect_block(&nodes[1], &block, 1);
3519 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3520 check_closed_broadcast!(nodes[1], false);
3521 check_added_monitors!(nodes[1], 1);
3523 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3525 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3526 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3527 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3529 connect_block(&nodes[2], &block, 1);
3530 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3531 assert_eq!(node_txn.len(), 1);
3532 assert_eq!(node_txn[0].input.len(), 1);
3533 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3534 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3535 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3537 check_spends!(node_txn[0], tx);
3541 fn test_unconf_chan() {
3542 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3543 let chanmon_cfgs = create_chanmon_cfgs(2);
3544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3546 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3547 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3549 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3550 assert_eq!(channel_state.by_id.len(), 1);
3551 assert_eq!(channel_state.short_to_id.len(), 1);
3552 mem::drop(channel_state);
3554 let mut headers = Vec::new();
3555 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3556 headers.push(header.clone());
3558 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3559 headers.push(header.clone());
3561 let mut height = 99;
3562 while !headers.is_empty() {
3563 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3566 check_closed_broadcast!(nodes[0], false);
3567 check_added_monitors!(nodes[0], 1);
3568 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3569 assert_eq!(channel_state.by_id.len(), 0);
3570 assert_eq!(channel_state.short_to_id.len(), 0);
3574 fn test_simple_peer_disconnect() {
3575 // Test that we can reconnect when there are no lost messages
3576 let chanmon_cfgs = create_chanmon_cfgs(3);
3577 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3578 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3579 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3580 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3581 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3583 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3584 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3585 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3587 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3588 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3589 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3590 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3592 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3593 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3594 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3596 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3597 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3598 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3601 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3602 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3604 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3605 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3607 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3609 let events = nodes[0].node.get_and_clear_pending_events();
3610 assert_eq!(events.len(), 2);
3612 Event::PaymentSent { payment_preimage } => {
3613 assert_eq!(payment_preimage, payment_preimage_3);
3615 _ => panic!("Unexpected event"),
3618 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3619 assert_eq!(payment_hash, payment_hash_5);
3620 assert!(rejected_by_dest);
3622 _ => panic!("Unexpected event"),
3626 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3627 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3630 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3631 // Test that we can reconnect when in-flight HTLC updates get dropped
3632 let chanmon_cfgs = create_chanmon_cfgs(2);
3633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3635 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3636 if messages_delivered == 0 {
3637 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3638 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3640 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3643 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3645 let logger = test_utils::TestLogger::new();
3646 let payment_event = {
3647 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3648 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3649 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3650 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3651 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3652 check_added_monitors!(nodes[0], 1);
3654 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3655 assert_eq!(events.len(), 1);
3656 SendEvent::from_event(events.remove(0))
3658 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3660 if messages_delivered < 2 {
3661 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3663 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3664 if messages_delivered >= 3 {
3665 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3666 check_added_monitors!(nodes[1], 1);
3667 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3669 if messages_delivered >= 4 {
3670 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3671 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3672 check_added_monitors!(nodes[0], 1);
3674 if messages_delivered >= 5 {
3675 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3676 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3677 // No commitment_signed so get_event_msg's assert(len == 1) passes
3678 check_added_monitors!(nodes[0], 1);
3680 if messages_delivered >= 6 {
3681 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3682 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3683 check_added_monitors!(nodes[1], 1);
3690 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3691 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3692 if messages_delivered < 3 {
3693 // Even if the funding_locked messages get exchanged, as long as nothing further was
3694 // received on either side, both sides will need to resend them.
3695 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3696 } else if messages_delivered == 3 {
3697 // nodes[0] still wants its RAA + commitment_signed
3698 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3699 } else if messages_delivered == 4 {
3700 // nodes[0] still wants its commitment_signed
3701 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3702 } else if messages_delivered == 5 {
3703 // nodes[1] still wants its final RAA
3704 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3705 } else if messages_delivered == 6 {
3706 // Everything was delivered...
3707 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3710 let events_1 = nodes[1].node.get_and_clear_pending_events();
3711 assert_eq!(events_1.len(), 1);
3713 Event::PendingHTLCsForwardable { .. } => { },
3714 _ => panic!("Unexpected event"),
3717 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3718 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3719 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3721 nodes[1].node.process_pending_htlc_forwards();
3723 let events_2 = nodes[1].node.get_and_clear_pending_events();
3724 assert_eq!(events_2.len(), 1);
3726 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3727 assert_eq!(payment_hash_1, *payment_hash);
3728 assert_eq!(*payment_secret, None);
3729 assert_eq!(amt, 1000000);
3731 _ => panic!("Unexpected event"),
3734 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3735 check_added_monitors!(nodes[1], 1);
3737 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3738 assert_eq!(events_3.len(), 1);
3739 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3740 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3741 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3742 assert!(updates.update_add_htlcs.is_empty());
3743 assert!(updates.update_fail_htlcs.is_empty());
3744 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3745 assert!(updates.update_fail_malformed_htlcs.is_empty());
3746 assert!(updates.update_fee.is_none());
3747 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3749 _ => panic!("Unexpected event"),
3752 if messages_delivered >= 1 {
3753 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3755 let events_4 = nodes[0].node.get_and_clear_pending_events();
3756 assert_eq!(events_4.len(), 1);
3758 Event::PaymentSent { ref payment_preimage } => {
3759 assert_eq!(payment_preimage_1, *payment_preimage);
3761 _ => panic!("Unexpected event"),
3764 if messages_delivered >= 2 {
3765 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3766 check_added_monitors!(nodes[0], 1);
3767 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3769 if messages_delivered >= 3 {
3770 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3771 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3772 check_added_monitors!(nodes[1], 1);
3774 if messages_delivered >= 4 {
3775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3776 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3777 // No commitment_signed so get_event_msg's assert(len == 1) passes
3778 check_added_monitors!(nodes[1], 1);
3780 if messages_delivered >= 5 {
3781 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3782 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3783 check_added_monitors!(nodes[0], 1);
3790 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3791 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3792 if messages_delivered < 2 {
3793 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3794 //TODO: Deduplicate PaymentSent events, then enable this if:
3795 //if messages_delivered < 1 {
3796 let events_4 = nodes[0].node.get_and_clear_pending_events();
3797 assert_eq!(events_4.len(), 1);
3799 Event::PaymentSent { ref payment_preimage } => {
3800 assert_eq!(payment_preimage_1, *payment_preimage);
3802 _ => panic!("Unexpected event"),
3805 } else if messages_delivered == 2 {
3806 // nodes[0] still wants its RAA + commitment_signed
3807 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3808 } else if messages_delivered == 3 {
3809 // nodes[0] still wants its commitment_signed
3810 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3811 } else if messages_delivered == 4 {
3812 // nodes[1] still wants its final RAA
3813 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3814 } else if messages_delivered == 5 {
3815 // Everything was delivered...
3816 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3819 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3820 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3821 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3823 // Channel should still work fine...
3824 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3825 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3826 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3827 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3828 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3829 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3833 fn test_drop_messages_peer_disconnect_a() {
3834 do_test_drop_messages_peer_disconnect(0);
3835 do_test_drop_messages_peer_disconnect(1);
3836 do_test_drop_messages_peer_disconnect(2);
3837 do_test_drop_messages_peer_disconnect(3);
3841 fn test_drop_messages_peer_disconnect_b() {
3842 do_test_drop_messages_peer_disconnect(4);
3843 do_test_drop_messages_peer_disconnect(5);
3844 do_test_drop_messages_peer_disconnect(6);
3848 fn test_funding_peer_disconnect() {
3849 // Test that we can lock in our funding tx while disconnected
3850 let chanmon_cfgs = create_chanmon_cfgs(2);
3851 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3852 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3853 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3854 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3856 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3857 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3859 confirm_transaction(&nodes[0], &tx);
3860 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3861 assert_eq!(events_1.len(), 1);
3863 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3864 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3866 _ => panic!("Unexpected event"),
3869 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3871 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3872 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3874 confirm_transaction(&nodes[1], &tx);
3875 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3876 assert_eq!(events_2.len(), 2);
3877 let funding_locked = match events_2[0] {
3878 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3879 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3882 _ => panic!("Unexpected event"),
3884 let bs_announcement_sigs = match events_2[1] {
3885 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3886 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3889 _ => panic!("Unexpected event"),
3892 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3894 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3895 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3896 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3897 assert_eq!(events_3.len(), 2);
3898 let as_announcement_sigs = match events_3[0] {
3899 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3900 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3903 _ => panic!("Unexpected event"),
3905 let (as_announcement, as_update) = match events_3[1] {
3906 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3907 (msg.clone(), update_msg.clone())
3909 _ => panic!("Unexpected event"),
3912 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3913 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3914 assert_eq!(events_4.len(), 1);
3915 let (_, bs_update) = match events_4[0] {
3916 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3917 (msg.clone(), update_msg.clone())
3919 _ => panic!("Unexpected event"),
3922 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3923 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3924 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3926 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3927 let logger = test_utils::TestLogger::new();
3928 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();
3929 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3930 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3934 fn test_drop_messages_peer_disconnect_dual_htlc() {
3935 // Test that we can handle reconnecting when both sides of a channel have pending
3936 // commitment_updates when we disconnect.
3937 let chanmon_cfgs = create_chanmon_cfgs(2);
3938 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3939 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3940 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3941 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3942 let logger = test_utils::TestLogger::new();
3944 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3946 // Now try to send a second payment which will fail to send
3947 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3948 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3949 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();
3950 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3951 check_added_monitors!(nodes[0], 1);
3953 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3954 assert_eq!(events_1.len(), 1);
3956 MessageSendEvent::UpdateHTLCs { .. } => {},
3957 _ => panic!("Unexpected event"),
3960 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3961 check_added_monitors!(nodes[1], 1);
3963 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3964 assert_eq!(events_2.len(), 1);
3966 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 } } => {
3967 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3968 assert!(update_add_htlcs.is_empty());
3969 assert_eq!(update_fulfill_htlcs.len(), 1);
3970 assert!(update_fail_htlcs.is_empty());
3971 assert!(update_fail_malformed_htlcs.is_empty());
3972 assert!(update_fee.is_none());
3974 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3975 let events_3 = nodes[0].node.get_and_clear_pending_events();
3976 assert_eq!(events_3.len(), 1);
3978 Event::PaymentSent { ref payment_preimage } => {
3979 assert_eq!(*payment_preimage, payment_preimage_1);
3981 _ => panic!("Unexpected event"),
3984 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3985 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3986 // No commitment_signed so get_event_msg's assert(len == 1) passes
3987 check_added_monitors!(nodes[0], 1);
3989 _ => panic!("Unexpected event"),
3992 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3993 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3995 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3996 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3997 assert_eq!(reestablish_1.len(), 1);
3998 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3999 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4000 assert_eq!(reestablish_2.len(), 1);
4002 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4003 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4004 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4005 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4007 assert!(as_resp.0.is_none());
4008 assert!(bs_resp.0.is_none());
4010 assert!(bs_resp.1.is_none());
4011 assert!(bs_resp.2.is_none());
4013 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4015 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4016 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4017 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4018 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4019 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4020 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4021 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4022 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4023 // No commitment_signed so get_event_msg's assert(len == 1) passes
4024 check_added_monitors!(nodes[1], 1);
4026 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4027 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4028 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4029 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4030 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4031 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4032 assert!(bs_second_commitment_signed.update_fee.is_none());
4033 check_added_monitors!(nodes[1], 1);
4035 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4036 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4037 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4038 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4039 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4040 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4041 assert!(as_commitment_signed.update_fee.is_none());
4042 check_added_monitors!(nodes[0], 1);
4044 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4045 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4046 // No commitment_signed so get_event_msg's assert(len == 1) passes
4047 check_added_monitors!(nodes[0], 1);
4049 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4050 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4051 // No commitment_signed so get_event_msg's assert(len == 1) passes
4052 check_added_monitors!(nodes[1], 1);
4054 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4055 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4056 check_added_monitors!(nodes[1], 1);
4058 expect_pending_htlcs_forwardable!(nodes[1]);
4060 let events_5 = nodes[1].node.get_and_clear_pending_events();
4061 assert_eq!(events_5.len(), 1);
4063 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4064 assert_eq!(payment_hash_2, *payment_hash);
4065 assert_eq!(*payment_secret, None);
4067 _ => panic!("Unexpected event"),
4070 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4071 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4072 check_added_monitors!(nodes[0], 1);
4074 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4077 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4078 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4079 // to avoid our counterparty failing the channel.
4080 let chanmon_cfgs = create_chanmon_cfgs(2);
4081 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4082 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4083 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4085 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4086 let logger = test_utils::TestLogger::new();
4088 let our_payment_hash = if send_partial_mpp {
4089 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4090 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();
4091 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4092 let payment_secret = PaymentSecret([0xdb; 32]);
4093 // Use the utility function send_payment_along_path to send the payment with MPP data which
4094 // indicates there are more HTLCs coming.
4095 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4096 check_added_monitors!(nodes[0], 1);
4097 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4098 assert_eq!(events.len(), 1);
4099 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4100 // hop should *not* yet generate any PaymentReceived event(s).
4101 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4104 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4107 let mut block = Block {
4108 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4111 connect_block(&nodes[0], &block, 101);
4112 connect_block(&nodes[1], &block, 101);
4113 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4114 block.header.prev_blockhash = block.block_hash();
4115 connect_block(&nodes[0], &block, i);
4116 connect_block(&nodes[1], &block, i);
4119 expect_pending_htlcs_forwardable!(nodes[1]);
4121 check_added_monitors!(nodes[1], 1);
4122 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4123 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4124 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4125 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4126 assert!(htlc_timeout_updates.update_fee.is_none());
4128 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4129 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4130 // 100_000 msat as u64, followed by a height of 123 as u32
4131 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4132 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4133 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4137 fn test_htlc_timeout() {
4138 do_test_htlc_timeout(true);
4139 do_test_htlc_timeout(false);
4142 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4143 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4144 let chanmon_cfgs = create_chanmon_cfgs(3);
4145 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4146 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4147 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4148 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4149 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4150 let logger = test_utils::TestLogger::new();
4152 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4153 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4155 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4156 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();
4157 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4159 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4160 check_added_monitors!(nodes[1], 1);
4162 // Now attempt to route a second payment, which should be placed in the holding cell
4163 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4165 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4166 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();
4167 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4168 check_added_monitors!(nodes[0], 1);
4169 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4170 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4171 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4172 expect_pending_htlcs_forwardable!(nodes[1]);
4173 check_added_monitors!(nodes[1], 0);
4175 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4176 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();
4177 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4178 check_added_monitors!(nodes[1], 0);
4181 let mut block = Block {
4182 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4185 connect_block(&nodes[1], &block, 101);
4186 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4187 block.header.prev_blockhash = block.block_hash();
4188 connect_block(&nodes[1], &block, i);
4191 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4192 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4194 block.header.prev_blockhash = block.block_hash();
4195 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4198 expect_pending_htlcs_forwardable!(nodes[1]);
4199 check_added_monitors!(nodes[1], 1);
4200 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4201 assert_eq!(fail_commit.len(), 1);
4202 match fail_commit[0] {
4203 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4204 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4205 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4207 _ => unreachable!(),
4209 expect_payment_failed!(nodes[0], second_payment_hash, false);
4210 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4212 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4213 _ => panic!("Unexpected event"),
4216 panic!("Unexpected event");
4219 expect_payment_failed!(nodes[1], second_payment_hash, true);
4224 fn test_holding_cell_htlc_add_timeouts() {
4225 do_test_holding_cell_htlc_add_timeouts(false);
4226 do_test_holding_cell_htlc_add_timeouts(true);
4230 fn test_invalid_channel_announcement() {
4231 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4232 let secp_ctx = Secp256k1::new();
4233 let chanmon_cfgs = create_chanmon_cfgs(2);
4234 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4235 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4236 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4238 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4240 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4241 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4242 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4243 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4245 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 } );
4247 let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4248 let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4250 let as_network_key = nodes[0].node.get_our_node_id();
4251 let bs_network_key = nodes[1].node.get_our_node_id();
4253 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4255 let mut chan_announcement;
4257 macro_rules! dummy_unsigned_msg {
4259 msgs::UnsignedChannelAnnouncement {
4260 features: ChannelFeatures::known(),
4261 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4262 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4263 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4264 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4265 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4266 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4267 excess_data: Vec::new(),
4272 macro_rules! sign_msg {
4273 ($unsigned_msg: expr) => {
4274 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4275 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4276 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4277 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4278 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4279 chan_announcement = msgs::ChannelAnnouncement {
4280 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4281 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4282 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4283 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4284 contents: $unsigned_msg
4289 let unsigned_msg = dummy_unsigned_msg!();
4290 sign_msg!(unsigned_msg);
4291 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4292 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 } );
4294 // Configured with Network::Testnet
4295 let mut unsigned_msg = dummy_unsigned_msg!();
4296 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4297 sign_msg!(unsigned_msg);
4298 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4300 let mut unsigned_msg = dummy_unsigned_msg!();
4301 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4302 sign_msg!(unsigned_msg);
4303 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4307 fn test_no_txn_manager_serialize_deserialize() {
4308 let chanmon_cfgs = create_chanmon_cfgs(2);
4309 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4310 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4311 let logger: test_utils::TestLogger;
4312 let fee_estimator: test_utils::TestFeeEstimator;
4313 let new_chain_monitor: test_utils::TestChainMonitor;
4314 let keys_manager: test_utils::TestKeysInterface;
4315 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4316 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4318 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4320 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4322 let nodes_0_serialized = nodes[0].node.encode();
4323 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4324 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4326 logger = test_utils::TestLogger::new();
4327 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4328 new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4329 nodes[0].chain_monitor = &new_chain_monitor;
4330 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4331 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4332 assert!(chan_0_monitor_read.is_empty());
4334 let mut nodes_0_read = &nodes_0_serialized[..];
4335 let config = UserConfig::default();
4336 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4337 let (_, nodes_0_deserialized_tmp) = {
4338 let mut channel_monitors = HashMap::new();
4339 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4340 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4341 default_config: config,
4342 keys_manager: &keys_manager,
4343 fee_estimator: &fee_estimator,
4344 chain_monitor: nodes[0].chain_monitor,
4345 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4350 nodes_0_deserialized = nodes_0_deserialized_tmp;
4351 assert!(nodes_0_read.is_empty());
4353 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4354 nodes[0].node = &nodes_0_deserialized;
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_chain_monitor: test_utils::TestChainMonitor;
4388 let keys_manager: test_utils::TestKeysInterface;
4389 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &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.chain_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.chain_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].chain_monitor.chain_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_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4436 nodes[0].chain_monitor = &new_chain_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::TestChainMonitor, &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 chain_monitor: nodes[0].chain_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].chain_monitor.watch_channel(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 assert_eq!(nodes[0].node.list_channels().len(), 1);
4478 check_added_monitors!(nodes[0], 1);
4480 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4481 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4482 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4483 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4485 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4486 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4487 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4488 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4490 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4491 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4492 for node in nodes.iter() {
4493 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4494 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4495 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4498 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4502 fn test_simple_manager_serialize_deserialize() {
4503 let chanmon_cfgs = create_chanmon_cfgs(2);
4504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4506 let logger: test_utils::TestLogger;
4507 let fee_estimator: test_utils::TestFeeEstimator;
4508 let new_chain_monitor: test_utils::TestChainMonitor;
4509 let keys_manager: test_utils::TestKeysInterface;
4510 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4511 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4512 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4514 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4515 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4517 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4519 let nodes_0_serialized = nodes[0].node.encode();
4520 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4521 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4523 logger = test_utils::TestLogger::new();
4524 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4525 new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4526 nodes[0].chain_monitor = &new_chain_monitor;
4527 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4528 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4529 assert!(chan_0_monitor_read.is_empty());
4531 let mut nodes_0_read = &nodes_0_serialized[..];
4532 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4533 let (_, nodes_0_deserialized_tmp) = {
4534 let mut channel_monitors = HashMap::new();
4535 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4536 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4537 default_config: UserConfig::default(),
4538 keys_manager: &keys_manager,
4539 fee_estimator: &fee_estimator,
4540 chain_monitor: nodes[0].chain_monitor,
4541 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4546 nodes_0_deserialized = nodes_0_deserialized_tmp;
4547 assert!(nodes_0_read.is_empty());
4549 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4550 nodes[0].node = &nodes_0_deserialized;
4551 check_added_monitors!(nodes[0], 1);
4553 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4555 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4556 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4560 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4561 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4562 let chanmon_cfgs = create_chanmon_cfgs(4);
4563 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4564 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4565 let logger: test_utils::TestLogger;
4566 let fee_estimator: test_utils::TestFeeEstimator;
4567 let new_chain_monitor: test_utils::TestChainMonitor;
4568 let keys_manager: test_utils::TestKeysInterface;
4569 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4570 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4571 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4572 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4573 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4575 let mut node_0_stale_monitors_serialized = Vec::new();
4576 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4577 let mut writer = test_utils::TestVecWriter(Vec::new());
4578 monitor.1.write_for_disk(&mut writer).unwrap();
4579 node_0_stale_monitors_serialized.push(writer.0);
4582 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4584 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4585 let nodes_0_serialized = nodes[0].node.encode();
4587 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4588 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4589 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4590 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4592 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4594 let mut node_0_monitors_serialized = Vec::new();
4595 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4596 let mut writer = test_utils::TestVecWriter(Vec::new());
4597 monitor.1.write_for_disk(&mut writer).unwrap();
4598 node_0_monitors_serialized.push(writer.0);
4601 logger = test_utils::TestLogger::new();
4602 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4603 new_chain_monitor = test_utils::TestChainMonitor::new(nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4604 nodes[0].chain_monitor = &new_chain_monitor;
4606 let mut node_0_stale_monitors = Vec::new();
4607 for serialized in node_0_stale_monitors_serialized.iter() {
4608 let mut read = &serialized[..];
4609 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4610 assert!(read.is_empty());
4611 node_0_stale_monitors.push(monitor);
4614 let mut node_0_monitors = Vec::new();
4615 for serialized in node_0_monitors_serialized.iter() {
4616 let mut read = &serialized[..];
4617 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4618 assert!(read.is_empty());
4619 node_0_monitors.push(monitor);
4622 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4624 let mut nodes_0_read = &nodes_0_serialized[..];
4625 if let Err(msgs::DecodeError::InvalidValue) =
4626 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4627 default_config: UserConfig::default(),
4628 keys_manager: &keys_manager,
4629 fee_estimator: &fee_estimator,
4630 chain_monitor: nodes[0].chain_monitor,
4631 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4633 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4635 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4638 let mut nodes_0_read = &nodes_0_serialized[..];
4639 let (_, nodes_0_deserialized_tmp) =
4640 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4641 default_config: UserConfig::default(),
4642 keys_manager: &keys_manager,
4643 fee_estimator: &fee_estimator,
4644 chain_monitor: nodes[0].chain_monitor,
4645 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4647 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4649 nodes_0_deserialized = nodes_0_deserialized_tmp;
4650 assert!(nodes_0_read.is_empty());
4652 { // Channel close should result in a commitment tx and an HTLC tx
4653 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4654 assert_eq!(txn.len(), 2);
4655 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4656 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4659 for monitor in node_0_monitors.drain(..) {
4660 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4661 check_added_monitors!(nodes[0], 1);
4663 nodes[0].node = &nodes_0_deserialized;
4665 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4666 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4667 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4668 //... and we can even still claim the payment!
4669 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4671 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4672 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4673 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4674 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4675 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4676 assert_eq!(msg_events.len(), 1);
4677 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4679 &ErrorAction::SendErrorMessage { ref msg } => {
4680 assert_eq!(msg.channel_id, channel_id);
4682 _ => panic!("Unexpected event!"),
4687 macro_rules! check_spendable_outputs {
4688 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4690 let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4691 let mut txn = Vec::new();
4692 for event in events {
4694 Event::SpendableOutputs { ref outputs } => {
4695 for outp in outputs {
4697 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4699 previous_output: outpoint.into_bitcoin_outpoint(),
4700 script_sig: Script::new(),
4702 witness: Vec::new(),
4705 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4706 value: output.value,
4708 let mut spend_tx = Transaction {
4714 let secp_ctx = Secp256k1::new();
4715 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4716 let remotepubkey = keys.pubkeys().payment_point;
4717 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4718 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4719 let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4720 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4721 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4722 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4725 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4727 previous_output: outpoint.into_bitcoin_outpoint(),
4728 script_sig: Script::new(),
4729 sequence: *to_self_delay as u32,
4730 witness: Vec::new(),
4733 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4734 value: output.value,
4736 let mut spend_tx = Transaction {
4742 let secp_ctx = Secp256k1::new();
4743 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4744 if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4746 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4747 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4748 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4749 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4750 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4751 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4752 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4753 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4757 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4758 let secp_ctx = Secp256k1::new();
4760 previous_output: outpoint.into_bitcoin_outpoint(),
4761 script_sig: Script::new(),
4763 witness: Vec::new(),
4766 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4767 value: output.value,
4769 let mut spend_tx = Transaction {
4773 output: vec![outp.clone()],
4776 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4778 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4780 Err(_) => panic!("Your RNG is busted"),
4783 Err(_) => panic!("Your rng is busted"),
4786 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4787 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4788 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4789 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4790 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4791 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4792 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4798 _ => panic!("Unexpected event"),
4807 fn test_claim_sizeable_push_msat() {
4808 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4809 let chanmon_cfgs = create_chanmon_cfgs(2);
4810 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4811 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4812 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4814 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4815 nodes[1].node.force_close_channel(&chan.2);
4816 check_closed_broadcast!(nodes[1], false);
4817 check_added_monitors!(nodes[1], 1);
4818 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4819 assert_eq!(node_txn.len(), 1);
4820 check_spends!(node_txn[0], chan.3);
4821 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
4823 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4824 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4825 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4827 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4828 assert_eq!(spend_txn.len(), 1);
4829 check_spends!(spend_txn[0], node_txn[0]);
4833 fn test_claim_on_remote_sizeable_push_msat() {
4834 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4835 // to_remote output is encumbered by a P2WPKH
4836 let chanmon_cfgs = create_chanmon_cfgs(2);
4837 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4838 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4839 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4841 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4842 nodes[0].node.force_close_channel(&chan.2);
4843 check_closed_broadcast!(nodes[0], false);
4844 check_added_monitors!(nodes[0], 1);
4846 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4847 assert_eq!(node_txn.len(), 1);
4848 check_spends!(node_txn[0], chan.3);
4849 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
4851 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4852 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4853 check_closed_broadcast!(nodes[1], false);
4854 check_added_monitors!(nodes[1], 1);
4855 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4857 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4858 assert_eq!(spend_txn.len(), 2);
4859 assert_eq!(spend_txn[0], spend_txn[1]);
4860 check_spends!(spend_txn[0], node_txn[0]);
4864 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4865 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4866 // to_remote output is encumbered by a P2WPKH
4868 let chanmon_cfgs = create_chanmon_cfgs(2);
4869 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4870 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4871 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4873 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4874 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4875 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4876 assert_eq!(revoked_local_txn[0].input.len(), 1);
4877 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4879 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4880 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4881 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4882 check_closed_broadcast!(nodes[1], false);
4883 check_added_monitors!(nodes[1], 1);
4885 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4886 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4887 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4888 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4890 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4891 assert_eq!(spend_txn.len(), 3);
4892 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4893 check_spends!(spend_txn[0], revoked_local_txn[0]);
4894 check_spends!(spend_txn[2], node_txn[0]);
4898 fn test_static_spendable_outputs_preimage_tx() {
4899 let chanmon_cfgs = create_chanmon_cfgs(2);
4900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4904 // Create some initial channels
4905 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4907 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4909 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4910 assert_eq!(commitment_tx[0].input.len(), 1);
4911 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4913 // Settle A's commitment tx on B's chain
4914 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4915 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4916 check_added_monitors!(nodes[1], 1);
4917 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4918 check_added_monitors!(nodes[1], 1);
4919 let events = nodes[1].node.get_and_clear_pending_msg_events();
4921 MessageSendEvent::UpdateHTLCs { .. } => {},
4922 _ => panic!("Unexpected event"),
4925 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4926 _ => panic!("Unexepected event"),
4929 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4930 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4931 assert_eq!(node_txn.len(), 3);
4932 check_spends!(node_txn[0], commitment_tx[0]);
4933 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4934 check_spends!(node_txn[1], chan_1.3);
4935 check_spends!(node_txn[2], node_txn[1]);
4937 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4938 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4939 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4941 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4942 assert_eq!(spend_txn.len(), 1);
4943 check_spends!(spend_txn[0], node_txn[0]);
4947 fn test_static_spendable_outputs_timeout_tx() {
4948 let chanmon_cfgs = create_chanmon_cfgs(2);
4949 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4950 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4951 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4953 // Create some initial channels
4954 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4956 // Rebalance the network a bit by relaying one payment through all the channels ...
4957 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4959 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4961 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4962 assert_eq!(commitment_tx[0].input.len(), 1);
4963 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4965 // Settle A's commitment tx on B' chain
4966 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4967 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4968 check_added_monitors!(nodes[1], 1);
4969 let events = nodes[1].node.get_and_clear_pending_msg_events();
4971 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4972 _ => panic!("Unexpected event"),
4975 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4976 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4977 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4978 check_spends!(node_txn[0], commitment_tx[0].clone());
4979 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4980 check_spends!(node_txn[1], chan_1.3.clone());
4981 check_spends!(node_txn[2], node_txn[1]);
4983 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4984 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4985 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4986 expect_payment_failed!(nodes[1], our_payment_hash, true);
4988 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4989 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4990 check_spends!(spend_txn[2], node_txn[0].clone());
4994 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4995 let chanmon_cfgs = create_chanmon_cfgs(2);
4996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4998 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5000 // Create some initial channels
5001 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5003 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5004 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5005 assert_eq!(revoked_local_txn[0].input.len(), 1);
5006 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5008 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5010 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5011 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
5012 check_closed_broadcast!(nodes[1], false);
5013 check_added_monitors!(nodes[1], 1);
5015 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5016 assert_eq!(node_txn.len(), 2);
5017 assert_eq!(node_txn[0].input.len(), 2);
5018 check_spends!(node_txn[0], revoked_local_txn[0]);
5020 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5021 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
5022 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5024 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5025 assert_eq!(spend_txn.len(), 1);
5026 check_spends!(spend_txn[0], node_txn[0]);
5030 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5031 let chanmon_cfgs = create_chanmon_cfgs(2);
5032 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5033 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5034 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5036 // Create some initial channels
5037 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5039 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5040 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5041 assert_eq!(revoked_local_txn[0].input.len(), 1);
5042 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5044 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5046 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5047 // A will generate HTLC-Timeout from revoked commitment tx
5048 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5049 check_closed_broadcast!(nodes[0], false);
5050 check_added_monitors!(nodes[0], 1);
5052 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5053 assert_eq!(revoked_htlc_txn.len(), 2);
5054 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5055 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5056 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5057 check_spends!(revoked_htlc_txn[1], chan_1.3);
5059 // B will generate justice tx from A's revoked commitment/HTLC tx
5060 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5061 check_closed_broadcast!(nodes[1], false);
5062 check_added_monitors!(nodes[1], 1);
5064 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5065 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5066 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5067 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5068 // transactions next...
5069 assert_eq!(node_txn[0].input.len(), 3);
5070 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5072 assert_eq!(node_txn[1].input.len(), 2);
5073 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5074 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5075 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5077 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5078 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5081 assert_eq!(node_txn[2].input.len(), 1);
5082 check_spends!(node_txn[2], chan_1.3);
5084 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5085 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5086 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5088 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5089 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5090 assert_eq!(spend_txn.len(), 1);
5091 assert_eq!(spend_txn[0].input.len(), 1);
5092 check_spends!(spend_txn[0], node_txn[1]);
5096 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5097 let chanmon_cfgs = create_chanmon_cfgs(2);
5098 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5099 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5100 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5102 // Create some initial channels
5103 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5105 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5106 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5107 assert_eq!(revoked_local_txn[0].input.len(), 1);
5108 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5110 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5111 assert_eq!(revoked_local_txn[0].output.len(), 2);
5113 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5115 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5116 // B will generate HTLC-Success from revoked commitment tx
5117 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5118 check_closed_broadcast!(nodes[1], false);
5119 check_added_monitors!(nodes[1], 1);
5120 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5122 assert_eq!(revoked_htlc_txn.len(), 2);
5123 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5124 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5125 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5127 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5128 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5129 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5131 // A will generate justice tx from B's revoked commitment/HTLC tx
5132 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5133 check_closed_broadcast!(nodes[0], false);
5134 check_added_monitors!(nodes[0], 1);
5136 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5137 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5139 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5140 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5141 // transactions next...
5142 assert_eq!(node_txn[0].input.len(), 2);
5143 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5144 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5145 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5147 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5148 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5151 assert_eq!(node_txn[1].input.len(), 1);
5152 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5154 check_spends!(node_txn[2], chan_1.3);
5156 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5157 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5158 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5160 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5161 // didn't try to generate any new transactions.
5163 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5164 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5165 assert_eq!(spend_txn.len(), 3); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5166 assert_eq!(spend_txn[0], spend_txn[1]);
5167 assert_eq!(spend_txn[0].input.len(), 1);
5168 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5169 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5170 check_spends!(spend_txn[2], node_txn[1]); // spending justice tx output on the htlc success tx
5174 fn test_onchain_to_onchain_claim() {
5175 // Test that in case of channel closure, we detect the state of output and claim HTLC
5176 // on downstream peer's remote commitment tx.
5177 // First, have C claim an HTLC against its own latest commitment transaction.
5178 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5180 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5183 let chanmon_cfgs = create_chanmon_cfgs(3);
5184 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5185 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5186 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5188 // Create some initial channels
5189 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5190 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5192 // Rebalance the network a bit by relaying one payment through all the channels ...
5193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5196 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5197 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5198 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5199 check_spends!(commitment_tx[0], chan_2.3);
5200 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5201 check_added_monitors!(nodes[2], 1);
5202 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5203 assert!(updates.update_add_htlcs.is_empty());
5204 assert!(updates.update_fail_htlcs.is_empty());
5205 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5206 assert!(updates.update_fail_malformed_htlcs.is_empty());
5208 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5209 check_closed_broadcast!(nodes[2], false);
5210 check_added_monitors!(nodes[2], 1);
5212 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5213 assert_eq!(c_txn.len(), 3);
5214 assert_eq!(c_txn[0], c_txn[2]);
5215 assert_eq!(commitment_tx[0], c_txn[1]);
5216 check_spends!(c_txn[1], chan_2.3);
5217 check_spends!(c_txn[2], c_txn[1]);
5218 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5219 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5220 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5221 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5223 // 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
5224 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5226 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5227 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5228 assert_eq!(b_txn.len(), 3);
5229 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5230 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5231 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5232 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5233 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5234 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5235 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5236 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5237 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5240 check_added_monitors!(nodes[1], 1);
5241 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5242 check_added_monitors!(nodes[1], 1);
5243 match msg_events[0] {
5244 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5245 _ => panic!("Unexpected event"),
5247 match msg_events[1] {
5248 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, .. } } => {
5249 assert!(update_add_htlcs.is_empty());
5250 assert!(update_fail_htlcs.is_empty());
5251 assert_eq!(update_fulfill_htlcs.len(), 1);
5252 assert!(update_fail_malformed_htlcs.is_empty());
5253 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5255 _ => panic!("Unexpected event"),
5257 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5258 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5259 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5260 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5261 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5262 assert_eq!(b_txn.len(), 3);
5263 check_spends!(b_txn[1], chan_1.3);
5264 check_spends!(b_txn[2], b_txn[1]);
5265 check_spends!(b_txn[0], commitment_tx[0]);
5266 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5267 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5268 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5270 check_closed_broadcast!(nodes[1], false);
5271 check_added_monitors!(nodes[1], 1);
5275 fn test_duplicate_payment_hash_one_failure_one_success() {
5276 // Topology : A --> B --> C
5277 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5278 let chanmon_cfgs = create_chanmon_cfgs(3);
5279 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5280 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5281 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5283 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5284 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5286 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5287 *nodes[0].network_payment_count.borrow_mut() -= 1;
5288 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5290 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5291 assert_eq!(commitment_txn[0].input.len(), 1);
5292 check_spends!(commitment_txn[0], chan_2.3);
5294 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5295 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5296 check_closed_broadcast!(nodes[1], false);
5297 check_added_monitors!(nodes[1], 1);
5299 let htlc_timeout_tx;
5300 { // Extract one of the two HTLC-Timeout transaction
5301 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5302 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5303 assert_eq!(node_txn.len(), 5);
5304 check_spends!(node_txn[0], commitment_txn[0]);
5305 assert_eq!(node_txn[0].input.len(), 1);
5306 check_spends!(node_txn[1], commitment_txn[0]);
5307 assert_eq!(node_txn[1].input.len(), 1);
5308 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5309 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5310 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5311 check_spends!(node_txn[2], chan_2.3);
5312 check_spends!(node_txn[3], node_txn[2]);
5313 check_spends!(node_txn[4], node_txn[2]);
5314 htlc_timeout_tx = node_txn[1].clone();
5317 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5318 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5319 check_added_monitors!(nodes[2], 3);
5320 let events = nodes[2].node.get_and_clear_pending_msg_events();
5322 MessageSendEvent::UpdateHTLCs { .. } => {},
5323 _ => panic!("Unexpected event"),
5326 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5327 _ => panic!("Unexepected event"),
5329 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5330 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)
5331 check_spends!(htlc_success_txn[2], chan_2.3);
5332 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5333 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5334 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5335 assert_eq!(htlc_success_txn[0].input.len(), 1);
5336 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5337 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5338 assert_eq!(htlc_success_txn[1].input.len(), 1);
5339 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5340 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5341 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5342 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5344 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5345 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5346 expect_pending_htlcs_forwardable!(nodes[1]);
5347 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5348 assert!(htlc_updates.update_add_htlcs.is_empty());
5349 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5350 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5351 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5352 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5353 check_added_monitors!(nodes[1], 1);
5355 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5356 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5358 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5359 let events = nodes[0].node.get_and_clear_pending_msg_events();
5360 assert_eq!(events.len(), 1);
5362 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5364 _ => { panic!("Unexpected event"); }
5367 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5369 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5370 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5371 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5372 assert!(updates.update_add_htlcs.is_empty());
5373 assert!(updates.update_fail_htlcs.is_empty());
5374 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5375 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5376 assert!(updates.update_fail_malformed_htlcs.is_empty());
5377 check_added_monitors!(nodes[1], 1);
5379 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5380 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5382 let events = nodes[0].node.get_and_clear_pending_events();
5384 Event::PaymentSent { ref payment_preimage } => {
5385 assert_eq!(*payment_preimage, our_payment_preimage);
5387 _ => panic!("Unexpected event"),
5392 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5393 let chanmon_cfgs = create_chanmon_cfgs(2);
5394 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5395 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5396 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5398 // Create some initial channels
5399 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5401 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5402 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5403 assert_eq!(local_txn[0].input.len(), 1);
5404 check_spends!(local_txn[0], chan_1.3);
5406 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5407 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5408 check_added_monitors!(nodes[1], 1);
5409 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5410 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5411 check_added_monitors!(nodes[1], 1);
5412 let events = nodes[1].node.get_and_clear_pending_msg_events();
5414 MessageSendEvent::UpdateHTLCs { .. } => {},
5415 _ => panic!("Unexpected event"),
5418 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5419 _ => panic!("Unexepected event"),
5422 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5423 assert_eq!(node_txn[0].input.len(), 1);
5424 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5425 check_spends!(node_txn[0], local_txn[0]);
5426 vec![node_txn[0].clone(), node_txn[2].clone()]
5429 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5430 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5431 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5433 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5434 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5435 assert_eq!(spend_txn.len(), 2);
5436 check_spends!(spend_txn[0], node_txn[0]);
5437 check_spends!(spend_txn[1], node_txn[1]);
5440 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5441 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5442 // unrevoked commitment transaction.
5443 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5444 // a remote RAA before they could be failed backwards (and combinations thereof).
5445 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5446 // use the same payment hashes.
5447 // Thus, we use a six-node network:
5452 // And test where C fails back to A/B when D announces its latest commitment transaction
5453 let chanmon_cfgs = create_chanmon_cfgs(6);
5454 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5455 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5456 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5457 let logger = test_utils::TestLogger::new();
5459 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5460 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5461 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5462 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5463 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5465 // Rebalance and check output sanity...
5466 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5467 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5468 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5470 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5472 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
5474 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
5475 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5476 let our_node_id = &nodes[1].node.get_our_node_id();
5477 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();
5479 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
5481 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
5483 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5485 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5486 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();
5488 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5490 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5493 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5495 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5496 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
5499 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
5501 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();
5502 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5504 // Double-check that six of the new HTLC were added
5505 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5506 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5507 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5508 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5510 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5511 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5512 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5513 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5514 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5515 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5516 check_added_monitors!(nodes[4], 0);
5517 expect_pending_htlcs_forwardable!(nodes[4]);
5518 check_added_monitors!(nodes[4], 1);
5520 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5521 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5522 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5523 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5524 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5525 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5527 // Fail 3rd below-dust and 7th above-dust HTLCs
5528 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5529 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5530 check_added_monitors!(nodes[5], 0);
5531 expect_pending_htlcs_forwardable!(nodes[5]);
5532 check_added_monitors!(nodes[5], 1);
5534 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5535 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5536 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5537 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5539 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5541 expect_pending_htlcs_forwardable!(nodes[3]);
5542 check_added_monitors!(nodes[3], 1);
5543 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5544 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5545 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5546 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5547 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5548 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5549 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5550 if deliver_last_raa {
5551 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5553 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5556 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5557 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5558 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5559 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5561 // We now broadcast the latest commitment transaction, which *should* result in failures for
5562 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5563 // the non-broadcast above-dust HTLCs.
5565 // Alternatively, we may broadcast the previous commitment transaction, which should only
5566 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5567 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5569 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5570 if announce_latest {
5571 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5573 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5575 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5576 check_closed_broadcast!(nodes[2], false);
5577 expect_pending_htlcs_forwardable!(nodes[2]);
5578 check_added_monitors!(nodes[2], 3);
5580 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5581 assert_eq!(cs_msgs.len(), 2);
5582 let mut a_done = false;
5583 for msg in cs_msgs {
5585 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5586 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5587 // should be failed-backwards here.
5588 let target = if *node_id == nodes[0].node.get_our_node_id() {
5589 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5590 for htlc in &updates.update_fail_htlcs {
5591 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 });
5593 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5598 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5599 for htlc in &updates.update_fail_htlcs {
5600 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5602 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5603 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5606 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5607 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5608 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5609 if announce_latest {
5610 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5611 if *node_id == nodes[0].node.get_our_node_id() {
5612 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5615 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5617 _ => panic!("Unexpected event"),
5621 let as_events = nodes[0].node.get_and_clear_pending_events();
5622 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5623 let mut as_failds = HashSet::new();
5624 for event in as_events.iter() {
5625 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5626 assert!(as_failds.insert(*payment_hash));
5627 if *payment_hash != payment_hash_2 {
5628 assert_eq!(*rejected_by_dest, deliver_last_raa);
5630 assert!(!rejected_by_dest);
5632 } else { panic!("Unexpected event"); }
5634 assert!(as_failds.contains(&payment_hash_1));
5635 assert!(as_failds.contains(&payment_hash_2));
5636 if announce_latest {
5637 assert!(as_failds.contains(&payment_hash_3));
5638 assert!(as_failds.contains(&payment_hash_5));
5640 assert!(as_failds.contains(&payment_hash_6));
5642 let bs_events = nodes[1].node.get_and_clear_pending_events();
5643 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5644 let mut bs_failds = HashSet::new();
5645 for event in bs_events.iter() {
5646 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5647 assert!(bs_failds.insert(*payment_hash));
5648 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5649 assert_eq!(*rejected_by_dest, deliver_last_raa);
5651 assert!(!rejected_by_dest);
5653 } else { panic!("Unexpected event"); }
5655 assert!(bs_failds.contains(&payment_hash_1));
5656 assert!(bs_failds.contains(&payment_hash_2));
5657 if announce_latest {
5658 assert!(bs_failds.contains(&payment_hash_4));
5660 assert!(bs_failds.contains(&payment_hash_5));
5662 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5663 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5664 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5665 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5666 // PaymentFailureNetworkUpdates.
5667 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5668 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5669 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5670 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5671 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5673 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5674 _ => panic!("Unexpected event"),
5680 fn test_fail_backwards_latest_remote_announce_a() {
5681 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5685 fn test_fail_backwards_latest_remote_announce_b() {
5686 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5690 fn test_fail_backwards_previous_remote_announce() {
5691 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5692 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5693 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5697 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5698 let chanmon_cfgs = create_chanmon_cfgs(2);
5699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5701 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5703 // Create some initial channels
5704 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5706 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5707 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5708 assert_eq!(local_txn[0].input.len(), 1);
5709 check_spends!(local_txn[0], chan_1.3);
5711 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5712 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5713 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5714 check_closed_broadcast!(nodes[0], false);
5715 check_added_monitors!(nodes[0], 1);
5717 let htlc_timeout = {
5718 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5719 assert_eq!(node_txn[0].input.len(), 1);
5720 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5721 check_spends!(node_txn[0], local_txn[0]);
5725 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5726 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5727 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5728 expect_payment_failed!(nodes[0], our_payment_hash, true);
5730 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5731 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5732 assert_eq!(spend_txn.len(), 3);
5733 assert_eq!(spend_txn[0], spend_txn[1]);
5734 check_spends!(spend_txn[0], local_txn[0]);
5735 check_spends!(spend_txn[2], htlc_timeout);
5739 fn test_key_derivation_params() {
5740 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5741 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5742 // let us re-derive the channel key set to then derive a delayed_payment_key.
5744 let chanmon_cfgs = create_chanmon_cfgs(3);
5746 // We manually create the node configuration to backup the seed.
5747 let seed = [42; 32];
5748 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5749 let chain_monitor = test_utils::TestChainMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5750 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager, node_seed: seed };
5751 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5752 node_cfgs.remove(0);
5753 node_cfgs.insert(0, node);
5755 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5756 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5758 // Create some initial channels
5759 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5761 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5762 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5763 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5765 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5766 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5767 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5768 assert_eq!(local_txn_1[0].input.len(), 1);
5769 check_spends!(local_txn_1[0], chan_1.3);
5771 // We check funding pubkey are unique
5772 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]));
5773 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]));
5774 if from_0_funding_key_0 == from_1_funding_key_0
5775 || from_0_funding_key_0 == from_1_funding_key_1
5776 || from_0_funding_key_1 == from_1_funding_key_0
5777 || from_0_funding_key_1 == from_1_funding_key_1 {
5778 panic!("Funding pubkeys aren't unique");
5781 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5782 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5783 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5784 check_closed_broadcast!(nodes[0], false);
5785 check_added_monitors!(nodes[0], 1);
5787 let htlc_timeout = {
5788 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5789 assert_eq!(node_txn[0].input.len(), 1);
5790 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5791 check_spends!(node_txn[0], local_txn_1[0]);
5795 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5796 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5797 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5798 expect_payment_failed!(nodes[0], our_payment_hash, true);
5800 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5801 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5802 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5803 assert_eq!(spend_txn.len(), 3);
5804 assert_eq!(spend_txn[0], spend_txn[1]);
5805 check_spends!(spend_txn[0], local_txn_1[0]);
5806 check_spends!(spend_txn[2], htlc_timeout);
5810 fn test_static_output_closing_tx() {
5811 let chanmon_cfgs = create_chanmon_cfgs(2);
5812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5814 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5816 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5818 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5819 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5821 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5822 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5823 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5825 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5826 assert_eq!(spend_txn.len(), 1);
5827 check_spends!(spend_txn[0], closing_tx);
5829 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5830 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5832 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5833 assert_eq!(spend_txn.len(), 1);
5834 check_spends!(spend_txn[0], closing_tx);
5837 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5838 let chanmon_cfgs = create_chanmon_cfgs(2);
5839 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5840 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5841 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5842 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5844 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5846 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5847 // present in B's local commitment transaction, but none of A's commitment transactions.
5848 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5849 check_added_monitors!(nodes[1], 1);
5851 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5852 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5853 let events = nodes[0].node.get_and_clear_pending_events();
5854 assert_eq!(events.len(), 1);
5856 Event::PaymentSent { payment_preimage } => {
5857 assert_eq!(payment_preimage, our_payment_preimage);
5859 _ => panic!("Unexpected event"),
5862 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5863 check_added_monitors!(nodes[0], 1);
5864 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5865 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5866 check_added_monitors!(nodes[1], 1);
5868 let mut block = Block {
5869 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5872 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5873 connect_block(&nodes[1], &block, i);
5874 block.header.prev_blockhash = block.block_hash();
5876 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5877 check_closed_broadcast!(nodes[1], false);
5878 check_added_monitors!(nodes[1], 1);
5881 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5882 let chanmon_cfgs = create_chanmon_cfgs(2);
5883 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5884 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5885 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5886 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5887 let logger = test_utils::TestLogger::new();
5889 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5890 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5891 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();
5892 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5893 check_added_monitors!(nodes[0], 1);
5895 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5897 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5898 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5899 // to "time out" the HTLC.
5901 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5903 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5904 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5905 header.prev_blockhash = header.block_hash();
5907 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5908 check_closed_broadcast!(nodes[0], false);
5909 check_added_monitors!(nodes[0], 1);
5912 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5913 let chanmon_cfgs = create_chanmon_cfgs(3);
5914 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5915 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5916 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5917 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5919 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5920 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5921 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5922 // actually revoked.
5923 let htlc_value = if use_dust { 50000 } else { 3000000 };
5924 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5925 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5926 expect_pending_htlcs_forwardable!(nodes[1]);
5927 check_added_monitors!(nodes[1], 1);
5929 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5930 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5931 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5932 check_added_monitors!(nodes[0], 1);
5933 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5934 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5935 check_added_monitors!(nodes[1], 1);
5936 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5937 check_added_monitors!(nodes[1], 1);
5938 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5940 if check_revoke_no_close {
5941 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5942 check_added_monitors!(nodes[0], 1);
5945 let mut block = Block {
5946 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5949 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5950 connect_block(&nodes[0], &block, i);
5951 block.header.prev_blockhash = block.block_hash();
5953 if !check_revoke_no_close {
5954 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5955 check_closed_broadcast!(nodes[0], false);
5956 check_added_monitors!(nodes[0], 1);
5958 expect_payment_failed!(nodes[0], our_payment_hash, true);
5962 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5963 // There are only a few cases to test here:
5964 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5965 // broadcastable commitment transactions result in channel closure,
5966 // * its included in an unrevoked-but-previous remote commitment transaction,
5967 // * its included in the latest remote or local commitment transactions.
5968 // We test each of the three possible commitment transactions individually and use both dust and
5970 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5971 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5972 // tested for at least one of the cases in other tests.
5974 fn htlc_claim_single_commitment_only_a() {
5975 do_htlc_claim_local_commitment_only(true);
5976 do_htlc_claim_local_commitment_only(false);
5978 do_htlc_claim_current_remote_commitment_only(true);
5979 do_htlc_claim_current_remote_commitment_only(false);
5983 fn htlc_claim_single_commitment_only_b() {
5984 do_htlc_claim_previous_remote_commitment_only(true, false);
5985 do_htlc_claim_previous_remote_commitment_only(false, false);
5986 do_htlc_claim_previous_remote_commitment_only(true, true);
5987 do_htlc_claim_previous_remote_commitment_only(false, true);
5992 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5993 let chanmon_cfgs = create_chanmon_cfgs(2);
5994 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5995 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5996 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5997 //Force duplicate channel ids
5998 for node in nodes.iter() {
5999 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6002 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6003 let channel_value_satoshis=10000;
6004 let push_msat=10001;
6005 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6006 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6007 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6009 //Create a second channel with a channel_id collision
6010 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6014 fn bolt2_open_channel_sending_node_checks_part2() {
6015 let chanmon_cfgs = create_chanmon_cfgs(2);
6016 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6017 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6018 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6020 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6021 let channel_value_satoshis=2^24;
6022 let push_msat=10001;
6023 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6025 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6026 let channel_value_satoshis=10000;
6027 // Test when push_msat is equal to 1000 * funding_satoshis.
6028 let push_msat=1000*channel_value_satoshis+1;
6029 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6031 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6032 let channel_value_satoshis=10000;
6033 let push_msat=10001;
6034 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
6035 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6036 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6038 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6039 // 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
6040 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6042 // 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.
6043 assert!(BREAKDOWN_TIMEOUT>0);
6044 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6046 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6047 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6048 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6050 // 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.
6051 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6052 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6053 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6054 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6055 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6058 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6059 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6060 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6061 // is no longer affordable once it's freed.
6063 fn test_fail_holding_cell_htlc_upon_free() {
6064 let chanmon_cfgs = create_chanmon_cfgs(2);
6065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6067 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6068 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6069 let logger = test_utils::TestLogger::new();
6071 // First nodes[0] generates an update_fee, setting the channel's
6072 // pending_update_fee.
6073 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6074 check_added_monitors!(nodes[0], 1);
6076 let events = nodes[0].node.get_and_clear_pending_msg_events();
6077 assert_eq!(events.len(), 1);
6078 let (update_msg, commitment_signed) = match events[0] {
6079 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6080 (update_fee.as_ref(), commitment_signed)
6082 _ => panic!("Unexpected event"),
6085 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6087 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6088 let channel_reserve = chan_stat.channel_reserve_msat;
6089 let feerate = get_feerate!(nodes[0], chan.2);
6091 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6092 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6093 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6094 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6095 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();
6097 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6098 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6099 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6100 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6102 // Flush the pending fee update.
6103 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6104 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6105 check_added_monitors!(nodes[1], 1);
6106 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6107 check_added_monitors!(nodes[0], 1);
6109 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6110 // HTLC, but now that the fee has been raised the payment will now fail, causing
6111 // us to surface its failure to the user.
6112 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6113 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6114 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6115 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);
6116 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6118 // Check that the payment failed to be sent out.
6119 let events = nodes[0].node.get_and_clear_pending_events();
6120 assert_eq!(events.len(), 1);
6122 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6123 assert_eq!(our_payment_hash.clone(), *payment_hash);
6124 assert_eq!(*rejected_by_dest, false);
6125 assert_eq!(*error_code, None);
6126 assert_eq!(*error_data, None);
6128 _ => panic!("Unexpected event"),
6132 // Test that if multiple HTLCs are released from the holding cell and one is
6133 // valid but the other is no longer valid upon release, the valid HTLC can be
6134 // successfully completed while the other one fails as expected.
6136 fn test_free_and_fail_holding_cell_htlcs() {
6137 let chanmon_cfgs = create_chanmon_cfgs(2);
6138 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6139 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6140 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6141 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6142 let logger = test_utils::TestLogger::new();
6144 // First nodes[0] generates an update_fee, setting the channel's
6145 // pending_update_fee.
6146 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6147 check_added_monitors!(nodes[0], 1);
6149 let events = nodes[0].node.get_and_clear_pending_msg_events();
6150 assert_eq!(events.len(), 1);
6151 let (update_msg, commitment_signed) = match events[0] {
6152 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6153 (update_fee.as_ref(), commitment_signed)
6155 _ => panic!("Unexpected event"),
6158 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6160 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6161 let channel_reserve = chan_stat.channel_reserve_msat;
6162 let feerate = get_feerate!(nodes[0], chan.2);
6164 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6165 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6167 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6168 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6169 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6170 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();
6171 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();
6173 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6174 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6175 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6176 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6177 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6178 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6179 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6181 // Flush the pending fee update.
6182 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6183 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6184 check_added_monitors!(nodes[1], 1);
6185 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6186 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6187 check_added_monitors!(nodes[0], 2);
6189 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6190 // but now that the fee has been raised the second payment will now fail, causing us
6191 // to surface its failure to the user. The first payment should succeed.
6192 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6193 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6194 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6195 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);
6196 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6198 // Check that the second payment failed to be sent out.
6199 let events = nodes[0].node.get_and_clear_pending_events();
6200 assert_eq!(events.len(), 1);
6202 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6203 assert_eq!(payment_hash_2.clone(), *payment_hash);
6204 assert_eq!(*rejected_by_dest, false);
6205 assert_eq!(*error_code, None);
6206 assert_eq!(*error_data, None);
6208 _ => panic!("Unexpected event"),
6211 // Complete the first payment and the RAA from the fee update.
6212 let (payment_event, send_raa_event) = {
6213 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6214 assert_eq!(msgs.len(), 2);
6215 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6217 let raa = match send_raa_event {
6218 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6219 _ => panic!("Unexpected event"),
6221 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6222 check_added_monitors!(nodes[1], 1);
6223 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6224 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6225 let events = nodes[1].node.get_and_clear_pending_events();
6226 assert_eq!(events.len(), 1);
6228 Event::PendingHTLCsForwardable { .. } => {},
6229 _ => panic!("Unexpected event"),
6231 nodes[1].node.process_pending_htlc_forwards();
6232 let events = nodes[1].node.get_and_clear_pending_events();
6233 assert_eq!(events.len(), 1);
6235 Event::PaymentReceived { .. } => {},
6236 _ => panic!("Unexpected event"),
6238 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6239 check_added_monitors!(nodes[1], 1);
6240 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6241 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6242 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6243 let events = nodes[0].node.get_and_clear_pending_events();
6244 assert_eq!(events.len(), 1);
6246 Event::PaymentSent { ref payment_preimage } => {
6247 assert_eq!(*payment_preimage, payment_preimage_1);
6249 _ => panic!("Unexpected event"),
6253 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6254 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6255 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6258 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6259 let chanmon_cfgs = create_chanmon_cfgs(3);
6260 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6261 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6262 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6263 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6264 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6265 let logger = test_utils::TestLogger::new();
6267 // First nodes[1] generates an update_fee, setting the channel's
6268 // pending_update_fee.
6269 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6270 check_added_monitors!(nodes[1], 1);
6272 let events = nodes[1].node.get_and_clear_pending_msg_events();
6273 assert_eq!(events.len(), 1);
6274 let (update_msg, commitment_signed) = match events[0] {
6275 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6276 (update_fee.as_ref(), commitment_signed)
6278 _ => panic!("Unexpected event"),
6281 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6283 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6284 let channel_reserve = chan_stat.channel_reserve_msat;
6285 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6287 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6289 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6290 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6291 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6292 let payment_event = {
6293 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6294 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();
6295 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6296 check_added_monitors!(nodes[0], 1);
6298 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6299 assert_eq!(events.len(), 1);
6301 SendEvent::from_event(events.remove(0))
6303 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6304 check_added_monitors!(nodes[1], 0);
6305 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6306 expect_pending_htlcs_forwardable!(nodes[1]);
6308 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6309 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6311 // Flush the pending fee update.
6312 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6313 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6314 check_added_monitors!(nodes[2], 1);
6315 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6316 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6317 check_added_monitors!(nodes[1], 2);
6319 // A final RAA message is generated to finalize the fee update.
6320 let events = nodes[1].node.get_and_clear_pending_msg_events();
6321 assert_eq!(events.len(), 1);
6323 let raa_msg = match &events[0] {
6324 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6327 _ => panic!("Unexpected event"),
6330 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6331 check_added_monitors!(nodes[2], 1);
6332 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6334 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6335 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6336 assert_eq!(process_htlc_forwards_event.len(), 1);
6337 match &process_htlc_forwards_event[0] {
6338 &Event::PendingHTLCsForwardable { .. } => {},
6339 _ => panic!("Unexpected event"),
6342 // In response, we call ChannelManager's process_pending_htlc_forwards
6343 nodes[1].node.process_pending_htlc_forwards();
6344 check_added_monitors!(nodes[1], 1);
6346 // This causes the HTLC to be failed backwards.
6347 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6348 assert_eq!(fail_event.len(), 1);
6349 let (fail_msg, commitment_signed) = match &fail_event[0] {
6350 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6351 assert_eq!(updates.update_add_htlcs.len(), 0);
6352 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6353 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6354 assert_eq!(updates.update_fail_htlcs.len(), 1);
6355 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6357 _ => panic!("Unexpected event"),
6360 // Pass the failure messages back to nodes[0].
6361 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6362 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6364 // Complete the HTLC failure+removal process.
6365 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6366 check_added_monitors!(nodes[0], 1);
6367 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6368 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6369 check_added_monitors!(nodes[1], 2);
6370 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6371 assert_eq!(final_raa_event.len(), 1);
6372 let raa = match &final_raa_event[0] {
6373 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6374 _ => panic!("Unexpected event"),
6376 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6377 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6378 assert_eq!(fail_msg_event.len(), 1);
6379 match &fail_msg_event[0] {
6380 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6381 _ => panic!("Unexpected event"),
6383 let failure_event = nodes[0].node.get_and_clear_pending_events();
6384 assert_eq!(failure_event.len(), 1);
6385 match &failure_event[0] {
6386 &Event::PaymentFailed { rejected_by_dest, .. } => {
6387 assert!(!rejected_by_dest);
6389 _ => panic!("Unexpected event"),
6391 check_added_monitors!(nodes[0], 1);
6394 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6395 // 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.
6396 //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.
6399 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6400 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6401 let chanmon_cfgs = create_chanmon_cfgs(2);
6402 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6403 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6404 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6405 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6407 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6408 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6409 let logger = test_utils::TestLogger::new();
6410 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();
6411 route.paths[0][0].fee_msat = 100;
6413 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6414 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6415 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6416 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6420 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6421 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6422 let chanmon_cfgs = create_chanmon_cfgs(2);
6423 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6424 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6425 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6426 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6427 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6429 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6430 let logger = test_utils::TestLogger::new();
6431 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();
6432 route.paths[0][0].fee_msat = 0;
6433 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6434 assert_eq!(err, "Cannot send 0-msat HTLC"));
6436 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6437 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6441 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6442 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6443 let chanmon_cfgs = create_chanmon_cfgs(2);
6444 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6445 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6446 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6447 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6449 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6450 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6451 let logger = test_utils::TestLogger::new();
6452 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();
6453 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6454 check_added_monitors!(nodes[0], 1);
6455 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6456 updates.update_add_htlcs[0].amount_msat = 0;
6458 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6459 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6460 check_closed_broadcast!(nodes[1], true).unwrap();
6461 check_added_monitors!(nodes[1], 1);
6465 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6466 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6467 //It is enforced when constructing a route.
6468 let chanmon_cfgs = create_chanmon_cfgs(2);
6469 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6470 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6471 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6472 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6473 let logger = test_utils::TestLogger::new();
6475 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6477 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6478 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();
6479 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6480 assert_eq!(err, &"Channel CLTV overflowed?"));
6484 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6485 //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.
6486 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6487 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6488 let chanmon_cfgs = create_chanmon_cfgs(2);
6489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6491 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6492 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6493 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6495 let logger = test_utils::TestLogger::new();
6496 for i in 0..max_accepted_htlcs {
6497 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6498 let payment_event = {
6499 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6500 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();
6501 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6502 check_added_monitors!(nodes[0], 1);
6504 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6505 assert_eq!(events.len(), 1);
6506 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6507 assert_eq!(htlcs[0].htlc_id, i);
6511 SendEvent::from_event(events.remove(0))
6513 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6514 check_added_monitors!(nodes[1], 0);
6515 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6517 expect_pending_htlcs_forwardable!(nodes[1]);
6518 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6520 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6521 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6522 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();
6523 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6524 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6526 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6527 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6531 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6532 //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.
6533 let chanmon_cfgs = create_chanmon_cfgs(2);
6534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6536 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6537 let channel_value = 100000;
6538 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6539 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6541 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6543 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6544 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6545 let logger = test_utils::TestLogger::new();
6546 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();
6547 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6548 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)));
6550 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6551 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);
6553 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6556 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6558 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6559 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6560 let chanmon_cfgs = create_chanmon_cfgs(2);
6561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6563 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6564 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6565 let htlc_minimum_msat: u64;
6567 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6568 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6569 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6572 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6573 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6574 let logger = test_utils::TestLogger::new();
6575 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();
6576 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6577 check_added_monitors!(nodes[0], 1);
6578 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6579 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6580 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6581 assert!(nodes[1].node.list_channels().is_empty());
6582 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6583 assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6584 check_added_monitors!(nodes[1], 1);
6588 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6589 //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
6590 let chanmon_cfgs = create_chanmon_cfgs(2);
6591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6593 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6594 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6595 let logger = test_utils::TestLogger::new();
6597 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6598 let channel_reserve = chan_stat.channel_reserve_msat;
6599 let feerate = get_feerate!(nodes[0], chan.2);
6600 // The 2* and +1 are for the fee spike reserve.
6601 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6603 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6604 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6605 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6606 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();
6607 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6608 check_added_monitors!(nodes[0], 1);
6609 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6611 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6612 // at this time channel-initiatee receivers are not required to enforce that senders
6613 // respect the fee_spike_reserve.
6614 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6615 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6617 assert!(nodes[1].node.list_channels().is_empty());
6618 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6619 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6620 check_added_monitors!(nodes[1], 1);
6624 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6625 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6626 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6627 let chanmon_cfgs = create_chanmon_cfgs(2);
6628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6630 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6631 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6632 let logger = test_utils::TestLogger::new();
6634 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6635 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6637 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6638 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();
6640 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6641 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6642 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6643 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6645 let mut msg = msgs::UpdateAddHTLC {
6649 payment_hash: our_payment_hash,
6650 cltv_expiry: htlc_cltv,
6651 onion_routing_packet: onion_packet.clone(),
6654 for i in 0..super::channel::OUR_MAX_HTLCS {
6655 msg.htlc_id = i as u64;
6656 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6658 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6659 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6661 assert!(nodes[1].node.list_channels().is_empty());
6662 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6663 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6664 check_added_monitors!(nodes[1], 1);
6668 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6669 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6670 let chanmon_cfgs = create_chanmon_cfgs(2);
6671 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6672 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6673 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6674 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6675 let logger = test_utils::TestLogger::new();
6677 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6678 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6679 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();
6680 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6681 check_added_monitors!(nodes[0], 1);
6682 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6683 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6684 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6686 assert!(nodes[1].node.list_channels().is_empty());
6687 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6688 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6689 check_added_monitors!(nodes[1], 1);
6693 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6694 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6695 let chanmon_cfgs = create_chanmon_cfgs(2);
6696 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6697 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6698 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6699 let logger = test_utils::TestLogger::new();
6701 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6702 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6703 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6704 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();
6705 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6706 check_added_monitors!(nodes[0], 1);
6707 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6708 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6711 assert!(nodes[1].node.list_channels().is_empty());
6712 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6713 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6714 check_added_monitors!(nodes[1], 1);
6718 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6719 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6720 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6721 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6722 let chanmon_cfgs = create_chanmon_cfgs(2);
6723 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6724 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6725 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6726 let logger = test_utils::TestLogger::new();
6728 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6729 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6730 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6731 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();
6732 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6733 check_added_monitors!(nodes[0], 1);
6734 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6735 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6737 //Disconnect and Reconnect
6738 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6739 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6740 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6741 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6742 assert_eq!(reestablish_1.len(), 1);
6743 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6744 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6745 assert_eq!(reestablish_2.len(), 1);
6746 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6747 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6748 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6749 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6752 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6753 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6755 check_added_monitors!(nodes[1], 1);
6756 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6758 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6760 assert!(nodes[1].node.list_channels().is_empty());
6761 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6762 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6763 check_added_monitors!(nodes[1], 1);
6767 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6768 //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.
6770 let chanmon_cfgs = create_chanmon_cfgs(2);
6771 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6772 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6773 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6774 let logger = test_utils::TestLogger::new();
6775 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6776 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6777 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6778 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();
6779 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6781 check_added_monitors!(nodes[0], 1);
6782 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6783 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6785 let update_msg = msgs::UpdateFulfillHTLC{
6788 payment_preimage: our_payment_preimage,
6791 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6793 assert!(nodes[0].node.list_channels().is_empty());
6794 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6795 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()));
6796 check_added_monitors!(nodes[0], 1);
6800 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6801 //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.
6803 let chanmon_cfgs = create_chanmon_cfgs(2);
6804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6806 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6807 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6808 let logger = test_utils::TestLogger::new();
6810 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6811 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6812 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();
6813 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6814 check_added_monitors!(nodes[0], 1);
6815 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6816 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6818 let update_msg = msgs::UpdateFailHTLC{
6821 reason: msgs::OnionErrorPacket { data: Vec::new()},
6824 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6826 assert!(nodes[0].node.list_channels().is_empty());
6827 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6828 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()));
6829 check_added_monitors!(nodes[0], 1);
6833 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6834 //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.
6836 let chanmon_cfgs = create_chanmon_cfgs(2);
6837 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6838 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6839 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6840 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6841 let logger = test_utils::TestLogger::new();
6843 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6844 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6845 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();
6846 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6847 check_added_monitors!(nodes[0], 1);
6848 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6849 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6851 let update_msg = msgs::UpdateFailMalformedHTLC{
6854 sha256_of_onion: [1; 32],
6855 failure_code: 0x8000,
6858 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6860 assert!(nodes[0].node.list_channels().is_empty());
6861 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6862 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()));
6863 check_added_monitors!(nodes[0], 1);
6867 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6868 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6870 let chanmon_cfgs = create_chanmon_cfgs(2);
6871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6873 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6874 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6876 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6878 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6879 check_added_monitors!(nodes[1], 1);
6881 let events = nodes[1].node.get_and_clear_pending_msg_events();
6882 assert_eq!(events.len(), 1);
6883 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6885 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, .. } } => {
6886 assert!(update_add_htlcs.is_empty());
6887 assert_eq!(update_fulfill_htlcs.len(), 1);
6888 assert!(update_fail_htlcs.is_empty());
6889 assert!(update_fail_malformed_htlcs.is_empty());
6890 assert!(update_fee.is_none());
6891 update_fulfill_htlcs[0].clone()
6893 _ => panic!("Unexpected event"),
6897 update_fulfill_msg.htlc_id = 1;
6899 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6901 assert!(nodes[0].node.list_channels().is_empty());
6902 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6903 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6904 check_added_monitors!(nodes[0], 1);
6908 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6909 //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.
6911 let chanmon_cfgs = create_chanmon_cfgs(2);
6912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6914 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6915 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6917 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6919 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6920 check_added_monitors!(nodes[1], 1);
6922 let events = nodes[1].node.get_and_clear_pending_msg_events();
6923 assert_eq!(events.len(), 1);
6924 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6926 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, .. } } => {
6927 assert!(update_add_htlcs.is_empty());
6928 assert_eq!(update_fulfill_htlcs.len(), 1);
6929 assert!(update_fail_htlcs.is_empty());
6930 assert!(update_fail_malformed_htlcs.is_empty());
6931 assert!(update_fee.is_none());
6932 update_fulfill_htlcs[0].clone()
6934 _ => panic!("Unexpected event"),
6938 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6940 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6942 assert!(nodes[0].node.list_channels().is_empty());
6943 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6944 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6945 check_added_monitors!(nodes[0], 1);
6949 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6950 //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.
6952 let chanmon_cfgs = create_chanmon_cfgs(2);
6953 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6954 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6955 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6956 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6957 let logger = test_utils::TestLogger::new();
6959 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6960 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6961 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();
6962 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6963 check_added_monitors!(nodes[0], 1);
6965 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6966 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6968 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6969 check_added_monitors!(nodes[1], 0);
6970 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6972 let events = nodes[1].node.get_and_clear_pending_msg_events();
6974 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6976 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, .. } } => {
6977 assert!(update_add_htlcs.is_empty());
6978 assert!(update_fulfill_htlcs.is_empty());
6979 assert!(update_fail_htlcs.is_empty());
6980 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6981 assert!(update_fee.is_none());
6982 update_fail_malformed_htlcs[0].clone()
6984 _ => panic!("Unexpected event"),
6987 update_msg.failure_code &= !0x8000;
6988 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6990 assert!(nodes[0].node.list_channels().is_empty());
6991 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6992 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6993 check_added_monitors!(nodes[0], 1);
6997 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6998 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6999 // * 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.
7001 let chanmon_cfgs = create_chanmon_cfgs(3);
7002 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7003 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7004 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7005 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7006 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7007 let logger = test_utils::TestLogger::new();
7009 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7012 let mut payment_event = {
7013 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7014 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();
7015 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7016 check_added_monitors!(nodes[0], 1);
7017 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7018 assert_eq!(events.len(), 1);
7019 SendEvent::from_event(events.remove(0))
7021 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7022 check_added_monitors!(nodes[1], 0);
7023 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7024 expect_pending_htlcs_forwardable!(nodes[1]);
7025 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7026 assert_eq!(events_2.len(), 1);
7027 check_added_monitors!(nodes[1], 1);
7028 payment_event = SendEvent::from_event(events_2.remove(0));
7029 assert_eq!(payment_event.msgs.len(), 1);
7032 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7033 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7034 check_added_monitors!(nodes[2], 0);
7035 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7037 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7038 assert_eq!(events_3.len(), 1);
7039 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7041 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 } } => {
7042 assert!(update_add_htlcs.is_empty());
7043 assert!(update_fulfill_htlcs.is_empty());
7044 assert!(update_fail_htlcs.is_empty());
7045 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7046 assert!(update_fee.is_none());
7047 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7049 _ => panic!("Unexpected event"),
7053 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7055 check_added_monitors!(nodes[1], 0);
7056 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7057 expect_pending_htlcs_forwardable!(nodes[1]);
7058 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7059 assert_eq!(events_4.len(), 1);
7061 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7063 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, .. } } => {
7064 assert!(update_add_htlcs.is_empty());
7065 assert!(update_fulfill_htlcs.is_empty());
7066 assert_eq!(update_fail_htlcs.len(), 1);
7067 assert!(update_fail_malformed_htlcs.is_empty());
7068 assert!(update_fee.is_none());
7070 _ => panic!("Unexpected event"),
7073 check_added_monitors!(nodes[1], 1);
7076 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7077 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7078 // 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
7079 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7081 let chanmon_cfgs = create_chanmon_cfgs(2);
7082 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7083 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7084 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7085 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7087 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7089 // We route 2 dust-HTLCs between A and B
7090 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7091 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7092 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7094 // Cache one local commitment tx as previous
7095 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7097 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7098 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7099 check_added_monitors!(nodes[1], 0);
7100 expect_pending_htlcs_forwardable!(nodes[1]);
7101 check_added_monitors!(nodes[1], 1);
7103 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7104 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7105 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7106 check_added_monitors!(nodes[0], 1);
7108 // Cache one local commitment tx as lastest
7109 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7111 let events = nodes[0].node.get_and_clear_pending_msg_events();
7113 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7114 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7116 _ => panic!("Unexpected event"),
7119 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7120 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7122 _ => panic!("Unexpected event"),
7125 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7126 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7127 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7129 if announce_latest {
7130 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7132 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7135 check_closed_broadcast!(nodes[0], false);
7136 check_added_monitors!(nodes[0], 1);
7138 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7139 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7140 let events = nodes[0].node.get_and_clear_pending_events();
7141 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7142 assert_eq!(events.len(), 2);
7143 let mut first_failed = false;
7144 for event in events {
7146 Event::PaymentFailed { payment_hash, .. } => {
7147 if payment_hash == payment_hash_1 {
7148 assert!(!first_failed);
7149 first_failed = true;
7151 assert_eq!(payment_hash, payment_hash_2);
7154 _ => panic!("Unexpected event"),
7160 fn test_failure_delay_dust_htlc_local_commitment() {
7161 do_test_failure_delay_dust_htlc_local_commitment(true);
7162 do_test_failure_delay_dust_htlc_local_commitment(false);
7166 fn test_no_failure_dust_htlc_local_commitment() {
7167 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7168 // prone to error, we test here that a dummy transaction don't fail them.
7170 let chanmon_cfgs = create_chanmon_cfgs(2);
7171 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7172 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7173 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7174 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7177 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7179 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7180 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7182 // We route 2 dust-HTLCs between A and B
7183 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7184 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7186 // Build a dummy invalid transaction trying to spend a commitment tx
7188 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7189 script_sig: Script::new(),
7191 witness: Vec::new(),
7195 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7199 let dummy_tx = Transaction {
7206 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7207 nodes[0].chain_monitor.chain_monitor.block_connected(&header, &[(0, &dummy_tx)], 1);
7208 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7209 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7210 // We broadcast a few more block to check everything is all right
7211 connect_blocks(&nodes[0], 20, 1, true, header.block_hash());
7212 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7213 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7215 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7216 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7219 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7220 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7221 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7222 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7223 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7224 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7225 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7227 let chanmon_cfgs = create_chanmon_cfgs(3);
7228 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7229 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7230 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7231 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7233 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7235 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7236 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7238 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7239 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7241 // We revoked bs_commitment_tx
7243 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7244 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7247 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7248 let mut timeout_tx = Vec::new();
7250 // We fail dust-HTLC 1 by broadcast of local commitment tx
7251 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7252 check_closed_broadcast!(nodes[0], false);
7253 check_added_monitors!(nodes[0], 1);
7254 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7255 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7256 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7257 expect_payment_failed!(nodes[0], dust_hash, true);
7258 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7259 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7260 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7261 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7262 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7263 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7264 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7265 expect_payment_failed!(nodes[0], non_dust_hash, true);
7267 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7268 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7269 check_closed_broadcast!(nodes[0], false);
7270 check_added_monitors!(nodes[0], 1);
7271 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7272 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7273 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7274 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7276 expect_payment_failed!(nodes[0], dust_hash, true);
7277 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7278 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7279 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7280 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7281 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7282 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7283 expect_payment_failed!(nodes[0], non_dust_hash, true);
7285 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7287 let events = nodes[0].node.get_and_clear_pending_events();
7288 assert_eq!(events.len(), 2);
7291 Event::PaymentFailed { payment_hash, .. } => {
7292 if payment_hash == dust_hash { first = true; }
7293 else { first = false; }
7295 _ => panic!("Unexpected event"),
7298 Event::PaymentFailed { payment_hash, .. } => {
7299 if first { assert_eq!(payment_hash, non_dust_hash); }
7300 else { assert_eq!(payment_hash, dust_hash); }
7302 _ => panic!("Unexpected event"),
7309 fn test_sweep_outbound_htlc_failure_update() {
7310 do_test_sweep_outbound_htlc_failure_update(false, true);
7311 do_test_sweep_outbound_htlc_failure_update(false, false);
7312 do_test_sweep_outbound_htlc_failure_update(true, false);
7316 fn test_upfront_shutdown_script() {
7317 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7318 // enforce it at shutdown message
7320 let mut config = UserConfig::default();
7321 config.channel_options.announced_channel = true;
7322 config.peer_channel_config_limits.force_announced_channel_preference = false;
7323 config.channel_options.commit_upfront_shutdown_pubkey = false;
7324 let user_cfgs = [None, Some(config), None];
7325 let chanmon_cfgs = create_chanmon_cfgs(3);
7326 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7327 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7328 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7330 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7331 let flags = InitFeatures::known();
7332 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7333 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7334 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7335 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7336 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7337 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7338 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()));
7339 check_added_monitors!(nodes[2], 1);
7341 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7342 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7343 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7344 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7345 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7346 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7347 let events = nodes[2].node.get_and_clear_pending_msg_events();
7348 assert_eq!(events.len(), 1);
7350 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7351 _ => panic!("Unexpected event"),
7354 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7355 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7356 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7357 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7358 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7359 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7360 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7361 let events = nodes[1].node.get_and_clear_pending_msg_events();
7362 assert_eq!(events.len(), 1);
7364 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7365 _ => panic!("Unexpected event"),
7368 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7369 // channel smoothly, opt-out is from channel initiator here
7370 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7371 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7372 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7373 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7374 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7375 let events = nodes[0].node.get_and_clear_pending_msg_events();
7376 assert_eq!(events.len(), 1);
7378 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7379 _ => panic!("Unexpected event"),
7382 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7383 //// channel smoothly
7384 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7385 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7386 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7387 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7388 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7389 let events = nodes[0].node.get_and_clear_pending_msg_events();
7390 assert_eq!(events.len(), 2);
7392 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7393 _ => panic!("Unexpected event"),
7396 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7397 _ => panic!("Unexpected event"),
7402 fn test_user_configurable_csv_delay() {
7403 // We test our channel constructors yield errors when we pass them absurd csv delay
7405 let mut low_our_to_self_config = UserConfig::default();
7406 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7407 let mut high_their_to_self_config = UserConfig::default();
7408 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7409 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7410 let chanmon_cfgs = create_chanmon_cfgs(2);
7411 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7412 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7413 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7415 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7416 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7417 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) {
7419 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())); },
7420 _ => panic!("Unexpected event"),
7422 } else { assert!(false) }
7424 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7425 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7426 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7427 open_channel.to_self_delay = 200;
7428 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) {
7430 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())); },
7431 _ => panic!("Unexpected event"),
7433 } else { assert!(false); }
7435 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7436 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7437 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()));
7438 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7439 accept_channel.to_self_delay = 200;
7440 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7441 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7443 &ErrorAction::SendErrorMessage { ref msg } => {
7444 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()));
7446 _ => { assert!(false); }
7448 } else { assert!(false); }
7450 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7451 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7452 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7453 open_channel.to_self_delay = 200;
7454 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) {
7456 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())); },
7457 _ => panic!("Unexpected event"),
7459 } else { assert!(false); }
7463 fn test_data_loss_protect() {
7464 // We want to be sure that :
7465 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7466 // * we close channel in case of detecting other being fallen behind
7467 // * we are able to claim our own outputs thanks to to_remote being static
7475 let chanmon_cfgs = create_chanmon_cfgs(2);
7476 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7477 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7478 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7480 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7482 // Cache node A state before any channel update
7483 let previous_node_state = nodes[0].node.encode();
7484 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7485 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chain_monitor_state).unwrap();
7487 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7488 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7490 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7491 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7493 // Restore node A from previous state
7494 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7495 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0)).unwrap().1;
7496 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7497 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7498 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7499 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7500 monitor = test_utils::TestChainMonitor::new(&tx_broadcaster, &logger, &fee_estimator);
7502 let mut channel_monitors = HashMap::new();
7503 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7504 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7505 keys_manager: &keys_manager,
7506 fee_estimator: &fee_estimator,
7507 chain_monitor: &monitor,
7509 tx_broadcaster: &tx_broadcaster,
7510 default_config: UserConfig::default(),
7514 nodes[0].node = &node_state_0;
7515 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7516 nodes[0].chain_monitor = &monitor;
7517 nodes[0].chain_source = &chain_source;
7519 check_added_monitors!(nodes[0], 1);
7521 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7522 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7524 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7526 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7527 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7528 check_added_monitors!(nodes[0], 1);
7531 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7532 assert_eq!(node_txn.len(), 0);
7535 let mut reestablish_1 = Vec::with_capacity(1);
7536 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7537 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7538 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7539 reestablish_1.push(msg.clone());
7540 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7541 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7543 &ErrorAction::SendErrorMessage { ref msg } => {
7544 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");
7546 _ => panic!("Unexpected event!"),
7549 panic!("Unexpected event")
7553 // Check we close channel detecting A is fallen-behind
7554 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7555 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7556 check_added_monitors!(nodes[1], 1);
7559 // Check A is able to claim to_remote output
7560 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7561 assert_eq!(node_txn.len(), 1);
7562 check_spends!(node_txn[0], chan.3);
7563 assert_eq!(node_txn[0].output.len(), 2);
7564 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7565 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7566 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7567 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7568 assert_eq!(spend_txn.len(), 1);
7569 check_spends!(spend_txn[0], node_txn[0]);
7573 fn test_check_htlc_underpaying() {
7574 // Send payment through A -> B but A is maliciously
7575 // sending a probe payment (i.e less than expected value0
7576 // to B, B should refuse payment.
7578 let chanmon_cfgs = create_chanmon_cfgs(2);
7579 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7580 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7581 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7583 // Create some initial channels
7584 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7586 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7588 // Node 3 is expecting payment of 100_000 but receive 10_000,
7589 // fail htlc like we didn't know the preimage.
7590 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7591 nodes[1].node.process_pending_htlc_forwards();
7593 let events = nodes[1].node.get_and_clear_pending_msg_events();
7594 assert_eq!(events.len(), 1);
7595 let (update_fail_htlc, commitment_signed) = match events[0] {
7596 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 } } => {
7597 assert!(update_add_htlcs.is_empty());
7598 assert!(update_fulfill_htlcs.is_empty());
7599 assert_eq!(update_fail_htlcs.len(), 1);
7600 assert!(update_fail_malformed_htlcs.is_empty());
7601 assert!(update_fee.is_none());
7602 (update_fail_htlcs[0].clone(), commitment_signed)
7604 _ => panic!("Unexpected event"),
7606 check_added_monitors!(nodes[1], 1);
7608 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7609 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7611 // 10_000 msat as u64, followed by a height of 99 as u32
7612 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7613 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7614 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7615 nodes[1].node.get_and_clear_pending_events();
7619 fn test_announce_disable_channels() {
7620 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7621 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7623 let chanmon_cfgs = create_chanmon_cfgs(2);
7624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7626 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7628 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7629 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7630 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7633 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7634 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7636 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7637 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7638 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7639 assert_eq!(msg_events.len(), 3);
7640 for e in msg_events {
7642 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7643 let short_id = msg.contents.short_channel_id;
7644 // Check generated channel_update match list in PendingChannelUpdate
7645 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7646 panic!("Generated ChannelUpdate for wrong chan!");
7649 _ => panic!("Unexpected event"),
7653 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7654 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7655 assert_eq!(reestablish_1.len(), 3);
7656 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7657 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7658 assert_eq!(reestablish_2.len(), 3);
7660 // Reestablish chan_1
7661 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7662 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7663 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7664 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7665 // Reestablish chan_2
7666 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
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[1]);
7669 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7670 // Reestablish chan_3
7671 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
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[2]);
7674 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7676 nodes[0].node.timer_chan_freshness_every_min();
7677 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7681 fn test_bump_penalty_txn_on_revoked_commitment() {
7682 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7683 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7685 let chanmon_cfgs = create_chanmon_cfgs(2);
7686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7688 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7690 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7691 let logger = test_utils::TestLogger::new();
7694 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7695 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7696 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();
7697 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7699 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7700 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7701 assert_eq!(revoked_txn[0].output.len(), 4);
7702 assert_eq!(revoked_txn[0].input.len(), 1);
7703 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7704 let revoked_txid = revoked_txn[0].txid();
7706 let mut penalty_sum = 0;
7707 for outp in revoked_txn[0].output.iter() {
7708 if outp.script_pubkey.is_v0_p2wsh() {
7709 penalty_sum += outp.value;
7713 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7714 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7716 // Actually revoke tx by claiming a HTLC
7717 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7718 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7719 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7720 check_added_monitors!(nodes[1], 1);
7722 // One or more justice tx should have been broadcast, check it
7726 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7727 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7728 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7729 assert_eq!(node_txn[0].output.len(), 1);
7730 check_spends!(node_txn[0], revoked_txn[0]);
7731 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7732 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7733 penalty_1 = node_txn[0].txid();
7737 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7738 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7739 let mut penalty_2 = penalty_1;
7740 let mut feerate_2 = 0;
7742 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7743 assert_eq!(node_txn.len(), 1);
7744 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7745 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7746 assert_eq!(node_txn[0].output.len(), 1);
7747 check_spends!(node_txn[0], revoked_txn[0]);
7748 penalty_2 = node_txn[0].txid();
7749 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7750 assert_ne!(penalty_2, penalty_1);
7751 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7752 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7753 // Verify 25% bump heuristic
7754 assert!(feerate_2 * 100 >= feerate_1 * 125);
7758 assert_ne!(feerate_2, 0);
7760 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7761 connect_blocks(&nodes[1], 3, 118, true, header);
7763 let mut feerate_3 = 0;
7765 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7766 assert_eq!(node_txn.len(), 1);
7767 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7768 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7769 assert_eq!(node_txn[0].output.len(), 1);
7770 check_spends!(node_txn[0], revoked_txn[0]);
7771 penalty_3 = node_txn[0].txid();
7772 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7773 assert_ne!(penalty_3, penalty_2);
7774 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7775 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7776 // Verify 25% bump heuristic
7777 assert!(feerate_3 * 100 >= feerate_2 * 125);
7781 assert_ne!(feerate_3, 0);
7783 nodes[1].node.get_and_clear_pending_events();
7784 nodes[1].node.get_and_clear_pending_msg_events();
7788 fn test_bump_penalty_txn_on_revoked_htlcs() {
7789 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7790 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7792 let chanmon_cfgs = create_chanmon_cfgs(2);
7793 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7794 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7795 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7797 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7798 // Lock HTLC in both directions
7799 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7800 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7802 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7803 assert_eq!(revoked_local_txn[0].input.len(), 1);
7804 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7806 // Revoke local commitment tx
7807 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7809 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7810 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7811 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7812 check_closed_broadcast!(nodes[1], false);
7813 check_added_monitors!(nodes[1], 1);
7815 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7816 assert_eq!(revoked_htlc_txn.len(), 4);
7817 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7818 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7819 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7820 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7821 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7822 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7823 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7824 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7825 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7826 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7827 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7828 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7829 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7830 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7833 // Broadcast set of revoked txn on A
7834 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7835 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7836 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7837 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7838 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7843 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7844 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7845 // Verify claim tx are spending revoked HTLC txn
7847 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7848 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7849 // which are included in the same block (they are broadcasted because we scan the
7850 // transactions linearly and generate claims as we go, they likely should be removed in the
7852 assert_eq!(node_txn[0].input.len(), 1);
7853 check_spends!(node_txn[0], revoked_local_txn[0]);
7854 assert_eq!(node_txn[1].input.len(), 1);
7855 check_spends!(node_txn[1], revoked_local_txn[0]);
7856 assert_eq!(node_txn[2].input.len(), 1);
7857 check_spends!(node_txn[2], revoked_local_txn[0]);
7859 // Each of the three justice transactions claim a separate (single) output of the three
7860 // available, which we check here:
7861 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7862 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7863 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7865 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7866 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7868 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7869 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7870 // a remote commitment tx has already been confirmed).
7871 check_spends!(node_txn[3], chan.3);
7873 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7874 // output, checked above).
7875 assert_eq!(node_txn[4].input.len(), 2);
7876 assert_eq!(node_txn[4].output.len(), 1);
7877 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7879 first = node_txn[4].txid();
7880 // Store both feerates for later comparison
7881 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7882 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7883 penalty_txn = vec![node_txn[2].clone()];
7887 // Connect one more block to see if bumped penalty are issued for HTLC txn
7888 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7889 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7890 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7891 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7893 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7894 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7896 check_spends!(node_txn[0], revoked_local_txn[0]);
7897 check_spends!(node_txn[1], revoked_local_txn[0]);
7898 // Note that these are both bogus - they spend outputs already claimed in block 129:
7899 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7900 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7902 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7903 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7909 // Few more blocks to confirm penalty txn
7910 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7911 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7912 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7914 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7915 assert_eq!(node_txn.len(), 1);
7917 assert_eq!(node_txn[0].input.len(), 2);
7918 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7919 // Verify bumped tx is different and 25% bump heuristic
7920 assert_ne!(first, node_txn[0].txid());
7921 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7922 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7923 assert!(feerate_2 * 100 > feerate_1 * 125);
7924 let txn = vec![node_txn[0].clone()];
7928 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7929 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7930 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7931 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7933 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7934 // We verify than no new transaction has been broadcast because previously
7935 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7936 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7937 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7938 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7939 // up bumped justice generation.
7940 assert_eq!(node_txn.len(), 0);
7943 check_closed_broadcast!(nodes[0], false);
7944 check_added_monitors!(nodes[0], 1);
7948 fn test_bump_penalty_txn_on_remote_commitment() {
7949 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7950 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7953 // Provide preimage for one
7954 // Check aggregation
7956 let chanmon_cfgs = create_chanmon_cfgs(2);
7957 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7958 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7959 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7961 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7962 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7963 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7965 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7966 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7967 assert_eq!(remote_txn[0].output.len(), 4);
7968 assert_eq!(remote_txn[0].input.len(), 1);
7969 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7971 // Claim a HTLC without revocation (provide B monitor with preimage)
7972 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7973 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7974 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7975 check_added_monitors!(nodes[1], 2);
7977 // One or more claim tx should have been broadcast, check it
7980 let feerate_timeout;
7981 let feerate_preimage;
7983 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7984 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7985 assert_eq!(node_txn[0].input.len(), 1);
7986 assert_eq!(node_txn[1].input.len(), 1);
7987 check_spends!(node_txn[0], remote_txn[0]);
7988 check_spends!(node_txn[1], remote_txn[0]);
7989 check_spends!(node_txn[2], chan.3);
7990 check_spends!(node_txn[3], node_txn[2]);
7991 check_spends!(node_txn[4], node_txn[2]);
7992 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7993 timeout = node_txn[0].txid();
7994 let index = node_txn[0].input[0].previous_output.vout;
7995 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7996 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7998 preimage = node_txn[1].txid();
7999 let index = node_txn[1].input[0].previous_output.vout;
8000 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8001 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
8003 timeout = 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_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
8008 preimage = node_txn[0].txid();
8009 let index = node_txn[0].input[0].previous_output.vout;
8010 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8011 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
8015 assert_ne!(feerate_timeout, 0);
8016 assert_ne!(feerate_preimage, 0);
8018 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
8019 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
8021 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8022 assert_eq!(node_txn.len(), 2);
8023 assert_eq!(node_txn[0].input.len(), 1);
8024 assert_eq!(node_txn[1].input.len(), 1);
8025 check_spends!(node_txn[0], remote_txn[0]);
8026 check_spends!(node_txn[1], remote_txn[0]);
8027 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
8028 let index = node_txn[0].input[0].previous_output.vout;
8029 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8030 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8031 assert!(new_feerate * 100 > feerate_timeout * 125);
8032 assert_ne!(timeout, node_txn[0].txid());
8034 let index = node_txn[1].input[0].previous_output.vout;
8035 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8036 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8037 assert!(new_feerate * 100 > feerate_preimage * 125);
8038 assert_ne!(preimage, node_txn[1].txid());
8040 let index = node_txn[1].input[0].previous_output.vout;
8041 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
8042 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
8043 assert!(new_feerate * 100 > feerate_timeout * 125);
8044 assert_ne!(timeout, node_txn[1].txid());
8046 let index = node_txn[0].input[0].previous_output.vout;
8047 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8048 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8049 assert!(new_feerate * 100 > feerate_preimage * 125);
8050 assert_ne!(preimage, node_txn[0].txid());
8055 nodes[1].node.get_and_clear_pending_events();
8056 nodes[1].node.get_and_clear_pending_msg_events();
8060 fn test_set_outpoints_partial_claiming() {
8061 // - remote party claim tx, new bump tx
8062 // - disconnect remote claiming tx, new bump
8063 // - disconnect tx, see no tx anymore
8064 let chanmon_cfgs = create_chanmon_cfgs(2);
8065 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8066 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8067 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8069 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8070 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8071 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8073 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8074 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8075 assert_eq!(remote_txn.len(), 3);
8076 assert_eq!(remote_txn[0].output.len(), 4);
8077 assert_eq!(remote_txn[0].input.len(), 1);
8078 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8079 check_spends!(remote_txn[1], remote_txn[0]);
8080 check_spends!(remote_txn[2], remote_txn[0]);
8082 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8083 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8084 // Provide node A with both preimage
8085 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8086 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8087 check_added_monitors!(nodes[0], 2);
8088 nodes[0].node.get_and_clear_pending_events();
8089 nodes[0].node.get_and_clear_pending_msg_events();
8091 // Connect blocks on node A commitment transaction
8092 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8093 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8094 check_closed_broadcast!(nodes[0], false);
8095 check_added_monitors!(nodes[0], 1);
8096 // Verify node A broadcast tx claiming both HTLCs
8098 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8099 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8100 assert_eq!(node_txn.len(), 4);
8101 check_spends!(node_txn[0], remote_txn[0]);
8102 check_spends!(node_txn[1], chan.3);
8103 check_spends!(node_txn[2], node_txn[1]);
8104 check_spends!(node_txn[3], node_txn[1]);
8105 assert_eq!(node_txn[0].input.len(), 2);
8109 // Connect blocks on node B
8110 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8111 check_closed_broadcast!(nodes[1], false);
8112 check_added_monitors!(nodes[1], 1);
8113 // Verify node B broadcast 2 HTLC-timeout txn
8114 let partial_claim_tx = {
8115 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8116 assert_eq!(node_txn.len(), 3);
8117 check_spends!(node_txn[1], node_txn[0]);
8118 check_spends!(node_txn[2], node_txn[0]);
8119 assert_eq!(node_txn[1].input.len(), 1);
8120 assert_eq!(node_txn[2].input.len(), 1);
8124 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8125 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8126 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8128 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8129 assert_eq!(node_txn.len(), 1);
8130 check_spends!(node_txn[0], remote_txn[0]);
8131 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8134 nodes[0].node.get_and_clear_pending_msg_events();
8136 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8137 disconnect_block(&nodes[0], &header, 102);
8139 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8140 assert_eq!(node_txn.len(), 1);
8141 check_spends!(node_txn[0], remote_txn[0]);
8142 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8146 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8147 disconnect_block(&nodes[0], &header, 101);
8148 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8150 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8151 assert_eq!(node_txn.len(), 0);
8157 fn test_counterparty_raa_skip_no_crash() {
8158 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8159 // commitment transaction, we would have happily carried on and provided them the next
8160 // commitment transaction based on one RAA forward. This would probably eventually have led to
8161 // channel closure, but it would not have resulted in funds loss. Still, our
8162 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8163 // check simply that the channel is closed in response to such an RAA, but don't check whether
8164 // we decide to punish our counterparty for revoking their funds (as we don't currently
8166 let chanmon_cfgs = create_chanmon_cfgs(2);
8167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8169 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8170 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8172 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8173 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8174 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8175 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8176 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8177 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8179 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8180 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8181 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8182 check_added_monitors!(nodes[1], 1);
8186 fn test_bump_txn_sanitize_tracking_maps() {
8187 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8188 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8190 let chanmon_cfgs = create_chanmon_cfgs(2);
8191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8193 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8195 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8196 // Lock HTLC in both directions
8197 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8198 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8200 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8201 assert_eq!(revoked_local_txn[0].input.len(), 1);
8202 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8204 // Revoke local commitment tx
8205 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8207 // Broadcast set of revoked txn on A
8208 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8209 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8211 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8212 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8213 check_closed_broadcast!(nodes[0], false);
8214 check_added_monitors!(nodes[0], 1);
8216 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8217 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8218 check_spends!(node_txn[0], revoked_local_txn[0]);
8219 check_spends!(node_txn[1], revoked_local_txn[0]);
8220 check_spends!(node_txn[2], revoked_local_txn[0]);
8221 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8225 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8226 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8227 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8229 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8230 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8231 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8232 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8238 fn test_override_channel_config() {
8239 let chanmon_cfgs = create_chanmon_cfgs(2);
8240 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8241 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8242 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8244 // Node0 initiates a channel to node1 using the override config.
8245 let mut override_config = UserConfig::default();
8246 override_config.own_channel_config.our_to_self_delay = 200;
8248 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8250 // Assert the channel created by node0 is using the override config.
8251 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8252 assert_eq!(res.channel_flags, 0);
8253 assert_eq!(res.to_self_delay, 200);
8257 fn test_override_0msat_htlc_minimum() {
8258 let mut zero_config = UserConfig::default();
8259 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8260 let chanmon_cfgs = create_chanmon_cfgs(2);
8261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8263 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8265 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8266 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8267 assert_eq!(res.htlc_minimum_msat, 1);
8269 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8270 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8271 assert_eq!(res.htlc_minimum_msat, 1);
8275 fn test_simple_payment_secret() {
8276 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8277 // features, however.
8278 let chanmon_cfgs = create_chanmon_cfgs(3);
8279 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8280 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8281 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8283 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8284 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8285 let logger = test_utils::TestLogger::new();
8287 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8288 let payment_secret = PaymentSecret([0xdb; 32]);
8289 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8290 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8291 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8292 // Claiming with all the correct values but the wrong secret should result in nothing...
8293 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8294 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8295 // ...but with the right secret we should be able to claim all the way back
8296 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8300 fn test_simple_mpp() {
8301 // Simple test of sending a multi-path payment.
8302 let chanmon_cfgs = create_chanmon_cfgs(4);
8303 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8304 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8305 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8307 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8308 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8309 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8310 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8311 let logger = test_utils::TestLogger::new();
8313 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8314 let payment_secret = PaymentSecret([0xdb; 32]);
8315 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8316 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
8317 let path = route.paths[0].clone();
8318 route.paths.push(path);
8319 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8320 route.paths[0][0].short_channel_id = chan_1_id;
8321 route.paths[0][1].short_channel_id = chan_3_id;
8322 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8323 route.paths[1][0].short_channel_id = chan_2_id;
8324 route.paths[1][1].short_channel_id = chan_4_id;
8325 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8326 // Claiming with all the correct values but the wrong secret should result in nothing...
8327 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8328 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8329 // ...but with the right secret we should be able to claim all the way back
8330 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8334 fn test_update_err_monitor_lockdown() {
8335 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8336 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8337 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8339 // This scenario may happen in a watchtower setup, where watchtower process a block height
8340 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8341 // commitment at same time.
8343 let chanmon_cfgs = create_chanmon_cfgs(2);
8344 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8345 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8346 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8348 // Create some initial channel
8349 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8350 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8352 // Rebalance the network to generate htlc in the two directions
8353 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8355 // Route a HTLC from node 0 to node 1 (but don't settle)
8356 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8358 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8359 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8361 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8362 let monitor = monitors.get(&outpoint).unwrap();
8363 let mut w = test_utils::TestVecWriter(Vec::new());
8364 monitor.write_for_disk(&mut w).unwrap();
8365 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8366 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8367 assert!(new_monitor == *monitor);
8368 let watchtower = test_utils::TestChainMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8369 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8372 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8373 watchtower.chain_monitor.block_connected(&header, &[], 200);
8375 // Try to update ChannelMonitor
8376 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8377 check_added_monitors!(nodes[1], 1);
8378 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8379 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8380 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8381 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8382 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8383 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8384 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8385 } else { assert!(false); }
8386 } else { assert!(false); };
8387 // Our local monitor is in-sync and hasn't processed yet timeout
8388 check_added_monitors!(nodes[0], 1);
8389 let events = nodes[0].node.get_and_clear_pending_events();
8390 assert_eq!(events.len(), 1);
8394 fn test_concurrent_monitor_claim() {
8395 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8396 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8397 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8398 // state N+1 confirms. Alice claims output from state N+1.
8400 let chanmon_cfgs = create_chanmon_cfgs(2);
8401 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8402 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8403 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8405 // Create some initial channel
8406 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8407 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8409 // Rebalance the network to generate htlc in the two directions
8410 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8412 // Route a HTLC from node 0 to node 1 (but don't settle)
8413 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8415 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8416 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8417 let watchtower_alice = {
8418 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8419 let monitor = monitors.get(&outpoint).unwrap();
8420 let mut w = test_utils::TestVecWriter(Vec::new());
8421 monitor.write_for_disk(&mut w).unwrap();
8422 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8423 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8424 assert!(new_monitor == *monitor);
8425 let watchtower = test_utils::TestChainMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8426 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8429 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8430 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8432 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8434 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8435 assert_eq!(txn.len(), 2);
8439 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8440 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8441 let watchtower_bob = {
8442 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8443 let monitor = monitors.get(&outpoint).unwrap();
8444 let mut w = test_utils::TestVecWriter(Vec::new());
8445 monitor.write_for_disk(&mut w).unwrap();
8446 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8447 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8448 assert!(new_monitor == *monitor);
8449 let watchtower = test_utils::TestChainMonitor::new(&chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8450 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8453 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8454 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8456 // Route another payment to generate another update with still previous HTLC pending
8457 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8459 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8460 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();
8461 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8463 check_added_monitors!(nodes[1], 1);
8465 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8466 assert_eq!(updates.update_add_htlcs.len(), 1);
8467 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8468 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8469 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8470 // Watchtower Alice should already have seen the block and reject the update
8471 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8472 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8473 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8474 } else { assert!(false); }
8475 } else { assert!(false); };
8476 // Our local monitor is in-sync and hasn't processed yet timeout
8477 check_added_monitors!(nodes[0], 1);
8479 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8480 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8482 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8485 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8486 assert_eq!(txn.len(), 2);
8487 bob_state_y = txn[0].clone();
8491 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8492 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8494 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8495 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8496 // the onchain detection of the HTLC output
8497 assert_eq!(htlc_txn.len(), 2);
8498 check_spends!(htlc_txn[0], bob_state_y);
8499 check_spends!(htlc_txn[1], bob_state_y);