1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
14 use chain::transaction::OutPoint;
15 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
16 use chain::chaininterface;
17 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
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, ManyChannelMonitor, 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());
420 assert!(nodes[0].chain_monitor.does_match_tx(&tx));
421 assert!(nodes[1].chain_monitor.does_match_tx(&tx));
423 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
424 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version as usize; 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 nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version as usize; 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{
450 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
451 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
452 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
455 if steps & 0x0f == 0 { return; }
456 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
457 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
459 if steps & 0x0f == 1 { return; }
460 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
461 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
463 if steps & 0x0f == 2 { return; }
464 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
466 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
468 if steps & 0x0f == 3 { return; }
469 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
470 check_added_monitors!(nodes[0], 0);
471 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
473 if steps & 0x0f == 4 { return; }
474 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
476 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
477 assert_eq!(added_monitors.len(), 1);
478 assert_eq!(added_monitors[0].0, funding_output);
479 added_monitors.clear();
481 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
483 if steps & 0x0f == 5 { return; }
484 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
486 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
487 assert_eq!(added_monitors.len(), 1);
488 assert_eq!(added_monitors[0].0, funding_output);
489 added_monitors.clear();
492 let events_4 = nodes[0].node.get_and_clear_pending_events();
493 assert_eq!(events_4.len(), 1);
495 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
496 assert_eq!(user_channel_id, 42);
497 assert_eq!(*funding_txo, funding_output);
499 _ => panic!("Unexpected event"),
502 if steps & 0x0f == 6 { return; }
503 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
505 if steps & 0x0f == 7 { return; }
506 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
507 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
511 fn test_sanity_on_in_flight_opens() {
512 do_test_sanity_on_in_flight_opens(0);
513 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
514 do_test_sanity_on_in_flight_opens(1);
515 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(2);
517 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
518 do_test_sanity_on_in_flight_opens(3);
519 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(4);
521 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(5);
523 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(6);
525 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(7);
527 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
528 do_test_sanity_on_in_flight_opens(8);
529 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
533 fn test_update_fee_vanilla() {
534 let chanmon_cfgs = create_chanmon_cfgs(2);
535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
537 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
538 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
539 let channel_id = chan.2;
541 let feerate = get_feerate!(nodes[0], channel_id);
542 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
543 check_added_monitors!(nodes[0], 1);
545 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
546 assert_eq!(events_0.len(), 1);
547 let (update_msg, commitment_signed) = match events_0[0] {
548 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 } } => {
549 (update_fee.as_ref(), commitment_signed)
551 _ => panic!("Unexpected event"),
553 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
555 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
556 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
557 check_added_monitors!(nodes[1], 1);
559 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
560 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
561 check_added_monitors!(nodes[0], 1);
563 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
564 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
565 // No commitment_signed so get_event_msg's assert(len == 1) passes
566 check_added_monitors!(nodes[0], 1);
568 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
569 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
570 check_added_monitors!(nodes[1], 1);
574 fn test_update_fee_that_funder_cannot_afford() {
575 let chanmon_cfgs = create_chanmon_cfgs(2);
576 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
577 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
578 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
579 let channel_value = 1888;
580 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
581 let channel_id = chan.2;
584 nodes[0].node.update_fee(channel_id, feerate).unwrap();
585 check_added_monitors!(nodes[0], 1);
586 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
588 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
590 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
592 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
593 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
595 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
597 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
598 let num_htlcs = commitment_tx.output.len() - 2;
599 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
600 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
601 actual_fee = channel_value - actual_fee;
602 assert_eq!(total_fee, actual_fee);
605 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
606 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
607 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
608 check_added_monitors!(nodes[0], 1);
610 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
612 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
614 //While producing the commitment_signed response after handling a received update_fee request the
615 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
616 //Should produce and error.
617 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
618 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
619 check_added_monitors!(nodes[1], 1);
620 check_closed_broadcast!(nodes[1], true);
624 fn test_update_fee_with_fundee_update_add_htlc() {
625 let chanmon_cfgs = create_chanmon_cfgs(2);
626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
628 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
629 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
630 let channel_id = chan.2;
631 let logger = test_utils::TestLogger::new();
634 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
636 let feerate = get_feerate!(nodes[0], channel_id);
637 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
638 check_added_monitors!(nodes[0], 1);
640 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
641 assert_eq!(events_0.len(), 1);
642 let (update_msg, commitment_signed) = match events_0[0] {
643 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 } } => {
644 (update_fee.as_ref(), commitment_signed)
646 _ => panic!("Unexpected event"),
648 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
649 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
650 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
651 check_added_monitors!(nodes[1], 1);
653 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
654 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
655 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();
657 // nothing happens since node[1] is in AwaitingRemoteRevoke
658 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
660 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
661 assert_eq!(added_monitors.len(), 0);
662 added_monitors.clear();
664 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
665 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
666 // node[1] has nothing to do
668 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
669 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
670 check_added_monitors!(nodes[0], 1);
672 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
673 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
674 // No commitment_signed so get_event_msg's assert(len == 1) passes
675 check_added_monitors!(nodes[0], 1);
676 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
677 check_added_monitors!(nodes[1], 1);
678 // AwaitingRemoteRevoke ends here
680 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
681 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
682 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
683 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
684 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
685 assert_eq!(commitment_update.update_fee.is_none(), true);
687 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
688 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
689 check_added_monitors!(nodes[0], 1);
690 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
692 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
693 check_added_monitors!(nodes[1], 1);
694 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
696 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
697 check_added_monitors!(nodes[1], 1);
698 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
699 // No commitment_signed so get_event_msg's assert(len == 1) passes
701 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
702 check_added_monitors!(nodes[0], 1);
703 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
705 expect_pending_htlcs_forwardable!(nodes[0]);
707 let events = nodes[0].node.get_and_clear_pending_events();
708 assert_eq!(events.len(), 1);
710 Event::PaymentReceived { .. } => { },
711 _ => panic!("Unexpected event"),
714 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
716 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
717 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
718 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
722 fn test_update_fee() {
723 let chanmon_cfgs = create_chanmon_cfgs(2);
724 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
725 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
726 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
727 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
728 let channel_id = chan.2;
731 // (1) update_fee/commitment_signed ->
732 // <- (2) revoke_and_ack
733 // .- send (3) commitment_signed
734 // (4) update_fee/commitment_signed ->
735 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
736 // <- (3) commitment_signed delivered
737 // send (6) revoke_and_ack -.
738 // <- (5) deliver revoke_and_ack
739 // (6) deliver revoke_and_ack ->
740 // .- send (7) commitment_signed in response to (4)
741 // <- (7) deliver commitment_signed
744 // Create and deliver (1)...
745 let feerate = get_feerate!(nodes[0], channel_id);
746 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
747 check_added_monitors!(nodes[0], 1);
749 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
750 assert_eq!(events_0.len(), 1);
751 let (update_msg, commitment_signed) = match events_0[0] {
752 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 } } => {
753 (update_fee.as_ref(), commitment_signed)
755 _ => panic!("Unexpected event"),
757 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
759 // Generate (2) and (3):
760 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
761 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
762 check_added_monitors!(nodes[1], 1);
765 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
766 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
767 check_added_monitors!(nodes[0], 1);
769 // Create and deliver (4)...
770 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
771 check_added_monitors!(nodes[0], 1);
772 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
773 assert_eq!(events_0.len(), 1);
774 let (update_msg, commitment_signed) = match events_0[0] {
775 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 } } => {
776 (update_fee.as_ref(), commitment_signed)
778 _ => panic!("Unexpected event"),
781 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
782 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
783 check_added_monitors!(nodes[1], 1);
785 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
786 // No commitment_signed so get_event_msg's assert(len == 1) passes
788 // Handle (3), creating (6):
789 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
790 check_added_monitors!(nodes[0], 1);
791 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
792 // No commitment_signed so get_event_msg's assert(len == 1) passes
795 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
796 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
797 check_added_monitors!(nodes[0], 1);
799 // Deliver (6), creating (7):
800 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
801 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
802 assert!(commitment_update.update_add_htlcs.is_empty());
803 assert!(commitment_update.update_fulfill_htlcs.is_empty());
804 assert!(commitment_update.update_fail_htlcs.is_empty());
805 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
806 assert!(commitment_update.update_fee.is_none());
807 check_added_monitors!(nodes[1], 1);
810 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
811 check_added_monitors!(nodes[0], 1);
812 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
813 // No commitment_signed so get_event_msg's assert(len == 1) passes
815 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
816 check_added_monitors!(nodes[1], 1);
817 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
819 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
820 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
821 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
825 fn pre_funding_lock_shutdown_test() {
826 // Test sending a shutdown prior to funding_locked after funding generation
827 let chanmon_cfgs = create_chanmon_cfgs(2);
828 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
829 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
830 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
831 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
832 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
833 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
834 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
836 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
837 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
838 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
839 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
840 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
842 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
843 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
844 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
845 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
846 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
847 assert!(node_0_none.is_none());
849 assert!(nodes[0].node.list_channels().is_empty());
850 assert!(nodes[1].node.list_channels().is_empty());
854 fn updates_shutdown_wait() {
855 // Test sending a shutdown with outstanding updates pending
856 let chanmon_cfgs = create_chanmon_cfgs(3);
857 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
858 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
859 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
860 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
861 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
862 let logger = test_utils::TestLogger::new();
864 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
866 nodes[0].node.close_channel(&chan_1.2).unwrap();
867 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
868 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
869 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
870 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
872 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
873 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
875 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
877 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
878 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
879 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();
880 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();
881 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
882 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
884 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
885 check_added_monitors!(nodes[2], 1);
886 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
887 assert!(updates.update_add_htlcs.is_empty());
888 assert!(updates.update_fail_htlcs.is_empty());
889 assert!(updates.update_fail_malformed_htlcs.is_empty());
890 assert!(updates.update_fee.is_none());
891 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
892 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
893 check_added_monitors!(nodes[1], 1);
894 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
895 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
897 assert!(updates_2.update_add_htlcs.is_empty());
898 assert!(updates_2.update_fail_htlcs.is_empty());
899 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
900 assert!(updates_2.update_fee.is_none());
901 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
902 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
903 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
905 let events = nodes[0].node.get_and_clear_pending_events();
906 assert_eq!(events.len(), 1);
908 Event::PaymentSent { ref payment_preimage } => {
909 assert_eq!(our_payment_preimage, *payment_preimage);
911 _ => panic!("Unexpected event"),
914 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
915 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
916 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
917 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
918 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
919 assert!(node_0_none.is_none());
921 assert!(nodes[0].node.list_channels().is_empty());
923 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
924 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
925 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
926 assert!(nodes[1].node.list_channels().is_empty());
927 assert!(nodes[2].node.list_channels().is_empty());
931 fn htlc_fail_async_shutdown() {
932 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
933 let chanmon_cfgs = create_chanmon_cfgs(3);
934 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
935 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
936 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
937 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
938 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
939 let logger = test_utils::TestLogger::new();
941 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
942 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
943 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();
944 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
945 check_added_monitors!(nodes[0], 1);
946 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
947 assert_eq!(updates.update_add_htlcs.len(), 1);
948 assert!(updates.update_fulfill_htlcs.is_empty());
949 assert!(updates.update_fail_htlcs.is_empty());
950 assert!(updates.update_fail_malformed_htlcs.is_empty());
951 assert!(updates.update_fee.is_none());
953 nodes[1].node.close_channel(&chan_1.2).unwrap();
954 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
955 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
956 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
958 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
959 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
960 check_added_monitors!(nodes[1], 1);
961 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
962 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
964 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
965 assert!(updates_2.update_add_htlcs.is_empty());
966 assert!(updates_2.update_fulfill_htlcs.is_empty());
967 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
968 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
969 assert!(updates_2.update_fee.is_none());
971 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
972 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
974 expect_payment_failed!(nodes[0], our_payment_hash, false);
976 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
977 assert_eq!(msg_events.len(), 2);
978 let node_0_closing_signed = match msg_events[0] {
979 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
980 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
983 _ => panic!("Unexpected event"),
985 match msg_events[1] {
986 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
987 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
989 _ => panic!("Unexpected event"),
992 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
993 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
994 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
995 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
996 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
997 assert!(node_0_none.is_none());
999 assert!(nodes[0].node.list_channels().is_empty());
1001 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1002 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1003 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1004 assert!(nodes[1].node.list_channels().is_empty());
1005 assert!(nodes[2].node.list_channels().is_empty());
1008 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1009 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1010 // messages delivered prior to disconnect
1011 let chanmon_cfgs = create_chanmon_cfgs(3);
1012 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1013 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1014 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1015 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1016 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1018 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1020 nodes[1].node.close_channel(&chan_1.2).unwrap();
1021 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1023 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1024 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1026 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1030 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1031 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1033 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1034 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1035 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1038 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1039 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1040 assert!(node_1_shutdown == node_1_2nd_shutdown);
1042 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1043 let node_0_2nd_shutdown = if recv_count > 0 {
1044 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1045 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1048 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1049 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1050 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1052 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1054 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1055 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1057 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1058 check_added_monitors!(nodes[2], 1);
1059 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1060 assert!(updates.update_add_htlcs.is_empty());
1061 assert!(updates.update_fail_htlcs.is_empty());
1062 assert!(updates.update_fail_malformed_htlcs.is_empty());
1063 assert!(updates.update_fee.is_none());
1064 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1065 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1066 check_added_monitors!(nodes[1], 1);
1067 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1068 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1070 assert!(updates_2.update_add_htlcs.is_empty());
1071 assert!(updates_2.update_fail_htlcs.is_empty());
1072 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1073 assert!(updates_2.update_fee.is_none());
1074 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1075 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1076 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1078 let events = nodes[0].node.get_and_clear_pending_events();
1079 assert_eq!(events.len(), 1);
1081 Event::PaymentSent { ref payment_preimage } => {
1082 assert_eq!(our_payment_preimage, *payment_preimage);
1084 _ => panic!("Unexpected event"),
1087 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1089 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1090 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1091 assert!(node_1_closing_signed.is_some());
1094 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1095 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1097 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1098 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1099 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100 if recv_count == 0 {
1101 // If all closing_signeds weren't delivered we can just resume where we left off...
1102 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1104 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1105 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1106 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1108 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1109 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1110 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1112 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1113 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1115 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1116 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1117 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1119 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1120 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1121 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1122 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1123 assert!(node_0_none.is_none());
1125 // If one node, however, received + responded with an identical closing_signed we end
1126 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1127 // There isn't really anything better we can do simply, but in the future we might
1128 // explore storing a set of recently-closed channels that got disconnected during
1129 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1130 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1132 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1134 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1135 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1136 assert_eq!(msg_events.len(), 1);
1137 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1139 &ErrorAction::SendErrorMessage { ref msg } => {
1140 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1141 assert_eq!(msg.channel_id, chan_1.2);
1143 _ => panic!("Unexpected event!"),
1145 } else { panic!("Needed SendErrorMessage close"); }
1147 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1148 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1149 // closing_signed so we do it ourselves
1150 check_closed_broadcast!(nodes[0], false);
1151 check_added_monitors!(nodes[0], 1);
1154 assert!(nodes[0].node.list_channels().is_empty());
1156 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1157 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1158 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1159 assert!(nodes[1].node.list_channels().is_empty());
1160 assert!(nodes[2].node.list_channels().is_empty());
1164 fn test_shutdown_rebroadcast() {
1165 do_test_shutdown_rebroadcast(0);
1166 do_test_shutdown_rebroadcast(1);
1167 do_test_shutdown_rebroadcast(2);
1171 fn fake_network_test() {
1172 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1173 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1174 let chanmon_cfgs = create_chanmon_cfgs(4);
1175 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1176 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1177 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1179 // Create some initial channels
1180 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1181 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1182 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1184 // Rebalance the network a bit by relaying one payment through all the channels...
1185 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1186 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1190 // Send some more payments
1191 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1192 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1193 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1195 // Test failure packets
1196 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1197 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1199 // Add a new channel that skips 3
1200 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1202 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1203 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1204 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1205 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1206 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1210 // Do some rebalance loop payments, simultaneously
1211 let mut hops = Vec::with_capacity(3);
1212 hops.push(RouteHop {
1213 pubkey: nodes[2].node.get_our_node_id(),
1214 node_features: NodeFeatures::empty(),
1215 short_channel_id: chan_2.0.contents.short_channel_id,
1216 channel_features: ChannelFeatures::empty(),
1218 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1220 hops.push(RouteHop {
1221 pubkey: nodes[3].node.get_our_node_id(),
1222 node_features: NodeFeatures::empty(),
1223 short_channel_id: chan_3.0.contents.short_channel_id,
1224 channel_features: ChannelFeatures::empty(),
1226 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1228 hops.push(RouteHop {
1229 pubkey: nodes[1].node.get_our_node_id(),
1230 node_features: NodeFeatures::empty(),
1231 short_channel_id: chan_4.0.contents.short_channel_id,
1232 channel_features: ChannelFeatures::empty(),
1234 cltv_expiry_delta: TEST_FINAL_CLTV,
1236 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;
1237 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;
1238 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1240 let mut hops = Vec::with_capacity(3);
1241 hops.push(RouteHop {
1242 pubkey: nodes[3].node.get_our_node_id(),
1243 node_features: NodeFeatures::empty(),
1244 short_channel_id: chan_4.0.contents.short_channel_id,
1245 channel_features: ChannelFeatures::empty(),
1247 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1249 hops.push(RouteHop {
1250 pubkey: nodes[2].node.get_our_node_id(),
1251 node_features: NodeFeatures::empty(),
1252 short_channel_id: chan_3.0.contents.short_channel_id,
1253 channel_features: ChannelFeatures::empty(),
1255 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1257 hops.push(RouteHop {
1258 pubkey: nodes[1].node.get_our_node_id(),
1259 node_features: NodeFeatures::empty(),
1260 short_channel_id: chan_2.0.contents.short_channel_id,
1261 channel_features: ChannelFeatures::empty(),
1263 cltv_expiry_delta: TEST_FINAL_CLTV,
1265 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;
1266 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;
1267 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1269 // Claim the rebalances...
1270 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1271 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1273 // Add a duplicate new channel from 2 to 4
1274 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1276 // Send some payments across both channels
1277 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1278 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1282 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1283 let events = nodes[0].node.get_and_clear_pending_msg_events();
1284 assert_eq!(events.len(), 0);
1285 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);
1287 //TODO: Test that routes work again here as we've been notified that the channel is full
1289 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1290 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1291 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1293 // Close down the channels...
1294 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1295 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1296 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1297 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1298 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1302 fn holding_cell_htlc_counting() {
1303 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1304 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1305 // commitment dance rounds.
1306 let chanmon_cfgs = create_chanmon_cfgs(3);
1307 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1308 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1309 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1310 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1311 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1312 let logger = test_utils::TestLogger::new();
1314 let mut payments = Vec::new();
1315 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1316 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1317 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1318 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();
1319 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1320 payments.push((payment_preimage, payment_hash));
1322 check_added_monitors!(nodes[1], 1);
1324 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1325 assert_eq!(events.len(), 1);
1326 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1327 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1329 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1330 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1332 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1334 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1335 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();
1336 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1337 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1338 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1339 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1342 // This should also be true if we try to forward a payment.
1343 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1345 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1346 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();
1347 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1348 check_added_monitors!(nodes[0], 1);
1351 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1352 assert_eq!(events.len(), 1);
1353 let payment_event = SendEvent::from_event(events.pop().unwrap());
1354 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1356 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1357 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1358 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1359 // fails), the second will process the resulting failure and fail the HTLC backward.
1360 expect_pending_htlcs_forwardable!(nodes[1]);
1361 expect_pending_htlcs_forwardable!(nodes[1]);
1362 check_added_monitors!(nodes[1], 1);
1364 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1365 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1366 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1368 let events = nodes[0].node.get_and_clear_pending_msg_events();
1369 assert_eq!(events.len(), 1);
1371 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1372 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1374 _ => panic!("Unexpected event"),
1377 expect_payment_failed!(nodes[0], payment_hash_2, false);
1379 // Now forward all the pending HTLCs and claim them back
1380 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1381 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1382 check_added_monitors!(nodes[2], 1);
1384 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1385 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1386 check_added_monitors!(nodes[1], 1);
1387 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1389 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1390 check_added_monitors!(nodes[1], 1);
1391 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1393 for ref update in as_updates.update_add_htlcs.iter() {
1394 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1396 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1397 check_added_monitors!(nodes[2], 1);
1398 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1399 check_added_monitors!(nodes[2], 1);
1400 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1402 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1403 check_added_monitors!(nodes[1], 1);
1404 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1405 check_added_monitors!(nodes[1], 1);
1406 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1408 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1409 check_added_monitors!(nodes[2], 1);
1411 expect_pending_htlcs_forwardable!(nodes[2]);
1413 let events = nodes[2].node.get_and_clear_pending_events();
1414 assert_eq!(events.len(), payments.len());
1415 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1417 &Event::PaymentReceived { ref payment_hash, .. } => {
1418 assert_eq!(*payment_hash, *hash);
1420 _ => panic!("Unexpected event"),
1424 for (preimage, _) in payments.drain(..) {
1425 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1428 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1432 fn duplicate_htlc_test() {
1433 // Test that we accept duplicate payment_hash HTLCs across the network and that
1434 // claiming/failing them are all separate and don't affect each other
1435 let chanmon_cfgs = create_chanmon_cfgs(6);
1436 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1437 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1438 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1440 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1441 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1442 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1443 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1444 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1445 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1447 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1449 *nodes[0].network_payment_count.borrow_mut() -= 1;
1450 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1452 *nodes[0].network_payment_count.borrow_mut() -= 1;
1453 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1455 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1456 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1457 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1461 fn test_duplicate_htlc_different_direction_onchain() {
1462 // Test that ChannelMonitor doesn't generate 2 preimage txn
1463 // when we have 2 HTLCs with same preimage that go across a node
1464 // in opposite directions.
1465 let chanmon_cfgs = create_chanmon_cfgs(2);
1466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1468 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1470 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1471 let logger = test_utils::TestLogger::new();
1474 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1476 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1478 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1479 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();
1480 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1482 // Provide preimage to node 0 by claiming payment
1483 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1484 check_added_monitors!(nodes[0], 1);
1486 // Broadcast node 1 commitment txn
1487 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1489 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1490 let mut has_both_htlcs = 0; // check htlcs match ones committed
1491 for outp in remote_txn[0].output.iter() {
1492 if outp.value == 800_000 / 1000 {
1493 has_both_htlcs += 1;
1494 } else if outp.value == 900_000 / 1000 {
1495 has_both_htlcs += 1;
1498 assert_eq!(has_both_htlcs, 2);
1500 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1501 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1502 check_added_monitors!(nodes[0], 1);
1504 // Check we only broadcast 1 timeout tx
1505 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1506 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()) };
1507 assert_eq!(claim_txn.len(), 5);
1508 check_spends!(claim_txn[2], chan_1.3);
1509 check_spends!(claim_txn[3], claim_txn[2]);
1510 assert_eq!(htlc_pair.0.input.len(), 1);
1511 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1512 check_spends!(htlc_pair.0, remote_txn[0]);
1513 assert_eq!(htlc_pair.1.input.len(), 1);
1514 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1515 check_spends!(htlc_pair.1, remote_txn[0]);
1517 let events = nodes[0].node.get_and_clear_pending_msg_events();
1518 assert_eq!(events.len(), 2);
1521 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1522 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, .. } } => {
1523 assert!(update_add_htlcs.is_empty());
1524 assert!(update_fail_htlcs.is_empty());
1525 assert_eq!(update_fulfill_htlcs.len(), 1);
1526 assert!(update_fail_malformed_htlcs.is_empty());
1527 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1529 _ => panic!("Unexpected event"),
1535 fn test_basic_channel_reserve() {
1536 let chanmon_cfgs = create_chanmon_cfgs(2);
1537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1539 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1540 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1541 let logger = test_utils::TestLogger::new();
1543 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1544 let channel_reserve = chan_stat.channel_reserve_msat;
1546 // The 2* and +1 are for the fee spike reserve.
1547 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1548 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1549 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1550 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1551 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();
1552 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1554 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1556 &APIError::ChannelUnavailable{ref err} =>
1557 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1558 _ => panic!("Unexpected error variant"),
1561 _ => panic!("Unexpected error variant"),
1563 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1564 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);
1566 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1570 fn test_fee_spike_violation_fails_htlc() {
1571 let chanmon_cfgs = create_chanmon_cfgs(2);
1572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1574 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1575 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1576 let logger = test_utils::TestLogger::new();
1578 macro_rules! get_route_and_payment_hash {
1579 ($recv_value: expr) => {{
1580 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1581 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1582 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();
1583 (route, payment_hash, payment_preimage)
1587 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1588 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1589 let secp_ctx = Secp256k1::new();
1590 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1592 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1594 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1595 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1596 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1597 let msg = msgs::UpdateAddHTLC {
1600 amount_msat: htlc_msat,
1601 payment_hash: payment_hash,
1602 cltv_expiry: htlc_cltv,
1603 onion_routing_packet: onion_packet,
1606 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1608 // Now manually create the commitment_signed message corresponding to the update_add
1609 // nodes[0] just sent. In the code for construction of this message, "local" refers
1610 // to the sender of the message, and "remote" refers to the receiver.
1612 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1614 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1616 // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1617 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1618 let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1619 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1620 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1621 let chan_keys = local_chan.get_keys();
1622 let pubkeys = chan_keys.pubkeys();
1623 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1624 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1626 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1627 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1628 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1629 let chan_keys = remote_chan.get_keys();
1630 let pubkeys = chan_keys.pubkeys();
1631 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1632 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1635 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1636 let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1637 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1638 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1639 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1641 // Build the remote commitment transaction so we can sign it, and then later use the
1642 // signature for the commitment_signed message.
1643 let local_chan_balance = 1313;
1644 let static_payment_pk = local_payment_point.serialize();
1645 let remote_commit_tx_output = TxOut {
1646 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1647 .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1649 value: local_chan_balance as u64
1652 let local_commit_tx_output = TxOut {
1653 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1655 &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1659 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1661 amount_msat: 3460001,
1662 cltv_expiry: htlc_cltv,
1663 payment_hash: payment_hash,
1664 transaction_output_index: Some(1),
1667 let htlc_output = TxOut {
1668 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1669 value: 3460001 / 1000
1672 let commit_tx_obscure_factor = {
1673 let mut sha = Sha256::engine();
1674 let remote_payment_point = &remote_payment_point.serialize();
1675 sha.input(&local_payment_point.serialize());
1676 sha.input(remote_payment_point);
1677 let res = Sha256::from_engine(sha).into_inner();
1679 ((res[26] as u64) << 5*8) |
1680 ((res[27] as u64) << 4*8) |
1681 ((res[28] as u64) << 3*8) |
1682 ((res[29] as u64) << 2*8) |
1683 ((res[30] as u64) << 1*8) |
1684 ((res[31] as u64) << 0*8)
1686 let commitment_number = 1;
1687 let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1688 let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1690 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1691 script_sig: Script::new(),
1692 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1693 witness: Vec::new(),
1696 let commit_tx = Transaction {
1700 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1703 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1704 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1705 let local_chan_keys = local_chan.get_keys();
1706 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1707 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1710 let commit_signed_msg = msgs::CommitmentSigned {
1713 htlc_signatures: res.1
1716 // Send the commitment_signed message to the nodes[1].
1717 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1718 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1720 // Send the RAA to nodes[1].
1721 let per_commitment_secret = local_secret;
1722 let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1723 let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1724 let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1725 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1727 let events = nodes[1].node.get_and_clear_pending_msg_events();
1728 assert_eq!(events.len(), 1);
1729 // Make sure the HTLC failed in the way we expect.
1731 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1732 assert_eq!(update_fail_htlcs.len(), 1);
1733 update_fail_htlcs[0].clone()
1735 _ => panic!("Unexpected event"),
1737 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1739 check_added_monitors!(nodes[1], 2);
1743 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1744 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1745 // Set the fee rate for the channel very high, to the point where the fundee
1746 // sending any amount would result in a channel reserve violation. In this test
1747 // we check that we would be prevented from sending an HTLC in this situation.
1748 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1749 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1752 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1753 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1754 let logger = test_utils::TestLogger::new();
1756 macro_rules! get_route_and_payment_hash {
1757 ($recv_value: expr) => {{
1758 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1759 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1760 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();
1761 (route, payment_hash, payment_preimage)
1765 let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1766 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1767 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1768 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1769 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);
1773 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1774 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1775 // Set the fee rate for the channel very high, to the point where the funder
1776 // receiving 1 update_add_htlc would result in them closing the channel due
1777 // to channel reserve violation. This close could also happen if the fee went
1778 // up a more realistic amount, but many HTLCs were outstanding at the time of
1779 // the update_add_htlc.
1780 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1781 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1782 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1783 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1784 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1785 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1786 let logger = test_utils::TestLogger::new();
1788 macro_rules! get_route_and_payment_hash {
1789 ($recv_value: expr) => {{
1790 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1791 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1792 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();
1793 (route, payment_hash, payment_preimage)
1797 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1798 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1799 let secp_ctx = Secp256k1::new();
1800 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1801 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1802 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1803 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1804 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1805 let msg = msgs::UpdateAddHTLC {
1808 amount_msat: htlc_msat + 1,
1809 payment_hash: payment_hash,
1810 cltv_expiry: htlc_cltv,
1811 onion_routing_packet: onion_packet,
1814 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1815 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1816 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);
1817 assert_eq!(nodes[0].node.list_channels().len(), 0);
1818 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1819 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1820 check_added_monitors!(nodes[0], 1);
1824 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1825 let chanmon_cfgs = create_chanmon_cfgs(3);
1826 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1827 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1828 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1829 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1830 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1831 let logger = test_utils::TestLogger::new();
1833 macro_rules! get_route_and_payment_hash {
1834 ($recv_value: expr) => {{
1835 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1836 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1837 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();
1838 (route, payment_hash, payment_preimage)
1843 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1844 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1845 let feerate = get_feerate!(nodes[0], chan.2);
1847 // Add a 2* and +1 for the fee spike reserve.
1848 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1849 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;
1850 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1852 // Add a pending HTLC.
1853 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1854 let payment_event_1 = {
1855 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1856 check_added_monitors!(nodes[0], 1);
1858 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1859 assert_eq!(events.len(), 1);
1860 SendEvent::from_event(events.remove(0))
1862 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1864 // Attempt to trigger a channel reserve violation --> payment failure.
1865 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1866 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;
1867 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1868 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1870 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1871 let secp_ctx = Secp256k1::new();
1872 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1873 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1874 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1875 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1876 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1877 let msg = msgs::UpdateAddHTLC {
1880 amount_msat: htlc_msat + 1,
1881 payment_hash: our_payment_hash_1,
1882 cltv_expiry: htlc_cltv,
1883 onion_routing_packet: onion_packet,
1886 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1887 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1888 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1889 assert_eq!(nodes[1].node.list_channels().len(), 1);
1890 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1891 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1892 check_added_monitors!(nodes[1], 1);
1896 fn test_inbound_outbound_capacity_is_not_zero() {
1897 let chanmon_cfgs = create_chanmon_cfgs(2);
1898 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1899 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1900 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1901 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1902 let channels0 = node_chanmgrs[0].list_channels();
1903 let channels1 = node_chanmgrs[1].list_channels();
1904 assert_eq!(channels0.len(), 1);
1905 assert_eq!(channels1.len(), 1);
1907 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1908 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1910 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1911 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1914 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1915 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1919 fn test_channel_reserve_holding_cell_htlcs() {
1920 let chanmon_cfgs = create_chanmon_cfgs(3);
1921 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1922 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1923 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1924 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1925 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1926 let logger = test_utils::TestLogger::new();
1928 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1929 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1931 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1932 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1934 macro_rules! get_route_and_payment_hash {
1935 ($recv_value: expr) => {{
1936 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1937 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1938 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();
1939 (route, payment_hash, payment_preimage)
1943 macro_rules! expect_forward {
1945 let mut events = $node.node.get_and_clear_pending_msg_events();
1946 assert_eq!(events.len(), 1);
1947 check_added_monitors!($node, 1);
1948 let payment_event = SendEvent::from_event(events.remove(0));
1953 let feemsat = 239; // somehow we know?
1954 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1955 let feerate = get_feerate!(nodes[0], chan_1.2);
1957 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1959 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1961 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1962 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1963 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1964 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)));
1965 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1966 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);
1969 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1970 // nodes[0]'s wealth
1972 let amt_msat = recv_value_0 + total_fee_msat;
1973 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1974 // Also, ensure that each payment has enough to be over the dust limit to
1975 // ensure it'll be included in each commit tx fee calculation.
1976 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1977 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1978 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1981 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1983 let (stat01_, stat11_, stat12_, stat22_) = (
1984 get_channel_value_stat!(nodes[0], chan_1.2),
1985 get_channel_value_stat!(nodes[1], chan_1.2),
1986 get_channel_value_stat!(nodes[1], chan_2.2),
1987 get_channel_value_stat!(nodes[2], chan_2.2),
1990 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1991 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1992 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1993 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1994 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1997 // adding pending output.
1998 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1999 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2000 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2001 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2002 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2003 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2004 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2005 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2006 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2008 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2009 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2010 let amt_msat_1 = recv_value_1 + total_fee_msat;
2012 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2013 let payment_event_1 = {
2014 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2015 check_added_monitors!(nodes[0], 1);
2017 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2018 assert_eq!(events.len(), 1);
2019 SendEvent::from_event(events.remove(0))
2021 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2023 // channel reserve test with htlc pending output > 0
2024 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2026 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2027 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2028 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2029 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2032 // split the rest to test holding cell
2033 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2034 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2035 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2036 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2038 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2039 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);
2042 // now see if they go through on both sides
2043 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2044 // but this will stuck in the holding cell
2045 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2046 check_added_monitors!(nodes[0], 0);
2047 let events = nodes[0].node.get_and_clear_pending_events();
2048 assert_eq!(events.len(), 0);
2050 // test with outbound holding cell amount > 0
2052 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2053 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2054 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2055 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2056 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);
2059 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2060 // this will also stuck in the holding cell
2061 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2062 check_added_monitors!(nodes[0], 0);
2063 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2064 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2066 // flush the pending htlc
2067 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2068 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2069 check_added_monitors!(nodes[1], 1);
2071 // the pending htlc should be promoted to committed
2072 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2073 check_added_monitors!(nodes[0], 1);
2074 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2076 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2077 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2078 // No commitment_signed so get_event_msg's assert(len == 1) passes
2079 check_added_monitors!(nodes[0], 1);
2081 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2082 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2083 check_added_monitors!(nodes[1], 1);
2085 expect_pending_htlcs_forwardable!(nodes[1]);
2087 let ref payment_event_11 = expect_forward!(nodes[1]);
2088 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2089 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2091 expect_pending_htlcs_forwardable!(nodes[2]);
2092 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2094 // flush the htlcs in the holding cell
2095 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2096 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2097 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2098 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2099 expect_pending_htlcs_forwardable!(nodes[1]);
2101 let ref payment_event_3 = expect_forward!(nodes[1]);
2102 assert_eq!(payment_event_3.msgs.len(), 2);
2103 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2104 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2106 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2107 expect_pending_htlcs_forwardable!(nodes[2]);
2109 let events = nodes[2].node.get_and_clear_pending_events();
2110 assert_eq!(events.len(), 2);
2112 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2113 assert_eq!(our_payment_hash_21, *payment_hash);
2114 assert_eq!(*payment_secret, None);
2115 assert_eq!(recv_value_21, amt);
2117 _ => panic!("Unexpected event"),
2120 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2121 assert_eq!(our_payment_hash_22, *payment_hash);
2122 assert_eq!(None, *payment_secret);
2123 assert_eq!(recv_value_22, amt);
2125 _ => panic!("Unexpected event"),
2128 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2129 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2130 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2132 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2133 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2135 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2136 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2138 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2140 &APIError::ChannelUnavailable{ref err} =>
2141 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2142 _ => panic!("Unexpected error variant"),
2145 _ => panic!("Unexpected error variant"),
2147 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2148 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);
2151 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2153 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2154 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);
2155 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2156 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2157 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2159 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2160 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2164 fn channel_reserve_in_flight_removes() {
2165 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2166 // can send to its counterparty, but due to update ordering, the other side may not yet have
2167 // considered those HTLCs fully removed.
2168 // This tests that we don't count HTLCs which will not be included in the next remote
2169 // commitment transaction towards the reserve value (as it implies no commitment transaction
2170 // will be generated which violates the remote reserve value).
2171 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2173 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2174 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2175 // you only consider the value of the first HTLC, it may not),
2176 // * start routing a third HTLC from A to B,
2177 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2178 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2179 // * deliver the first fulfill from B
2180 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2182 // * deliver A's response CS and RAA.
2183 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2184 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2185 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2186 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2187 let chanmon_cfgs = create_chanmon_cfgs(2);
2188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2190 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2191 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2192 let logger = test_utils::TestLogger::new();
2194 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2195 // Route the first two HTLCs.
2196 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2197 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2199 // Start routing the third HTLC (this is just used to get everyone in the right state).
2200 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2202 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2203 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();
2204 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2205 check_added_monitors!(nodes[0], 1);
2206 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2207 assert_eq!(events.len(), 1);
2208 SendEvent::from_event(events.remove(0))
2211 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2212 // initial fulfill/CS.
2213 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2214 check_added_monitors!(nodes[1], 1);
2215 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2217 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2218 // remove the second HTLC when we send the HTLC back from B to A.
2219 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2220 check_added_monitors!(nodes[1], 1);
2221 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2223 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2224 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2225 check_added_monitors!(nodes[0], 1);
2226 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2227 expect_payment_sent!(nodes[0], payment_preimage_1);
2229 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2230 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2231 check_added_monitors!(nodes[1], 1);
2232 // B is already AwaitingRAA, so cant generate a CS here
2233 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2235 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2236 check_added_monitors!(nodes[1], 1);
2237 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2239 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2240 check_added_monitors!(nodes[0], 1);
2241 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2243 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2244 check_added_monitors!(nodes[1], 1);
2245 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2247 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2248 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2249 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2250 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2251 // on-chain as necessary).
2252 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2253 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2254 check_added_monitors!(nodes[0], 1);
2255 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2256 expect_payment_sent!(nodes[0], payment_preimage_2);
2258 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2259 check_added_monitors!(nodes[1], 1);
2260 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2262 expect_pending_htlcs_forwardable!(nodes[1]);
2263 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2265 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2266 // resolve the second HTLC from A's point of view.
2267 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2268 check_added_monitors!(nodes[0], 1);
2269 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2271 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2272 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2273 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2275 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2276 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();
2277 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2278 check_added_monitors!(nodes[1], 1);
2279 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2280 assert_eq!(events.len(), 1);
2281 SendEvent::from_event(events.remove(0))
2284 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2285 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2286 check_added_monitors!(nodes[0], 1);
2287 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2289 // Now just resolve all the outstanding messages/HTLCs for completeness...
2291 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2292 check_added_monitors!(nodes[1], 1);
2293 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2295 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2296 check_added_monitors!(nodes[1], 1);
2298 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2299 check_added_monitors!(nodes[0], 1);
2300 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2302 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2303 check_added_monitors!(nodes[1], 1);
2304 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2306 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2307 check_added_monitors!(nodes[0], 1);
2309 expect_pending_htlcs_forwardable!(nodes[0]);
2310 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2312 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2313 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2317 fn channel_monitor_network_test() {
2318 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2319 // tests that ChannelMonitor is able to recover from various states.
2320 let chanmon_cfgs = create_chanmon_cfgs(5);
2321 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2322 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2323 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2325 // Create some initial channels
2326 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2327 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2328 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2329 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2331 // Rebalance the network a bit by relaying one payment through all the channels...
2332 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2333 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2334 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2335 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2337 // Simple case with no pending HTLCs:
2338 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2339 check_added_monitors!(nodes[1], 1);
2341 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2342 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2343 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2344 check_added_monitors!(nodes[0], 1);
2345 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2347 get_announce_close_broadcast_events(&nodes, 0, 1);
2348 assert_eq!(nodes[0].node.list_channels().len(), 0);
2349 assert_eq!(nodes[1].node.list_channels().len(), 1);
2351 // One pending HTLC is discarded by the force-close:
2352 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2354 // Simple case of one pending HTLC to HTLC-Timeout
2355 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2356 check_added_monitors!(nodes[1], 1);
2358 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2359 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2360 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2361 check_added_monitors!(nodes[2], 1);
2362 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2364 get_announce_close_broadcast_events(&nodes, 1, 2);
2365 assert_eq!(nodes[1].node.list_channels().len(), 0);
2366 assert_eq!(nodes[2].node.list_channels().len(), 1);
2368 macro_rules! claim_funds {
2369 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2371 assert!($node.node.claim_funds($preimage, &None, $amount));
2372 check_added_monitors!($node, 1);
2374 let events = $node.node.get_and_clear_pending_msg_events();
2375 assert_eq!(events.len(), 1);
2377 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2378 assert!(update_add_htlcs.is_empty());
2379 assert!(update_fail_htlcs.is_empty());
2380 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2382 _ => panic!("Unexpected event"),
2388 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2389 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2390 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2391 check_added_monitors!(nodes[2], 1);
2392 let node2_commitment_txid;
2394 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2395 node2_commitment_txid = node_txn[0].txid();
2397 // Claim the payment on nodes[3], giving it knowledge of the preimage
2398 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2400 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2401 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2402 check_added_monitors!(nodes[3], 1);
2404 check_preimage_claim(&nodes[3], &node_txn);
2406 get_announce_close_broadcast_events(&nodes, 2, 3);
2407 assert_eq!(nodes[2].node.list_channels().len(), 0);
2408 assert_eq!(nodes[3].node.list_channels().len(), 1);
2410 { // Cheat and reset nodes[4]'s height to 1
2411 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2412 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2415 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2416 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2417 // One pending HTLC to time out:
2418 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2419 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2422 let (close_chan_update_1, close_chan_update_2) = {
2423 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2424 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2425 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2426 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2427 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2429 let events = nodes[3].node.get_and_clear_pending_msg_events();
2430 assert_eq!(events.len(), 1);
2431 let close_chan_update_1 = match events[0] {
2432 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2435 _ => panic!("Unexpected event"),
2437 check_added_monitors!(nodes[3], 1);
2439 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2441 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2442 node_txn.retain(|tx| {
2443 if tx.input[0].previous_output.txid == node2_commitment_txid {
2449 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2451 // Claim the payment on nodes[4], giving it knowledge of the preimage
2452 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2454 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2456 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2457 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2458 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2459 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2461 let events = nodes[4].node.get_and_clear_pending_msg_events();
2462 assert_eq!(events.len(), 1);
2463 let close_chan_update_2 = match events[0] {
2464 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2467 _ => panic!("Unexpected event"),
2469 check_added_monitors!(nodes[4], 1);
2470 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2472 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2473 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2475 check_preimage_claim(&nodes[4], &node_txn);
2476 (close_chan_update_1, close_chan_update_2)
2478 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2479 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2480 assert_eq!(nodes[3].node.list_channels().len(), 0);
2481 assert_eq!(nodes[4].node.list_channels().len(), 0);
2485 fn test_justice_tx() {
2486 // Test justice txn built on revoked HTLC-Success tx, against both sides
2487 let mut alice_config = UserConfig::default();
2488 alice_config.channel_options.announced_channel = true;
2489 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2490 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2491 let mut bob_config = UserConfig::default();
2492 bob_config.channel_options.announced_channel = true;
2493 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2494 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2495 let user_cfgs = [Some(alice_config), Some(bob_config)];
2496 let chanmon_cfgs = create_chanmon_cfgs(2);
2497 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2498 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2499 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2500 // Create some new channels:
2501 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2503 // A pending HTLC which will be revoked:
2504 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2505 // Get the will-be-revoked local txn from nodes[0]
2506 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2507 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2508 assert_eq!(revoked_local_txn[0].input.len(), 1);
2509 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2510 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2511 assert_eq!(revoked_local_txn[1].input.len(), 1);
2512 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2513 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2514 // Revoke the old state
2515 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2518 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2519 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2521 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2522 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2523 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2525 check_spends!(node_txn[0], revoked_local_txn[0]);
2526 node_txn.swap_remove(0);
2527 node_txn.truncate(1);
2529 check_added_monitors!(nodes[1], 1);
2530 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2532 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2533 // Verify broadcast of revoked HTLC-timeout
2534 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2535 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2536 check_added_monitors!(nodes[0], 1);
2537 // Broadcast revoked HTLC-timeout on node 1
2538 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2539 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2541 get_announce_close_broadcast_events(&nodes, 0, 1);
2543 assert_eq!(nodes[0].node.list_channels().len(), 0);
2544 assert_eq!(nodes[1].node.list_channels().len(), 0);
2546 // We test justice_tx build by A on B's revoked HTLC-Success tx
2547 // Create some new channels:
2548 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2550 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2554 // A pending HTLC which will be revoked:
2555 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2556 // Get the will-be-revoked local txn from B
2557 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2558 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2559 assert_eq!(revoked_local_txn[0].input.len(), 1);
2560 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2561 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2562 // Revoke the old state
2563 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2565 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2566 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2568 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2569 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2570 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2572 check_spends!(node_txn[0], revoked_local_txn[0]);
2573 node_txn.swap_remove(0);
2575 check_added_monitors!(nodes[0], 1);
2576 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2578 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2579 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2580 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2581 check_added_monitors!(nodes[1], 1);
2582 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2583 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2585 get_announce_close_broadcast_events(&nodes, 0, 1);
2586 assert_eq!(nodes[0].node.list_channels().len(), 0);
2587 assert_eq!(nodes[1].node.list_channels().len(), 0);
2591 fn revoked_output_claim() {
2592 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2593 // transaction is broadcast by its counterparty
2594 let chanmon_cfgs = create_chanmon_cfgs(2);
2595 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2596 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2597 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2598 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2599 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2600 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2601 assert_eq!(revoked_local_txn.len(), 1);
2602 // Only output is the full channel value back to nodes[0]:
2603 assert_eq!(revoked_local_txn[0].output.len(), 1);
2604 // Send a payment through, updating everyone's latest commitment txn
2605 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2607 // Inform nodes[1] that nodes[0] broadcast a stale tx
2608 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2609 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2610 check_added_monitors!(nodes[1], 1);
2611 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2612 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2614 check_spends!(node_txn[0], revoked_local_txn[0]);
2615 check_spends!(node_txn[1], chan_1.3);
2617 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2618 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2619 get_announce_close_broadcast_events(&nodes, 0, 1);
2620 check_added_monitors!(nodes[0], 1)
2624 fn claim_htlc_outputs_shared_tx() {
2625 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2626 let chanmon_cfgs = create_chanmon_cfgs(2);
2627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2629 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2631 // Create some new channel:
2632 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2634 // Rebalance the network to generate htlc in the two directions
2635 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2636 // 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
2637 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2638 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2640 // Get the will-be-revoked local txn from node[0]
2641 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2642 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2643 assert_eq!(revoked_local_txn[0].input.len(), 1);
2644 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2645 assert_eq!(revoked_local_txn[1].input.len(), 1);
2646 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2647 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2648 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2650 //Revoke the old state
2651 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2654 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2655 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2656 check_added_monitors!(nodes[0], 1);
2657 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2658 check_added_monitors!(nodes[1], 1);
2659 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2660 expect_payment_failed!(nodes[1], payment_hash_2, true);
2662 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2663 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2665 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2666 check_spends!(node_txn[0], revoked_local_txn[0]);
2668 let mut witness_lens = BTreeSet::new();
2669 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2670 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2671 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2672 assert_eq!(witness_lens.len(), 3);
2673 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2674 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2675 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2677 // Next nodes[1] broadcasts its current local tx state:
2678 assert_eq!(node_txn[1].input.len(), 1);
2679 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2681 assert_eq!(node_txn[2].input.len(), 1);
2682 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2683 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2684 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2685 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2686 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2688 get_announce_close_broadcast_events(&nodes, 0, 1);
2689 assert_eq!(nodes[0].node.list_channels().len(), 0);
2690 assert_eq!(nodes[1].node.list_channels().len(), 0);
2694 fn claim_htlc_outputs_single_tx() {
2695 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2696 let chanmon_cfgs = create_chanmon_cfgs(2);
2697 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2698 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2699 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2701 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2703 // Rebalance the network to generate htlc in the two directions
2704 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2705 // 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
2706 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2707 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2708 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2710 // Get the will-be-revoked local txn from node[0]
2711 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2713 //Revoke the old state
2714 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2717 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2718 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2719 check_added_monitors!(nodes[0], 1);
2720 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2721 check_added_monitors!(nodes[1], 1);
2722 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2724 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2725 expect_payment_failed!(nodes[1], payment_hash_2, true);
2727 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2728 assert_eq!(node_txn.len(), 9);
2729 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2730 // ChannelManager: local commmitment + local HTLC-timeout (2)
2731 // 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)
2732 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2734 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2735 assert_eq!(node_txn[2].input.len(), 1);
2736 check_spends!(node_txn[2], chan_1.3);
2737 assert_eq!(node_txn[3].input.len(), 1);
2738 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2739 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2740 check_spends!(node_txn[3], node_txn[2]);
2742 // Justice transactions are indices 1-2-4
2743 assert_eq!(node_txn[0].input.len(), 1);
2744 assert_eq!(node_txn[1].input.len(), 1);
2745 assert_eq!(node_txn[4].input.len(), 1);
2747 check_spends!(node_txn[0], revoked_local_txn[0]);
2748 check_spends!(node_txn[1], revoked_local_txn[0]);
2749 check_spends!(node_txn[4], revoked_local_txn[0]);
2751 let mut witness_lens = BTreeSet::new();
2752 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2753 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2754 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2755 assert_eq!(witness_lens.len(), 3);
2756 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2757 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2758 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2760 get_announce_close_broadcast_events(&nodes, 0, 1);
2761 assert_eq!(nodes[0].node.list_channels().len(), 0);
2762 assert_eq!(nodes[1].node.list_channels().len(), 0);
2766 fn test_htlc_on_chain_success() {
2767 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2768 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2769 // broadcasting the right event to other nodes in payment path.
2770 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2771 // A --------------------> B ----------------------> C (preimage)
2772 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2773 // commitment transaction was broadcast.
2774 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2776 // B should be able to claim via preimage if A then broadcasts its local tx.
2777 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2778 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2779 // PaymentSent event).
2781 let chanmon_cfgs = create_chanmon_cfgs(3);
2782 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2783 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2784 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2786 // Create some initial channels
2787 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2788 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2790 // Rebalance the network a bit by relaying one payment through all the channels...
2791 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2792 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2794 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2795 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2796 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2798 // Broadcast legit commitment tx from C on B's chain
2799 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2800 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2801 assert_eq!(commitment_tx.len(), 1);
2802 check_spends!(commitment_tx[0], chan_2.3);
2803 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2804 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2805 check_added_monitors!(nodes[2], 2);
2806 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2807 assert!(updates.update_add_htlcs.is_empty());
2808 assert!(updates.update_fail_htlcs.is_empty());
2809 assert!(updates.update_fail_malformed_htlcs.is_empty());
2810 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2812 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2813 check_closed_broadcast!(nodes[2], false);
2814 check_added_monitors!(nodes[2], 1);
2815 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)
2816 assert_eq!(node_txn.len(), 5);
2817 assert_eq!(node_txn[0], node_txn[3]);
2818 assert_eq!(node_txn[1], node_txn[4]);
2819 assert_eq!(node_txn[2], commitment_tx[0]);
2820 check_spends!(node_txn[0], commitment_tx[0]);
2821 check_spends!(node_txn[1], commitment_tx[0]);
2822 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2823 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2824 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2825 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2826 assert_eq!(node_txn[0].lock_time, 0);
2827 assert_eq!(node_txn[1].lock_time, 0);
2829 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2830 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2832 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2833 assert_eq!(added_monitors.len(), 1);
2834 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2835 added_monitors.clear();
2837 let events = nodes[1].node.get_and_clear_pending_msg_events();
2839 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2840 assert_eq!(added_monitors.len(), 2);
2841 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2842 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2843 added_monitors.clear();
2845 assert_eq!(events.len(), 2);
2847 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2848 _ => panic!("Unexpected event"),
2851 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, .. } } => {
2852 assert!(update_add_htlcs.is_empty());
2853 assert!(update_fail_htlcs.is_empty());
2854 assert_eq!(update_fulfill_htlcs.len(), 1);
2855 assert!(update_fail_malformed_htlcs.is_empty());
2856 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2858 _ => panic!("Unexpected event"),
2860 macro_rules! check_tx_local_broadcast {
2861 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2862 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2863 assert_eq!(node_txn.len(), 5);
2864 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2865 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2866 check_spends!(node_txn[0], $commitment_tx);
2867 check_spends!(node_txn[1], $commitment_tx);
2868 assert_ne!(node_txn[0].lock_time, 0);
2869 assert_ne!(node_txn[1].lock_time, 0);
2871 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2872 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2873 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2874 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2876 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2877 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2878 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2879 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2881 check_spends!(node_txn[2], $chan_tx);
2882 check_spends!(node_txn[3], node_txn[2]);
2883 check_spends!(node_txn[4], node_txn[2]);
2884 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2885 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2886 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2887 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2888 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2889 assert_ne!(node_txn[3].lock_time, 0);
2890 assert_ne!(node_txn[4].lock_time, 0);
2894 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2895 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2896 // timeout-claim of the output that nodes[2] just claimed via success.
2897 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2899 // Broadcast legit commitment tx from A on B's chain
2900 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2901 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2902 check_spends!(commitment_tx[0], chan_1.3);
2903 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2904 check_closed_broadcast!(nodes[1], false);
2905 check_added_monitors!(nodes[1], 1);
2906 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2907 assert_eq!(node_txn.len(), 4);
2908 check_spends!(node_txn[0], commitment_tx[0]);
2909 assert_eq!(node_txn[0].input.len(), 2);
2910 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2911 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2912 assert_eq!(node_txn[0].lock_time, 0);
2913 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2914 check_spends!(node_txn[1], chan_1.3);
2915 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2916 check_spends!(node_txn[2], node_txn[1]);
2917 check_spends!(node_txn[3], node_txn[1]);
2918 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2919 // we already checked the same situation with A.
2921 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2922 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2923 check_closed_broadcast!(nodes[0], false);
2924 check_added_monitors!(nodes[0], 1);
2925 let events = nodes[0].node.get_and_clear_pending_events();
2926 assert_eq!(events.len(), 2);
2927 let mut first_claimed = false;
2928 for event in events {
2930 Event::PaymentSent { payment_preimage } => {
2931 if payment_preimage == our_payment_preimage {
2932 assert!(!first_claimed);
2933 first_claimed = true;
2935 assert_eq!(payment_preimage, our_payment_preimage_2);
2938 _ => panic!("Unexpected event"),
2941 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2945 fn test_htlc_on_chain_timeout() {
2946 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2947 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2948 // broadcasting the right event to other nodes in payment path.
2949 // A ------------------> B ----------------------> C (timeout)
2950 // B's commitment tx C's commitment tx
2952 // B's HTLC timeout tx B's timeout tx
2954 let chanmon_cfgs = create_chanmon_cfgs(3);
2955 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2956 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2957 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2959 // Create some intial channels
2960 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2961 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2963 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2964 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2965 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2967 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2968 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2970 // Broadcast legit commitment tx from C on B's chain
2971 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2972 check_spends!(commitment_tx[0], chan_2.3);
2973 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2974 check_added_monitors!(nodes[2], 0);
2975 expect_pending_htlcs_forwardable!(nodes[2]);
2976 check_added_monitors!(nodes[2], 1);
2978 let events = nodes[2].node.get_and_clear_pending_msg_events();
2979 assert_eq!(events.len(), 1);
2981 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, .. } } => {
2982 assert!(update_add_htlcs.is_empty());
2983 assert!(!update_fail_htlcs.is_empty());
2984 assert!(update_fulfill_htlcs.is_empty());
2985 assert!(update_fail_malformed_htlcs.is_empty());
2986 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2988 _ => panic!("Unexpected event"),
2990 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2991 check_closed_broadcast!(nodes[2], false);
2992 check_added_monitors!(nodes[2], 1);
2993 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2994 assert_eq!(node_txn.len(), 1);
2995 check_spends!(node_txn[0], chan_2.3);
2996 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2998 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2999 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3000 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3003 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3004 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3005 assert_eq!(node_txn[1], node_txn[3]);
3006 assert_eq!(node_txn[2], node_txn[4]);
3008 check_spends!(node_txn[0], commitment_tx[0]);
3009 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3011 check_spends!(node_txn[1], chan_2.3);
3012 check_spends!(node_txn[2], node_txn[1]);
3013 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3014 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3016 timeout_tx = node_txn[0].clone();
3020 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
3021 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3022 check_added_monitors!(nodes[1], 1);
3023 check_closed_broadcast!(nodes[1], false);
3025 expect_pending_htlcs_forwardable!(nodes[1]);
3026 check_added_monitors!(nodes[1], 1);
3027 let events = nodes[1].node.get_and_clear_pending_msg_events();
3028 assert_eq!(events.len(), 1);
3030 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, .. } } => {
3031 assert!(update_add_htlcs.is_empty());
3032 assert!(!update_fail_htlcs.is_empty());
3033 assert!(update_fulfill_htlcs.is_empty());
3034 assert!(update_fail_malformed_htlcs.is_empty());
3035 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3037 _ => panic!("Unexpected event"),
3039 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
3040 assert_eq!(node_txn.len(), 0);
3042 // Broadcast legit commitment tx from B on A's chain
3043 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3044 check_spends!(commitment_tx[0], chan_1.3);
3046 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3047 check_closed_broadcast!(nodes[0], false);
3048 check_added_monitors!(nodes[0], 1);
3049 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3050 assert_eq!(node_txn.len(), 3);
3051 check_spends!(node_txn[0], commitment_tx[0]);
3052 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3053 check_spends!(node_txn[1], chan_1.3);
3054 check_spends!(node_txn[2], node_txn[1]);
3055 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3056 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3060 fn test_simple_commitment_revoked_fail_backward() {
3061 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3062 // and fail backward accordingly.
3064 let chanmon_cfgs = create_chanmon_cfgs(3);
3065 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3066 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3067 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3069 // Create some initial channels
3070 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3071 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3073 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3074 // Get the will-be-revoked local txn from nodes[2]
3075 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3076 // Revoke the old state
3077 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3079 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3081 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3082 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3083 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3084 check_added_monitors!(nodes[1], 1);
3085 check_closed_broadcast!(nodes[1], false);
3087 expect_pending_htlcs_forwardable!(nodes[1]);
3088 check_added_monitors!(nodes[1], 1);
3089 let events = nodes[1].node.get_and_clear_pending_msg_events();
3090 assert_eq!(events.len(), 1);
3092 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, .. } } => {
3093 assert!(update_add_htlcs.is_empty());
3094 assert_eq!(update_fail_htlcs.len(), 1);
3095 assert!(update_fulfill_htlcs.is_empty());
3096 assert!(update_fail_malformed_htlcs.is_empty());
3097 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3099 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3100 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3102 let events = nodes[0].node.get_and_clear_pending_msg_events();
3103 assert_eq!(events.len(), 1);
3105 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3106 _ => panic!("Unexpected event"),
3108 expect_payment_failed!(nodes[0], payment_hash, false);
3110 _ => panic!("Unexpected event"),
3114 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3115 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3116 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3117 // commitment transaction anymore.
3118 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3119 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3120 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3121 // technically disallowed and we should probably handle it reasonably.
3122 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3123 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3125 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3126 // commitment_signed (implying it will be in the latest remote commitment transaction).
3127 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3128 // and once they revoke the previous commitment transaction (allowing us to send a new
3129 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3130 let chanmon_cfgs = create_chanmon_cfgs(3);
3131 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3132 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3133 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3135 // Create some initial channels
3136 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3137 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3139 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3140 // Get the will-be-revoked local txn from nodes[2]
3141 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3142 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3143 // Revoke the old state
3144 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3146 let value = if use_dust {
3147 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3148 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3149 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3152 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3153 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3154 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3156 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3157 expect_pending_htlcs_forwardable!(nodes[2]);
3158 check_added_monitors!(nodes[2], 1);
3159 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3160 assert!(updates.update_add_htlcs.is_empty());
3161 assert!(updates.update_fulfill_htlcs.is_empty());
3162 assert!(updates.update_fail_malformed_htlcs.is_empty());
3163 assert_eq!(updates.update_fail_htlcs.len(), 1);
3164 assert!(updates.update_fee.is_none());
3165 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3166 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3167 // Drop the last RAA from 3 -> 2
3169 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3170 expect_pending_htlcs_forwardable!(nodes[2]);
3171 check_added_monitors!(nodes[2], 1);
3172 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3173 assert!(updates.update_add_htlcs.is_empty());
3174 assert!(updates.update_fulfill_htlcs.is_empty());
3175 assert!(updates.update_fail_malformed_htlcs.is_empty());
3176 assert_eq!(updates.update_fail_htlcs.len(), 1);
3177 assert!(updates.update_fee.is_none());
3178 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3179 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3180 check_added_monitors!(nodes[1], 1);
3181 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3182 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3183 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3184 check_added_monitors!(nodes[2], 1);
3186 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3187 expect_pending_htlcs_forwardable!(nodes[2]);
3188 check_added_monitors!(nodes[2], 1);
3189 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3190 assert!(updates.update_add_htlcs.is_empty());
3191 assert!(updates.update_fulfill_htlcs.is_empty());
3192 assert!(updates.update_fail_malformed_htlcs.is_empty());
3193 assert_eq!(updates.update_fail_htlcs.len(), 1);
3194 assert!(updates.update_fee.is_none());
3195 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3196 // At this point first_payment_hash has dropped out of the latest two commitment
3197 // transactions that nodes[1] is tracking...
3198 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3199 check_added_monitors!(nodes[1], 1);
3200 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3201 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3202 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3203 check_added_monitors!(nodes[2], 1);
3205 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3206 // on nodes[2]'s RAA.
3207 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3208 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3209 let logger = test_utils::TestLogger::new();
3210 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();
3211 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3212 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3213 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3214 check_added_monitors!(nodes[1], 0);
3217 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3218 // One monitor for the new revocation preimage, no second on as we won't generate a new
3219 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3220 check_added_monitors!(nodes[1], 1);
3221 let events = nodes[1].node.get_and_clear_pending_events();
3222 assert_eq!(events.len(), 1);
3224 Event::PendingHTLCsForwardable { .. } => { },
3225 _ => panic!("Unexpected event"),
3227 // Deliberately don't process the pending fail-back so they all fail back at once after
3228 // block connection just like the !deliver_bs_raa case
3231 let mut failed_htlcs = HashSet::new();
3232 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3234 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3235 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3236 check_added_monitors!(nodes[1], 1);
3237 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3239 let events = nodes[1].node.get_and_clear_pending_events();
3240 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3242 Event::PaymentFailed { ref payment_hash, .. } => {
3243 assert_eq!(*payment_hash, fourth_payment_hash);
3245 _ => panic!("Unexpected event"),
3247 if !deliver_bs_raa {
3249 Event::PendingHTLCsForwardable { .. } => { },
3250 _ => panic!("Unexpected event"),
3253 nodes[1].node.process_pending_htlc_forwards();
3254 check_added_monitors!(nodes[1], 1);
3256 let events = nodes[1].node.get_and_clear_pending_msg_events();
3257 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3258 match events[if deliver_bs_raa { 1 } else { 0 }] {
3259 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3260 _ => panic!("Unexpected event"),
3264 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, .. } } => {
3265 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3266 assert_eq!(update_add_htlcs.len(), 1);
3267 assert!(update_fulfill_htlcs.is_empty());
3268 assert!(update_fail_htlcs.is_empty());
3269 assert!(update_fail_malformed_htlcs.is_empty());
3271 _ => panic!("Unexpected event"),
3274 match events[if deliver_bs_raa { 2 } else { 1 }] {
3275 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, .. } } => {
3276 assert!(update_add_htlcs.is_empty());
3277 assert_eq!(update_fail_htlcs.len(), 3);
3278 assert!(update_fulfill_htlcs.is_empty());
3279 assert!(update_fail_malformed_htlcs.is_empty());
3280 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3282 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3283 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3284 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3286 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3288 let events = nodes[0].node.get_and_clear_pending_msg_events();
3289 // If we delivered B's RAA we got an unknown preimage error, not something
3290 // that we should update our routing table for.
3291 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3292 for event in events {
3294 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3295 _ => panic!("Unexpected event"),
3298 let events = nodes[0].node.get_and_clear_pending_events();
3299 assert_eq!(events.len(), 3);
3301 Event::PaymentFailed { ref payment_hash, .. } => {
3302 assert!(failed_htlcs.insert(payment_hash.0));
3304 _ => panic!("Unexpected event"),
3307 Event::PaymentFailed { ref payment_hash, .. } => {
3308 assert!(failed_htlcs.insert(payment_hash.0));
3310 _ => panic!("Unexpected event"),
3313 Event::PaymentFailed { ref payment_hash, .. } => {
3314 assert!(failed_htlcs.insert(payment_hash.0));
3316 _ => panic!("Unexpected event"),
3319 _ => panic!("Unexpected event"),
3322 assert!(failed_htlcs.contains(&first_payment_hash.0));
3323 assert!(failed_htlcs.contains(&second_payment_hash.0));
3324 assert!(failed_htlcs.contains(&third_payment_hash.0));
3328 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3329 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3330 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3331 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3332 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3336 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3337 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3338 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3339 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3340 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3344 fn fail_backward_pending_htlc_upon_channel_failure() {
3345 let chanmon_cfgs = create_chanmon_cfgs(2);
3346 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3347 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3348 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3349 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3350 let logger = test_utils::TestLogger::new();
3352 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3354 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3355 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3356 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();
3357 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3358 check_added_monitors!(nodes[0], 1);
3360 let payment_event = {
3361 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3362 assert_eq!(events.len(), 1);
3363 SendEvent::from_event(events.remove(0))
3365 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3366 assert_eq!(payment_event.msgs.len(), 1);
3369 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3370 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3372 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3373 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3374 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3375 check_added_monitors!(nodes[0], 0);
3377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3380 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3382 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3384 let secp_ctx = Secp256k1::new();
3385 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3386 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3387 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3388 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();
3389 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3390 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3391 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3393 // Send a 0-msat update_add_htlc to fail the channel.
3394 let update_add_htlc = msgs::UpdateAddHTLC {
3400 onion_routing_packet,
3402 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3405 // Check that Alice fails backward the pending HTLC from the second payment.
3406 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3407 check_closed_broadcast!(nodes[0], true);
3408 check_added_monitors!(nodes[0], 1);
3412 fn test_htlc_ignore_latest_remote_commitment() {
3413 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3414 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3415 let chanmon_cfgs = create_chanmon_cfgs(2);
3416 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3417 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3418 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3419 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3421 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3422 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3423 check_closed_broadcast!(nodes[0], false);
3424 check_added_monitors!(nodes[0], 1);
3426 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3427 assert_eq!(node_txn.len(), 2);
3429 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3430 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3431 check_closed_broadcast!(nodes[1], false);
3432 check_added_monitors!(nodes[1], 1);
3434 // Duplicate the block_connected call since this may happen due to other listeners
3435 // registering new transactions
3436 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3440 fn test_force_close_fail_back() {
3441 // Check which HTLCs are failed-backwards on channel force-closure
3442 let chanmon_cfgs = create_chanmon_cfgs(3);
3443 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3444 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3445 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3446 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3447 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3448 let logger = test_utils::TestLogger::new();
3450 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3452 let mut payment_event = {
3453 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3454 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();
3455 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3456 check_added_monitors!(nodes[0], 1);
3458 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3459 assert_eq!(events.len(), 1);
3460 SendEvent::from_event(events.remove(0))
3463 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3464 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3466 expect_pending_htlcs_forwardable!(nodes[1]);
3468 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3469 assert_eq!(events_2.len(), 1);
3470 payment_event = SendEvent::from_event(events_2.remove(0));
3471 assert_eq!(payment_event.msgs.len(), 1);
3473 check_added_monitors!(nodes[1], 1);
3474 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3475 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3476 check_added_monitors!(nodes[2], 1);
3477 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3479 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3480 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3481 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3483 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3484 check_closed_broadcast!(nodes[2], false);
3485 check_added_monitors!(nodes[2], 1);
3487 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3488 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3489 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3490 // back to nodes[1] upon timeout otherwise.
3491 assert_eq!(node_txn.len(), 1);
3495 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3496 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3498 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3499 check_closed_broadcast!(nodes[1], false);
3500 check_added_monitors!(nodes[1], 1);
3502 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3504 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3505 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3506 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3508 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3509 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3510 assert_eq!(node_txn.len(), 1);
3511 assert_eq!(node_txn[0].input.len(), 1);
3512 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3513 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3514 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3516 check_spends!(node_txn[0], tx);
3520 fn test_unconf_chan() {
3521 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3522 let chanmon_cfgs = create_chanmon_cfgs(2);
3523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3528 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3529 assert_eq!(channel_state.by_id.len(), 1);
3530 assert_eq!(channel_state.short_to_id.len(), 1);
3531 mem::drop(channel_state);
3533 let mut headers = Vec::new();
3534 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3535 headers.push(header.clone());
3537 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3538 headers.push(header.clone());
3540 let mut height = 99;
3541 while !headers.is_empty() {
3542 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3545 check_closed_broadcast!(nodes[0], false);
3546 check_added_monitors!(nodes[0], 1);
3547 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3548 assert_eq!(channel_state.by_id.len(), 0);
3549 assert_eq!(channel_state.short_to_id.len(), 0);
3553 fn test_simple_peer_disconnect() {
3554 // Test that we can reconnect when there are no lost messages
3555 let chanmon_cfgs = create_chanmon_cfgs(3);
3556 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3557 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3558 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3559 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3560 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3562 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3563 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3564 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3566 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3567 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3568 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3569 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3571 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3572 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3573 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3575 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3576 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3577 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3578 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3584 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3586 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3588 let events = nodes[0].node.get_and_clear_pending_events();
3589 assert_eq!(events.len(), 2);
3591 Event::PaymentSent { payment_preimage } => {
3592 assert_eq!(payment_preimage, payment_preimage_3);
3594 _ => panic!("Unexpected event"),
3597 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3598 assert_eq!(payment_hash, payment_hash_5);
3599 assert!(rejected_by_dest);
3601 _ => panic!("Unexpected event"),
3605 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3606 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3609 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3610 // Test that we can reconnect when in-flight HTLC updates get dropped
3611 let chanmon_cfgs = create_chanmon_cfgs(2);
3612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3614 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3615 if messages_delivered == 0 {
3616 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3617 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3619 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3622 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3624 let logger = test_utils::TestLogger::new();
3625 let payment_event = {
3626 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3627 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3628 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3629 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3630 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3631 check_added_monitors!(nodes[0], 1);
3633 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3634 assert_eq!(events.len(), 1);
3635 SendEvent::from_event(events.remove(0))
3637 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3639 if messages_delivered < 2 {
3640 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3642 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3643 if messages_delivered >= 3 {
3644 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3645 check_added_monitors!(nodes[1], 1);
3646 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3648 if messages_delivered >= 4 {
3649 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3650 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3651 check_added_monitors!(nodes[0], 1);
3653 if messages_delivered >= 5 {
3654 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3655 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3656 // No commitment_signed so get_event_msg's assert(len == 1) passes
3657 check_added_monitors!(nodes[0], 1);
3659 if messages_delivered >= 6 {
3660 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3661 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3662 check_added_monitors!(nodes[1], 1);
3669 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3670 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3671 if messages_delivered < 3 {
3672 // Even if the funding_locked messages get exchanged, as long as nothing further was
3673 // received on either side, both sides will need to resend them.
3674 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3675 } else if messages_delivered == 3 {
3676 // nodes[0] still wants its RAA + commitment_signed
3677 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3678 } else if messages_delivered == 4 {
3679 // nodes[0] still wants its commitment_signed
3680 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3681 } else if messages_delivered == 5 {
3682 // nodes[1] still wants its final RAA
3683 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3684 } else if messages_delivered == 6 {
3685 // Everything was delivered...
3686 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3689 let events_1 = nodes[1].node.get_and_clear_pending_events();
3690 assert_eq!(events_1.len(), 1);
3692 Event::PendingHTLCsForwardable { .. } => { },
3693 _ => panic!("Unexpected event"),
3696 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3697 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3698 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700 nodes[1].node.process_pending_htlc_forwards();
3702 let events_2 = nodes[1].node.get_and_clear_pending_events();
3703 assert_eq!(events_2.len(), 1);
3705 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3706 assert_eq!(payment_hash_1, *payment_hash);
3707 assert_eq!(*payment_secret, None);
3708 assert_eq!(amt, 1000000);
3710 _ => panic!("Unexpected event"),
3713 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3714 check_added_monitors!(nodes[1], 1);
3716 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3717 assert_eq!(events_3.len(), 1);
3718 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3719 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3720 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3721 assert!(updates.update_add_htlcs.is_empty());
3722 assert!(updates.update_fail_htlcs.is_empty());
3723 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3724 assert!(updates.update_fail_malformed_htlcs.is_empty());
3725 assert!(updates.update_fee.is_none());
3726 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3728 _ => panic!("Unexpected event"),
3731 if messages_delivered >= 1 {
3732 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3734 let events_4 = nodes[0].node.get_and_clear_pending_events();
3735 assert_eq!(events_4.len(), 1);
3737 Event::PaymentSent { ref payment_preimage } => {
3738 assert_eq!(payment_preimage_1, *payment_preimage);
3740 _ => panic!("Unexpected event"),
3743 if messages_delivered >= 2 {
3744 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3745 check_added_monitors!(nodes[0], 1);
3746 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3748 if messages_delivered >= 3 {
3749 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3750 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3751 check_added_monitors!(nodes[1], 1);
3753 if messages_delivered >= 4 {
3754 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3755 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3756 // No commitment_signed so get_event_msg's assert(len == 1) passes
3757 check_added_monitors!(nodes[1], 1);
3759 if messages_delivered >= 5 {
3760 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3761 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3762 check_added_monitors!(nodes[0], 1);
3769 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3770 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3771 if messages_delivered < 2 {
3772 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3773 //TODO: Deduplicate PaymentSent events, then enable this if:
3774 //if messages_delivered < 1 {
3775 let events_4 = nodes[0].node.get_and_clear_pending_events();
3776 assert_eq!(events_4.len(), 1);
3778 Event::PaymentSent { ref payment_preimage } => {
3779 assert_eq!(payment_preimage_1, *payment_preimage);
3781 _ => panic!("Unexpected event"),
3784 } else if messages_delivered == 2 {
3785 // nodes[0] still wants its RAA + commitment_signed
3786 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3787 } else if messages_delivered == 3 {
3788 // nodes[0] still wants its commitment_signed
3789 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3790 } else if messages_delivered == 4 {
3791 // nodes[1] still wants its final RAA
3792 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3793 } else if messages_delivered == 5 {
3794 // Everything was delivered...
3795 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3798 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3799 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3800 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3802 // Channel should still work fine...
3803 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3804 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3805 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3806 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3807 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3808 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3812 fn test_drop_messages_peer_disconnect_a() {
3813 do_test_drop_messages_peer_disconnect(0);
3814 do_test_drop_messages_peer_disconnect(1);
3815 do_test_drop_messages_peer_disconnect(2);
3816 do_test_drop_messages_peer_disconnect(3);
3820 fn test_drop_messages_peer_disconnect_b() {
3821 do_test_drop_messages_peer_disconnect(4);
3822 do_test_drop_messages_peer_disconnect(5);
3823 do_test_drop_messages_peer_disconnect(6);
3827 fn test_funding_peer_disconnect() {
3828 // Test that we can lock in our funding tx while disconnected
3829 let chanmon_cfgs = create_chanmon_cfgs(2);
3830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3833 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3835 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3836 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3838 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3839 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3840 assert_eq!(events_1.len(), 1);
3842 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3843 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3845 _ => panic!("Unexpected event"),
3848 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3850 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3851 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3853 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3854 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3855 assert_eq!(events_2.len(), 2);
3856 let funding_locked = match events_2[0] {
3857 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3858 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3861 _ => panic!("Unexpected event"),
3863 let bs_announcement_sigs = match events_2[1] {
3864 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3865 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3868 _ => panic!("Unexpected event"),
3871 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3873 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3874 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3875 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3876 assert_eq!(events_3.len(), 2);
3877 let as_announcement_sigs = match events_3[0] {
3878 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3879 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3882 _ => panic!("Unexpected event"),
3884 let (as_announcement, as_update) = match events_3[1] {
3885 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3886 (msg.clone(), update_msg.clone())
3888 _ => panic!("Unexpected event"),
3891 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3892 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3893 assert_eq!(events_4.len(), 1);
3894 let (_, bs_update) = match events_4[0] {
3895 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3896 (msg.clone(), update_msg.clone())
3898 _ => panic!("Unexpected event"),
3901 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3902 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3903 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3905 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3906 let logger = test_utils::TestLogger::new();
3907 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();
3908 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3909 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3913 fn test_drop_messages_peer_disconnect_dual_htlc() {
3914 // Test that we can handle reconnecting when both sides of a channel have pending
3915 // commitment_updates when we disconnect.
3916 let chanmon_cfgs = create_chanmon_cfgs(2);
3917 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3918 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3919 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3920 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3921 let logger = test_utils::TestLogger::new();
3923 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3925 // Now try to send a second payment which will fail to send
3926 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3927 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
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 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3930 check_added_monitors!(nodes[0], 1);
3932 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3933 assert_eq!(events_1.len(), 1);
3935 MessageSendEvent::UpdateHTLCs { .. } => {},
3936 _ => panic!("Unexpected event"),
3939 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3940 check_added_monitors!(nodes[1], 1);
3942 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3943 assert_eq!(events_2.len(), 1);
3945 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 } } => {
3946 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3947 assert!(update_add_htlcs.is_empty());
3948 assert_eq!(update_fulfill_htlcs.len(), 1);
3949 assert!(update_fail_htlcs.is_empty());
3950 assert!(update_fail_malformed_htlcs.is_empty());
3951 assert!(update_fee.is_none());
3953 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3954 let events_3 = nodes[0].node.get_and_clear_pending_events();
3955 assert_eq!(events_3.len(), 1);
3957 Event::PaymentSent { ref payment_preimage } => {
3958 assert_eq!(*payment_preimage, payment_preimage_1);
3960 _ => panic!("Unexpected event"),
3963 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3964 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3965 // No commitment_signed so get_event_msg's assert(len == 1) passes
3966 check_added_monitors!(nodes[0], 1);
3968 _ => panic!("Unexpected event"),
3971 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3972 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3974 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3975 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3976 assert_eq!(reestablish_1.len(), 1);
3977 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3978 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3979 assert_eq!(reestablish_2.len(), 1);
3981 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3982 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3983 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3984 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3986 assert!(as_resp.0.is_none());
3987 assert!(bs_resp.0.is_none());
3989 assert!(bs_resp.1.is_none());
3990 assert!(bs_resp.2.is_none());
3992 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3994 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3995 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3996 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3997 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3998 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3999 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4000 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4001 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4002 // No commitment_signed so get_event_msg's assert(len == 1) passes
4003 check_added_monitors!(nodes[1], 1);
4005 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4006 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4007 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4008 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4009 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4010 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4011 assert!(bs_second_commitment_signed.update_fee.is_none());
4012 check_added_monitors!(nodes[1], 1);
4014 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4015 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4016 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4017 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4018 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4019 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4020 assert!(as_commitment_signed.update_fee.is_none());
4021 check_added_monitors!(nodes[0], 1);
4023 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4024 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4025 // No commitment_signed so get_event_msg's assert(len == 1) passes
4026 check_added_monitors!(nodes[0], 1);
4028 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4029 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4030 // No commitment_signed so get_event_msg's assert(len == 1) passes
4031 check_added_monitors!(nodes[1], 1);
4033 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4034 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4035 check_added_monitors!(nodes[1], 1);
4037 expect_pending_htlcs_forwardable!(nodes[1]);
4039 let events_5 = nodes[1].node.get_and_clear_pending_events();
4040 assert_eq!(events_5.len(), 1);
4042 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4043 assert_eq!(payment_hash_2, *payment_hash);
4044 assert_eq!(*payment_secret, None);
4046 _ => panic!("Unexpected event"),
4049 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4050 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4051 check_added_monitors!(nodes[0], 1);
4053 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4056 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4057 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4058 // to avoid our counterparty failing the channel.
4059 let chanmon_cfgs = create_chanmon_cfgs(2);
4060 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4061 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4062 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4064 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4065 let logger = test_utils::TestLogger::new();
4067 let our_payment_hash = if send_partial_mpp {
4068 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4069 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();
4070 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4071 let payment_secret = PaymentSecret([0xdb; 32]);
4072 // Use the utility function send_payment_along_path to send the payment with MPP data which
4073 // indicates there are more HTLCs coming.
4074 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4075 check_added_monitors!(nodes[0], 1);
4076 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4077 assert_eq!(events.len(), 1);
4078 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4079 // hop should *not* yet generate any PaymentReceived event(s).
4080 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4083 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4086 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4087 nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4088 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4089 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4090 header.prev_blockhash = header.block_hash();
4091 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
4092 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
4095 expect_pending_htlcs_forwardable!(nodes[1]);
4097 check_added_monitors!(nodes[1], 1);
4098 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4099 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4100 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4101 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4102 assert!(htlc_timeout_updates.update_fee.is_none());
4104 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4105 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4106 // 100_000 msat as u64, followed by a height of 123 as u32
4107 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4108 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4109 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4113 fn test_htlc_timeout() {
4114 do_test_htlc_timeout(true);
4115 do_test_htlc_timeout(false);
4118 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4119 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4120 let chanmon_cfgs = create_chanmon_cfgs(3);
4121 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4122 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4123 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4124 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4125 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4126 let logger = test_utils::TestLogger::new();
4128 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4129 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4131 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4132 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();
4133 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4135 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4136 check_added_monitors!(nodes[1], 1);
4138 // Now attempt to route a second payment, which should be placed in the holding cell
4139 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4141 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4142 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();
4143 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4144 check_added_monitors!(nodes[0], 1);
4145 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4146 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4147 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4148 expect_pending_htlcs_forwardable!(nodes[1]);
4149 check_added_monitors!(nodes[1], 0);
4151 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4152 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();
4153 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4154 check_added_monitors!(nodes[1], 0);
4157 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4158 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
4159 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4160 header.prev_blockhash = header.block_hash();
4161 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
4164 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4165 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4167 header.prev_blockhash = header.block_hash();
4168 nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
4171 expect_pending_htlcs_forwardable!(nodes[1]);
4172 check_added_monitors!(nodes[1], 1);
4173 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4174 assert_eq!(fail_commit.len(), 1);
4175 match fail_commit[0] {
4176 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4177 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4178 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4180 _ => unreachable!(),
4182 expect_payment_failed!(nodes[0], second_payment_hash, false);
4183 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4185 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4186 _ => panic!("Unexpected event"),
4189 panic!("Unexpected event");
4192 expect_payment_failed!(nodes[1], second_payment_hash, true);
4197 fn test_holding_cell_htlc_add_timeouts() {
4198 do_test_holding_cell_htlc_add_timeouts(false);
4199 do_test_holding_cell_htlc_add_timeouts(true);
4203 fn test_invalid_channel_announcement() {
4204 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4205 let secp_ctx = Secp256k1::new();
4206 let chanmon_cfgs = create_chanmon_cfgs(2);
4207 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4208 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4209 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4211 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4213 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4214 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4215 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4216 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4218 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 } );
4220 let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4221 let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4223 let as_network_key = nodes[0].node.get_our_node_id();
4224 let bs_network_key = nodes[1].node.get_our_node_id();
4226 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4228 let mut chan_announcement;
4230 macro_rules! dummy_unsigned_msg {
4232 msgs::UnsignedChannelAnnouncement {
4233 features: ChannelFeatures::known(),
4234 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4235 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4236 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4237 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4238 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4239 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4240 excess_data: Vec::new(),
4245 macro_rules! sign_msg {
4246 ($unsigned_msg: expr) => {
4247 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4248 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4249 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4250 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4251 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4252 chan_announcement = msgs::ChannelAnnouncement {
4253 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4254 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4255 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4256 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4257 contents: $unsigned_msg
4262 let unsigned_msg = dummy_unsigned_msg!();
4263 sign_msg!(unsigned_msg);
4264 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4265 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 } );
4267 // Configured with Network::Testnet
4268 let mut unsigned_msg = dummy_unsigned_msg!();
4269 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4270 sign_msg!(unsigned_msg);
4271 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4273 let mut unsigned_msg = dummy_unsigned_msg!();
4274 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4275 sign_msg!(unsigned_msg);
4276 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4280 fn test_no_txn_manager_serialize_deserialize() {
4281 let chanmon_cfgs = create_chanmon_cfgs(2);
4282 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4283 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4284 let logger: test_utils::TestLogger;
4285 let fee_estimator: test_utils::TestFeeEstimator;
4286 let new_chan_monitor: test_utils::TestChannelMonitor;
4287 let keys_manager: test_utils::TestKeysInterface;
4288 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4289 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4291 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4293 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4295 let nodes_0_serialized = nodes[0].node.encode();
4296 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4297 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4299 logger = test_utils::TestLogger::new();
4300 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4301 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4302 nodes[0].chan_monitor = &new_chan_monitor;
4303 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4304 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4305 assert!(chan_0_monitor_read.is_empty());
4307 let mut nodes_0_read = &nodes_0_serialized[..];
4308 let config = UserConfig::default();
4309 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4310 let (_, nodes_0_deserialized_tmp) = {
4311 let mut channel_monitors = HashMap::new();
4312 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4313 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4314 default_config: config,
4315 keys_manager: &keys_manager,
4316 fee_estimator: &fee_estimator,
4317 monitor: nodes[0].chan_monitor,
4318 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4323 nodes_0_deserialized = nodes_0_deserialized_tmp;
4324 assert!(nodes_0_read.is_empty());
4326 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4327 nodes[0].node = &nodes_0_deserialized;
4328 nodes[0].block_notifier.register_listener(nodes[0].node);
4329 assert_eq!(nodes[0].node.list_channels().len(), 1);
4330 check_added_monitors!(nodes[0], 1);
4332 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4333 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4334 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4335 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4337 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4338 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4339 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4340 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4342 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4343 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4344 for node in nodes.iter() {
4345 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4346 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4347 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4350 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4354 fn test_manager_serialize_deserialize_events() {
4355 // This test makes sure the events field in ChannelManager survives de/serialization
4356 let chanmon_cfgs = create_chanmon_cfgs(2);
4357 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4358 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4359 let fee_estimator: test_utils::TestFeeEstimator;
4360 let logger: test_utils::TestLogger;
4361 let new_chan_monitor: test_utils::TestChannelMonitor;
4362 let keys_manager: test_utils::TestKeysInterface;
4363 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4364 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4366 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4367 let channel_value = 100000;
4368 let push_msat = 10001;
4369 let a_flags = InitFeatures::known();
4370 let b_flags = InitFeatures::known();
4371 let node_a = nodes.pop().unwrap();
4372 let node_b = nodes.pop().unwrap();
4373 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4374 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()));
4375 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()));
4377 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4379 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4380 check_added_monitors!(node_a, 0);
4382 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()));
4384 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
4385 assert_eq!(added_monitors.len(), 1);
4386 assert_eq!(added_monitors[0].0, funding_output);
4387 added_monitors.clear();
4390 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()));
4392 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
4393 assert_eq!(added_monitors.len(), 1);
4394 assert_eq!(added_monitors[0].0, funding_output);
4395 added_monitors.clear();
4397 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4402 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4403 let nodes_0_serialized = nodes[0].node.encode();
4404 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4405 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4407 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4408 logger = test_utils::TestLogger::new();
4409 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4410 nodes[0].chan_monitor = &new_chan_monitor;
4411 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4412 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4413 assert!(chan_0_monitor_read.is_empty());
4415 let mut nodes_0_read = &nodes_0_serialized[..];
4416 let config = UserConfig::default();
4417 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4418 let (_, nodes_0_deserialized_tmp) = {
4419 let mut channel_monitors = HashMap::new();
4420 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4421 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4422 default_config: config,
4423 keys_manager: &keys_manager,
4424 fee_estimator: &fee_estimator,
4425 monitor: nodes[0].chan_monitor,
4426 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4431 nodes_0_deserialized = nodes_0_deserialized_tmp;
4432 assert!(nodes_0_read.is_empty());
4434 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4436 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4437 nodes[0].node = &nodes_0_deserialized;
4439 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4440 let events_4 = nodes[0].node.get_and_clear_pending_events();
4441 assert_eq!(events_4.len(), 1);
4443 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4444 assert_eq!(user_channel_id, 42);
4445 assert_eq!(*funding_txo, funding_output);
4447 _ => panic!("Unexpected event"),
4450 // Make sure the channel is functioning as though the de/serialization never happened
4451 nodes[0].block_notifier.register_listener(nodes[0].node);
4452 assert_eq!(nodes[0].node.list_channels().len(), 1);
4453 check_added_monitors!(nodes[0], 1);
4455 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4456 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4457 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4458 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4460 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4461 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4462 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4463 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4465 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4466 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4467 for node in nodes.iter() {
4468 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4469 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4470 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4473 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4477 fn test_simple_manager_serialize_deserialize() {
4478 let chanmon_cfgs = create_chanmon_cfgs(2);
4479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481 let logger: test_utils::TestLogger;
4482 let fee_estimator: test_utils::TestFeeEstimator;
4483 let new_chan_monitor: test_utils::TestChannelMonitor;
4484 let keys_manager: test_utils::TestKeysInterface;
4485 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4486 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4487 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4489 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4490 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4492 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4494 let nodes_0_serialized = nodes[0].node.encode();
4495 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4496 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4498 logger = test_utils::TestLogger::new();
4499 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4500 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4501 nodes[0].chan_monitor = &new_chan_monitor;
4502 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4503 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4504 assert!(chan_0_monitor_read.is_empty());
4506 let mut nodes_0_read = &nodes_0_serialized[..];
4507 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4508 let (_, nodes_0_deserialized_tmp) = {
4509 let mut channel_monitors = HashMap::new();
4510 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4511 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4512 default_config: UserConfig::default(),
4513 keys_manager: &keys_manager,
4514 fee_estimator: &fee_estimator,
4515 monitor: nodes[0].chan_monitor,
4516 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4521 nodes_0_deserialized = nodes_0_deserialized_tmp;
4522 assert!(nodes_0_read.is_empty());
4524 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4525 nodes[0].node = &nodes_0_deserialized;
4526 check_added_monitors!(nodes[0], 1);
4528 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4530 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4531 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4535 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4536 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4537 let chanmon_cfgs = create_chanmon_cfgs(4);
4538 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4539 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4540 let logger: test_utils::TestLogger;
4541 let fee_estimator: test_utils::TestFeeEstimator;
4542 let new_chan_monitor: test_utils::TestChannelMonitor;
4543 let keys_manager: test_utils::TestKeysInterface;
4544 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4545 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4546 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4547 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4548 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4550 let mut node_0_stale_monitors_serialized = Vec::new();
4551 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4552 let mut writer = test_utils::TestVecWriter(Vec::new());
4553 monitor.1.write_for_disk(&mut writer).unwrap();
4554 node_0_stale_monitors_serialized.push(writer.0);
4557 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4559 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4560 let nodes_0_serialized = nodes[0].node.encode();
4562 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4563 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4564 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4565 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4567 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4569 let mut node_0_monitors_serialized = Vec::new();
4570 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4571 let mut writer = test_utils::TestVecWriter(Vec::new());
4572 monitor.1.write_for_disk(&mut writer).unwrap();
4573 node_0_monitors_serialized.push(writer.0);
4576 logger = test_utils::TestLogger::new();
4577 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4578 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4579 nodes[0].chan_monitor = &new_chan_monitor;
4581 let mut node_0_stale_monitors = Vec::new();
4582 for serialized in node_0_stale_monitors_serialized.iter() {
4583 let mut read = &serialized[..];
4584 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4585 assert!(read.is_empty());
4586 node_0_stale_monitors.push(monitor);
4589 let mut node_0_monitors = Vec::new();
4590 for serialized in node_0_monitors_serialized.iter() {
4591 let mut read = &serialized[..];
4592 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4593 assert!(read.is_empty());
4594 node_0_monitors.push(monitor);
4597 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4599 let mut nodes_0_read = &nodes_0_serialized[..];
4600 if let Err(msgs::DecodeError::InvalidValue) =
4601 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4602 default_config: UserConfig::default(),
4603 keys_manager: &keys_manager,
4604 fee_estimator: &fee_estimator,
4605 monitor: nodes[0].chan_monitor,
4606 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4608 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4610 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4613 let mut nodes_0_read = &nodes_0_serialized[..];
4614 let (_, nodes_0_deserialized_tmp) =
4615 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4616 default_config: UserConfig::default(),
4617 keys_manager: &keys_manager,
4618 fee_estimator: &fee_estimator,
4619 monitor: nodes[0].chan_monitor,
4620 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4622 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4624 nodes_0_deserialized = nodes_0_deserialized_tmp;
4625 assert!(nodes_0_read.is_empty());
4627 { // Channel close should result in a commitment tx and an HTLC tx
4628 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4629 assert_eq!(txn.len(), 2);
4630 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4631 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4634 for monitor in node_0_monitors.drain(..) {
4635 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().0, monitor).is_ok());
4636 check_added_monitors!(nodes[0], 1);
4638 nodes[0].node = &nodes_0_deserialized;
4640 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4641 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4642 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4643 //... and we can even still claim the payment!
4644 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4646 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4647 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4648 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4649 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4650 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4651 assert_eq!(msg_events.len(), 1);
4652 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4654 &ErrorAction::SendErrorMessage { ref msg } => {
4655 assert_eq!(msg.channel_id, channel_id);
4657 _ => panic!("Unexpected event!"),
4662 macro_rules! check_spendable_outputs {
4663 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4665 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4666 let mut txn = Vec::new();
4667 for event in events {
4669 Event::SpendableOutputs { ref outputs } => {
4670 for outp in outputs {
4672 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4674 previous_output: outpoint.into_bitcoin_outpoint(),
4675 script_sig: Script::new(),
4677 witness: Vec::new(),
4680 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4681 value: output.value,
4683 let mut spend_tx = Transaction {
4689 let secp_ctx = Secp256k1::new();
4690 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4691 let remotepubkey = keys.pubkeys().payment_point;
4692 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4693 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4694 let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4695 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4696 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4697 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4700 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4702 previous_output: outpoint.into_bitcoin_outpoint(),
4703 script_sig: Script::new(),
4704 sequence: *to_self_delay as u32,
4705 witness: Vec::new(),
4708 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4709 value: output.value,
4711 let mut spend_tx = Transaction {
4717 let secp_ctx = Secp256k1::new();
4718 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4719 if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4721 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4722 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4723 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4724 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4725 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4726 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4727 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4728 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4732 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4733 let secp_ctx = Secp256k1::new();
4735 previous_output: outpoint.into_bitcoin_outpoint(),
4736 script_sig: Script::new(),
4738 witness: Vec::new(),
4741 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4742 value: output.value,
4744 let mut spend_tx = Transaction {
4748 output: vec![outp.clone()],
4751 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4753 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4755 Err(_) => panic!("Your RNG is busted"),
4758 Err(_) => panic!("Your rng is busted"),
4761 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4762 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4763 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4764 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4765 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4766 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4767 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4773 _ => panic!("Unexpected event"),
4782 fn test_claim_sizeable_push_msat() {
4783 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4784 let chanmon_cfgs = create_chanmon_cfgs(2);
4785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4787 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4789 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4790 nodes[1].node.force_close_channel(&chan.2);
4791 check_closed_broadcast!(nodes[1], false);
4792 check_added_monitors!(nodes[1], 1);
4793 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4794 assert_eq!(node_txn.len(), 1);
4795 check_spends!(node_txn[0], chan.3);
4796 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
4798 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4799 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4800 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4802 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4803 assert_eq!(spend_txn.len(), 1);
4804 check_spends!(spend_txn[0], node_txn[0]);
4808 fn test_claim_on_remote_sizeable_push_msat() {
4809 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4810 // to_remote output is encumbered by a P2WPKH
4811 let chanmon_cfgs = create_chanmon_cfgs(2);
4812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4814 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4816 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4817 nodes[0].node.force_close_channel(&chan.2);
4818 check_closed_broadcast!(nodes[0], false);
4819 check_added_monitors!(nodes[0], 1);
4821 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4822 assert_eq!(node_txn.len(), 1);
4823 check_spends!(node_txn[0], chan.3);
4824 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
4826 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4827 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4828 check_closed_broadcast!(nodes[1], false);
4829 check_added_monitors!(nodes[1], 1);
4830 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4832 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4833 assert_eq!(spend_txn.len(), 2);
4834 assert_eq!(spend_txn[0], spend_txn[1]);
4835 check_spends!(spend_txn[0], node_txn[0]);
4839 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4840 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4841 // to_remote output is encumbered by a P2WPKH
4843 let chanmon_cfgs = create_chanmon_cfgs(2);
4844 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4845 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4846 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4848 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4849 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4850 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4851 assert_eq!(revoked_local_txn[0].input.len(), 1);
4852 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4854 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4855 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4856 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4857 check_closed_broadcast!(nodes[1], false);
4858 check_added_monitors!(nodes[1], 1);
4860 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4861 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4862 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4863 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4865 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4866 assert_eq!(spend_txn.len(), 3);
4867 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4868 check_spends!(spend_txn[0], revoked_local_txn[0]);
4869 check_spends!(spend_txn[2], node_txn[0]);
4873 fn test_static_spendable_outputs_preimage_tx() {
4874 let chanmon_cfgs = create_chanmon_cfgs(2);
4875 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4876 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4877 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4879 // Create some initial channels
4880 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4882 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4884 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4885 assert_eq!(commitment_tx[0].input.len(), 1);
4886 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4888 // Settle A's commitment tx on B's chain
4889 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4891 check_added_monitors!(nodes[1], 1);
4892 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4893 check_added_monitors!(nodes[1], 1);
4894 let events = nodes[1].node.get_and_clear_pending_msg_events();
4896 MessageSendEvent::UpdateHTLCs { .. } => {},
4897 _ => panic!("Unexpected event"),
4900 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4901 _ => panic!("Unexepected event"),
4904 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4905 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4906 assert_eq!(node_txn.len(), 3);
4907 check_spends!(node_txn[0], commitment_tx[0]);
4908 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4909 check_spends!(node_txn[1], chan_1.3);
4910 check_spends!(node_txn[2], node_txn[1]);
4912 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4913 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4914 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4916 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4917 assert_eq!(spend_txn.len(), 1);
4918 check_spends!(spend_txn[0], node_txn[0]);
4922 fn test_static_spendable_outputs_timeout_tx() {
4923 let chanmon_cfgs = create_chanmon_cfgs(2);
4924 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4925 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4926 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4928 // Create some initial channels
4929 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4931 // Rebalance the network a bit by relaying one payment through all the channels ...
4932 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4934 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4936 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4937 assert_eq!(commitment_tx[0].input.len(), 1);
4938 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4940 // Settle A's commitment tx on B' chain
4941 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4942 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4943 check_added_monitors!(nodes[1], 1);
4944 let events = nodes[1].node.get_and_clear_pending_msg_events();
4946 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4947 _ => panic!("Unexpected event"),
4950 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4951 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4952 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4953 check_spends!(node_txn[0], commitment_tx[0].clone());
4954 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4955 check_spends!(node_txn[1], chan_1.3.clone());
4956 check_spends!(node_txn[2], node_txn[1]);
4958 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4959 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4960 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4961 expect_payment_failed!(nodes[1], our_payment_hash, true);
4963 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4964 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4965 check_spends!(spend_txn[2], node_txn[0].clone());
4969 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4970 let chanmon_cfgs = create_chanmon_cfgs(2);
4971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4973 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4975 // Create some initial channels
4976 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4978 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4979 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4980 assert_eq!(revoked_local_txn[0].input.len(), 1);
4981 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4983 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4985 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4986 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4987 check_closed_broadcast!(nodes[1], false);
4988 check_added_monitors!(nodes[1], 1);
4990 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4991 assert_eq!(node_txn.len(), 2);
4992 assert_eq!(node_txn[0].input.len(), 2);
4993 check_spends!(node_txn[0], revoked_local_txn[0]);
4995 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4996 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4997 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4999 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5000 assert_eq!(spend_txn.len(), 1);
5001 check_spends!(spend_txn[0], node_txn[0]);
5005 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5006 let chanmon_cfgs = create_chanmon_cfgs(2);
5007 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5008 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5009 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5011 // Create some initial channels
5012 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5014 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5015 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5016 assert_eq!(revoked_local_txn[0].input.len(), 1);
5017 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5019 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5021 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5022 // A will generate HTLC-Timeout from revoked commitment tx
5023 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5024 check_closed_broadcast!(nodes[0], false);
5025 check_added_monitors!(nodes[0], 1);
5027 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5028 assert_eq!(revoked_htlc_txn.len(), 2);
5029 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5030 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5031 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5032 check_spends!(revoked_htlc_txn[1], chan_1.3);
5034 // B will generate justice tx from A's revoked commitment/HTLC tx
5035 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5036 check_closed_broadcast!(nodes[1], false);
5037 check_added_monitors!(nodes[1], 1);
5039 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5040 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
5042 // node_txn[0] fully spends revoked_local_txn[0].
5043 assert_eq!(node_txn[0].input.len(), 3);
5044 assert_eq!(revoked_local_txn[0].output.len(), 2);
5045 // node_txn[0] tries to spend both revoked_local_txn[0] and revoked_htlc_txn[0], but
5046 // revoked_htlc_txn[0] spends revoked_local_txn[0] (ie this is a double-spend)!
5047 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5048 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5050 check_spends!(node_txn[1], chan_1.3);
5051 assert_eq!(node_txn[2].input.len(), 1);
5052 check_spends!(node_txn[2], revoked_htlc_txn[0]);
5053 assert_eq!(node_txn[3].input.len(), 1);
5054 check_spends!(node_txn[3], revoked_local_txn[0]);
5056 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5057 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5058 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5060 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5061 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5062 assert_eq!(spend_txn.len(), 2);
5063 check_spends!(spend_txn[0], node_txn[0]);
5064 check_spends!(spend_txn[1], node_txn[2]);
5068 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5069 let chanmon_cfgs = create_chanmon_cfgs(2);
5070 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5071 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5072 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5074 // Create some initial channels
5075 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5077 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5078 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5079 assert_eq!(revoked_local_txn[0].input.len(), 1);
5080 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5082 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5084 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5085 // B will generate HTLC-Success from revoked commitment tx
5086 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5087 check_closed_broadcast!(nodes[1], false);
5088 check_added_monitors!(nodes[1], 1);
5089 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5091 assert_eq!(revoked_htlc_txn.len(), 2);
5092 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5093 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5094 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5096 // A will generate justice tx from B's revoked commitment/HTLC tx
5097 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5098 check_closed_broadcast!(nodes[0], false);
5099 check_added_monitors!(nodes[0], 1);
5101 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5102 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5103 assert_eq!(node_txn[2].input.len(), 1);
5104 check_spends!(node_txn[2], revoked_htlc_txn[0]);
5106 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5107 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5108 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5110 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5111 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5112 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5113 assert_eq!(spend_txn[0], spend_txn[1]);
5114 assert_eq!(spend_txn[0], spend_txn[2]);
5115 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5116 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
5117 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
5121 fn test_onchain_to_onchain_claim() {
5122 // Test that in case of channel closure, we detect the state of output thanks to
5123 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5124 // First, have C claim an HTLC against its own latest commitment transaction.
5125 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5127 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5130 let chanmon_cfgs = create_chanmon_cfgs(3);
5131 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5132 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5133 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5135 // Create some initial channels
5136 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5137 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5139 // Rebalance the network a bit by relaying one payment through all the channels ...
5140 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5141 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5143 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5144 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5145 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5146 check_spends!(commitment_tx[0], chan_2.3);
5147 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5148 check_added_monitors!(nodes[2], 1);
5149 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5150 assert!(updates.update_add_htlcs.is_empty());
5151 assert!(updates.update_fail_htlcs.is_empty());
5152 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5153 assert!(updates.update_fail_malformed_htlcs.is_empty());
5155 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5156 check_closed_broadcast!(nodes[2], false);
5157 check_added_monitors!(nodes[2], 1);
5159 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5160 assert_eq!(c_txn.len(), 3);
5161 assert_eq!(c_txn[0], c_txn[2]);
5162 assert_eq!(commitment_tx[0], c_txn[1]);
5163 check_spends!(c_txn[1], chan_2.3);
5164 check_spends!(c_txn[2], c_txn[1]);
5165 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5166 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5167 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5168 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5170 // 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
5171 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5173 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5174 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5175 assert_eq!(b_txn.len(), 3);
5176 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5177 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5178 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5179 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5180 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5181 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5182 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5183 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5184 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5187 check_added_monitors!(nodes[1], 1);
5188 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5189 check_added_monitors!(nodes[1], 1);
5190 match msg_events[0] {
5191 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5192 _ => panic!("Unexpected event"),
5194 match msg_events[1] {
5195 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, .. } } => {
5196 assert!(update_add_htlcs.is_empty());
5197 assert!(update_fail_htlcs.is_empty());
5198 assert_eq!(update_fulfill_htlcs.len(), 1);
5199 assert!(update_fail_malformed_htlcs.is_empty());
5200 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5202 _ => panic!("Unexpected event"),
5204 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5205 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5206 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5207 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5208 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5209 assert_eq!(b_txn.len(), 3);
5210 check_spends!(b_txn[1], chan_1.3);
5211 check_spends!(b_txn[2], b_txn[1]);
5212 check_spends!(b_txn[0], commitment_tx[0]);
5213 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5214 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5215 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5217 check_closed_broadcast!(nodes[1], false);
5218 check_added_monitors!(nodes[1], 1);
5222 fn test_duplicate_payment_hash_one_failure_one_success() {
5223 // Topology : A --> B --> C
5224 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5225 let chanmon_cfgs = create_chanmon_cfgs(3);
5226 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5227 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5228 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5230 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5231 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5233 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5234 *nodes[0].network_payment_count.borrow_mut() -= 1;
5235 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5237 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5238 assert_eq!(commitment_txn[0].input.len(), 1);
5239 check_spends!(commitment_txn[0], chan_2.3);
5241 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5242 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5243 check_closed_broadcast!(nodes[1], false);
5244 check_added_monitors!(nodes[1], 1);
5246 let htlc_timeout_tx;
5247 { // Extract one of the two HTLC-Timeout transaction
5248 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5249 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5250 assert_eq!(node_txn.len(), 5);
5251 check_spends!(node_txn[0], commitment_txn[0]);
5252 assert_eq!(node_txn[0].input.len(), 1);
5253 check_spends!(node_txn[1], commitment_txn[0]);
5254 assert_eq!(node_txn[1].input.len(), 1);
5255 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5256 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5257 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5258 check_spends!(node_txn[2], chan_2.3);
5259 check_spends!(node_txn[3], node_txn[2]);
5260 check_spends!(node_txn[4], node_txn[2]);
5261 htlc_timeout_tx = node_txn[1].clone();
5264 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5265 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5266 check_added_monitors!(nodes[2], 3);
5267 let events = nodes[2].node.get_and_clear_pending_msg_events();
5269 MessageSendEvent::UpdateHTLCs { .. } => {},
5270 _ => panic!("Unexpected event"),
5273 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5274 _ => panic!("Unexepected event"),
5276 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5277 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)
5278 check_spends!(htlc_success_txn[2], chan_2.3);
5279 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5280 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5281 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5282 assert_eq!(htlc_success_txn[0].input.len(), 1);
5283 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5284 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5285 assert_eq!(htlc_success_txn[1].input.len(), 1);
5286 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5287 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5288 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5289 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5291 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5292 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5293 expect_pending_htlcs_forwardable!(nodes[1]);
5294 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5295 assert!(htlc_updates.update_add_htlcs.is_empty());
5296 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5297 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5298 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5299 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5300 check_added_monitors!(nodes[1], 1);
5302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5303 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5305 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5306 let events = nodes[0].node.get_and_clear_pending_msg_events();
5307 assert_eq!(events.len(), 1);
5309 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5311 _ => { panic!("Unexpected event"); }
5314 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5316 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5317 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5318 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5319 assert!(updates.update_add_htlcs.is_empty());
5320 assert!(updates.update_fail_htlcs.is_empty());
5321 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5322 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5323 assert!(updates.update_fail_malformed_htlcs.is_empty());
5324 check_added_monitors!(nodes[1], 1);
5326 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5327 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5329 let events = nodes[0].node.get_and_clear_pending_events();
5331 Event::PaymentSent { ref payment_preimage } => {
5332 assert_eq!(*payment_preimage, our_payment_preimage);
5334 _ => panic!("Unexpected event"),
5339 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5340 let chanmon_cfgs = create_chanmon_cfgs(2);
5341 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5342 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5343 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5345 // Create some initial channels
5346 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5348 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5349 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5350 assert_eq!(local_txn[0].input.len(), 1);
5351 check_spends!(local_txn[0], chan_1.3);
5353 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5354 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5355 check_added_monitors!(nodes[1], 1);
5356 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5357 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5358 check_added_monitors!(nodes[1], 1);
5359 let events = nodes[1].node.get_and_clear_pending_msg_events();
5361 MessageSendEvent::UpdateHTLCs { .. } => {},
5362 _ => panic!("Unexpected event"),
5365 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5366 _ => panic!("Unexepected event"),
5369 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5370 assert_eq!(node_txn[0].input.len(), 1);
5371 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5372 check_spends!(node_txn[0], local_txn[0]);
5373 vec![node_txn[0].clone(), node_txn[2].clone()]
5376 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5377 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
5378 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5380 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5381 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5382 assert_eq!(spend_txn.len(), 2);
5383 check_spends!(spend_txn[0], node_txn[0]);
5384 check_spends!(spend_txn[1], node_txn[1]);
5387 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5388 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5389 // unrevoked commitment transaction.
5390 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5391 // a remote RAA before they could be failed backwards (and combinations thereof).
5392 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5393 // use the same payment hashes.
5394 // Thus, we use a six-node network:
5399 // And test where C fails back to A/B when D announces its latest commitment transaction
5400 let chanmon_cfgs = create_chanmon_cfgs(6);
5401 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5402 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5403 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5404 let logger = test_utils::TestLogger::new();
5406 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5407 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5408 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5409 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5410 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5412 // Rebalance and check output sanity...
5413 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5414 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5415 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5417 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5419 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
5421 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
5422 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5423 let our_node_id = &nodes[1].node.get_our_node_id();
5424 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();
5426 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
5428 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
5430 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5432 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5433 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();
5435 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5437 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5440 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5442 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();
5443 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
5446 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
5448 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();
5449 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5451 // Double-check that six of the new HTLC were added
5452 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5453 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5454 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5455 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5457 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5458 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5459 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5460 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5461 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5462 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5463 check_added_monitors!(nodes[4], 0);
5464 expect_pending_htlcs_forwardable!(nodes[4]);
5465 check_added_monitors!(nodes[4], 1);
5467 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5468 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5469 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5470 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5471 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5472 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5474 // Fail 3rd below-dust and 7th above-dust HTLCs
5475 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5476 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5477 check_added_monitors!(nodes[5], 0);
5478 expect_pending_htlcs_forwardable!(nodes[5]);
5479 check_added_monitors!(nodes[5], 1);
5481 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5482 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5483 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5484 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5486 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5488 expect_pending_htlcs_forwardable!(nodes[3]);
5489 check_added_monitors!(nodes[3], 1);
5490 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5491 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5492 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5493 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5494 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5495 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5496 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5497 if deliver_last_raa {
5498 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5500 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5503 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5504 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5505 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5506 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5508 // We now broadcast the latest commitment transaction, which *should* result in failures for
5509 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5510 // the non-broadcast above-dust HTLCs.
5512 // Alternatively, we may broadcast the previous commitment transaction, which should only
5513 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5514 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5516 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5517 if announce_latest {
5518 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5520 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5522 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5523 check_closed_broadcast!(nodes[2], false);
5524 expect_pending_htlcs_forwardable!(nodes[2]);
5525 check_added_monitors!(nodes[2], 3);
5527 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5528 assert_eq!(cs_msgs.len(), 2);
5529 let mut a_done = false;
5530 for msg in cs_msgs {
5532 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5533 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5534 // should be failed-backwards here.
5535 let target = if *node_id == nodes[0].node.get_our_node_id() {
5536 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5537 for htlc in &updates.update_fail_htlcs {
5538 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 });
5540 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5545 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5546 for htlc in &updates.update_fail_htlcs {
5547 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5549 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5550 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5553 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5554 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5555 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5556 if announce_latest {
5557 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5558 if *node_id == nodes[0].node.get_our_node_id() {
5559 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5562 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5564 _ => panic!("Unexpected event"),
5568 let as_events = nodes[0].node.get_and_clear_pending_events();
5569 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5570 let mut as_failds = HashSet::new();
5571 for event in as_events.iter() {
5572 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5573 assert!(as_failds.insert(*payment_hash));
5574 if *payment_hash != payment_hash_2 {
5575 assert_eq!(*rejected_by_dest, deliver_last_raa);
5577 assert!(!rejected_by_dest);
5579 } else { panic!("Unexpected event"); }
5581 assert!(as_failds.contains(&payment_hash_1));
5582 assert!(as_failds.contains(&payment_hash_2));
5583 if announce_latest {
5584 assert!(as_failds.contains(&payment_hash_3));
5585 assert!(as_failds.contains(&payment_hash_5));
5587 assert!(as_failds.contains(&payment_hash_6));
5589 let bs_events = nodes[1].node.get_and_clear_pending_events();
5590 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5591 let mut bs_failds = HashSet::new();
5592 for event in bs_events.iter() {
5593 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5594 assert!(bs_failds.insert(*payment_hash));
5595 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5596 assert_eq!(*rejected_by_dest, deliver_last_raa);
5598 assert!(!rejected_by_dest);
5600 } else { panic!("Unexpected event"); }
5602 assert!(bs_failds.contains(&payment_hash_1));
5603 assert!(bs_failds.contains(&payment_hash_2));
5604 if announce_latest {
5605 assert!(bs_failds.contains(&payment_hash_4));
5607 assert!(bs_failds.contains(&payment_hash_5));
5609 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5610 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5611 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5612 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5613 // PaymentFailureNetworkUpdates.
5614 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5615 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5616 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5617 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5618 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5620 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5621 _ => panic!("Unexpected event"),
5627 fn test_fail_backwards_latest_remote_announce_a() {
5628 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5632 fn test_fail_backwards_latest_remote_announce_b() {
5633 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5637 fn test_fail_backwards_previous_remote_announce() {
5638 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5639 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5640 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5644 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5645 let chanmon_cfgs = create_chanmon_cfgs(2);
5646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5650 // Create some initial channels
5651 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5653 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5654 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5655 assert_eq!(local_txn[0].input.len(), 1);
5656 check_spends!(local_txn[0], chan_1.3);
5658 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5659 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5660 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5661 check_closed_broadcast!(nodes[0], false);
5662 check_added_monitors!(nodes[0], 1);
5664 let htlc_timeout = {
5665 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5666 assert_eq!(node_txn[0].input.len(), 1);
5667 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5668 check_spends!(node_txn[0], local_txn[0]);
5672 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5673 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5674 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5675 expect_payment_failed!(nodes[0], our_payment_hash, true);
5677 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5678 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5679 assert_eq!(spend_txn.len(), 3);
5680 assert_eq!(spend_txn[0], spend_txn[1]);
5681 check_spends!(spend_txn[0], local_txn[0]);
5682 check_spends!(spend_txn[2], htlc_timeout);
5686 fn test_key_derivation_params() {
5687 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5688 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5689 // let us re-derive the channel key set to then derive a delayed_payment_key.
5691 let chanmon_cfgs = create_chanmon_cfgs(3);
5693 // We manually create the node configuration to backup the seed.
5694 let seed = [42; 32];
5695 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5696 let chan_monitor = test_utils::TestChannelMonitor::new(&chanmon_cfgs[0].chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator);
5697 let node = NodeCfg { chain_monitor: &chanmon_cfgs[0].chain_monitor, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chan_monitor, keys_manager, node_seed: seed };
5698 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5699 node_cfgs.remove(0);
5700 node_cfgs.insert(0, node);
5702 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5703 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5705 // Create some initial channels
5706 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5708 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5709 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5710 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5712 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5713 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5714 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5715 assert_eq!(local_txn_1[0].input.len(), 1);
5716 check_spends!(local_txn_1[0], chan_1.3);
5718 // We check funding pubkey are unique
5719 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]));
5720 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]));
5721 if from_0_funding_key_0 == from_1_funding_key_0
5722 || from_0_funding_key_0 == from_1_funding_key_1
5723 || from_0_funding_key_1 == from_1_funding_key_0
5724 || from_0_funding_key_1 == from_1_funding_key_1 {
5725 panic!("Funding pubkeys aren't unique");
5728 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5729 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5730 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5731 check_closed_broadcast!(nodes[0], false);
5732 check_added_monitors!(nodes[0], 1);
5734 let htlc_timeout = {
5735 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5736 assert_eq!(node_txn[0].input.len(), 1);
5737 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5738 check_spends!(node_txn[0], local_txn_1[0]);
5742 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5743 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5744 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5745 expect_payment_failed!(nodes[0], our_payment_hash, true);
5747 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5748 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5749 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5750 assert_eq!(spend_txn.len(), 3);
5751 assert_eq!(spend_txn[0], spend_txn[1]);
5752 check_spends!(spend_txn[0], local_txn_1[0]);
5753 check_spends!(spend_txn[2], htlc_timeout);
5757 fn test_static_output_closing_tx() {
5758 let chanmon_cfgs = create_chanmon_cfgs(2);
5759 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5760 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5761 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5763 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5765 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5766 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5768 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5769 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5770 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5772 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5773 assert_eq!(spend_txn.len(), 1);
5774 check_spends!(spend_txn[0], closing_tx);
5776 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5777 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5779 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5780 assert_eq!(spend_txn.len(), 1);
5781 check_spends!(spend_txn[0], closing_tx);
5784 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5785 let chanmon_cfgs = create_chanmon_cfgs(2);
5786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5788 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5789 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5791 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5793 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5794 // present in B's local commitment transaction, but none of A's commitment transactions.
5795 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5796 check_added_monitors!(nodes[1], 1);
5798 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5799 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5800 let events = nodes[0].node.get_and_clear_pending_events();
5801 assert_eq!(events.len(), 1);
5803 Event::PaymentSent { payment_preimage } => {
5804 assert_eq!(payment_preimage, our_payment_preimage);
5806 _ => panic!("Unexpected event"),
5809 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5810 check_added_monitors!(nodes[0], 1);
5811 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5812 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5813 check_added_monitors!(nodes[1], 1);
5815 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5816 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5817 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5818 header.prev_blockhash = header.block_hash();
5820 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5821 check_closed_broadcast!(nodes[1], false);
5822 check_added_monitors!(nodes[1], 1);
5825 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5826 let chanmon_cfgs = create_chanmon_cfgs(2);
5827 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5828 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5829 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5830 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5831 let logger = test_utils::TestLogger::new();
5833 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5834 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5835 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();
5836 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5837 check_added_monitors!(nodes[0], 1);
5839 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5841 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5842 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5843 // to "time out" the HTLC.
5845 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5847 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5848 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5849 header.prev_blockhash = header.block_hash();
5851 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5852 check_closed_broadcast!(nodes[0], false);
5853 check_added_monitors!(nodes[0], 1);
5856 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5857 let chanmon_cfgs = create_chanmon_cfgs(3);
5858 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5859 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5860 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5861 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5863 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5864 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5865 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5866 // actually revoked.
5867 let htlc_value = if use_dust { 50000 } else { 3000000 };
5868 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5869 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5870 expect_pending_htlcs_forwardable!(nodes[1]);
5871 check_added_monitors!(nodes[1], 1);
5873 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5874 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5875 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5876 check_added_monitors!(nodes[0], 1);
5877 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5878 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5879 check_added_monitors!(nodes[1], 1);
5880 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5881 check_added_monitors!(nodes[1], 1);
5882 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5884 if check_revoke_no_close {
5885 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5886 check_added_monitors!(nodes[0], 1);
5889 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5890 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5891 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5892 header.prev_blockhash = header.block_hash();
5894 if !check_revoke_no_close {
5895 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5896 check_closed_broadcast!(nodes[0], false);
5897 check_added_monitors!(nodes[0], 1);
5899 expect_payment_failed!(nodes[0], our_payment_hash, true);
5903 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5904 // There are only a few cases to test here:
5905 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5906 // broadcastable commitment transactions result in channel closure,
5907 // * its included in an unrevoked-but-previous remote commitment transaction,
5908 // * its included in the latest remote or local commitment transactions.
5909 // We test each of the three possible commitment transactions individually and use both dust and
5911 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5912 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5913 // tested for at least one of the cases in other tests.
5915 fn htlc_claim_single_commitment_only_a() {
5916 do_htlc_claim_local_commitment_only(true);
5917 do_htlc_claim_local_commitment_only(false);
5919 do_htlc_claim_current_remote_commitment_only(true);
5920 do_htlc_claim_current_remote_commitment_only(false);
5924 fn htlc_claim_single_commitment_only_b() {
5925 do_htlc_claim_previous_remote_commitment_only(true, false);
5926 do_htlc_claim_previous_remote_commitment_only(false, false);
5927 do_htlc_claim_previous_remote_commitment_only(true, true);
5928 do_htlc_claim_previous_remote_commitment_only(false, true);
5933 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5934 let chanmon_cfgs = create_chanmon_cfgs(2);
5935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5937 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5938 //Force duplicate channel ids
5939 for node in nodes.iter() {
5940 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5943 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5944 let channel_value_satoshis=10000;
5945 let push_msat=10001;
5946 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5947 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5948 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5950 //Create a second channel with a channel_id collision
5951 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5955 fn bolt2_open_channel_sending_node_checks_part2() {
5956 let chanmon_cfgs = create_chanmon_cfgs(2);
5957 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5958 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5959 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5961 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5962 let channel_value_satoshis=2^24;
5963 let push_msat=10001;
5964 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5966 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5967 let channel_value_satoshis=10000;
5968 // Test when push_msat is equal to 1000 * funding_satoshis.
5969 let push_msat=1000*channel_value_satoshis+1;
5970 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5972 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5973 let channel_value_satoshis=10000;
5974 let push_msat=10001;
5975 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
5976 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5977 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5979 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5980 // 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
5981 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5983 // 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.
5984 assert!(BREAKDOWN_TIMEOUT>0);
5985 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5987 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5988 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5989 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5991 // 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.
5992 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5993 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5994 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5995 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5996 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5999 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6000 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6001 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6002 // is no longer affordable once it's freed.
6004 fn test_fail_holding_cell_htlc_upon_free() {
6005 let chanmon_cfgs = create_chanmon_cfgs(2);
6006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6008 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6009 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6010 let logger = test_utils::TestLogger::new();
6012 // First nodes[0] generates an update_fee, setting the channel's
6013 // pending_update_fee.
6014 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6015 check_added_monitors!(nodes[0], 1);
6017 let events = nodes[0].node.get_and_clear_pending_msg_events();
6018 assert_eq!(events.len(), 1);
6019 let (update_msg, commitment_signed) = match events[0] {
6020 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6021 (update_fee.as_ref(), commitment_signed)
6023 _ => panic!("Unexpected event"),
6026 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6028 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6029 let channel_reserve = chan_stat.channel_reserve_msat;
6030 let feerate = get_feerate!(nodes[0], chan.2);
6032 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6033 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6034 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6035 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6036 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();
6038 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6039 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6040 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6041 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6043 // Flush the pending fee update.
6044 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6045 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6046 check_added_monitors!(nodes[1], 1);
6047 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6048 check_added_monitors!(nodes[0], 1);
6050 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6051 // HTLC, but now that the fee has been raised the payment will now fail, causing
6052 // us to surface its failure to the user.
6053 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6054 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6055 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6056 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);
6057 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6059 // Check that the payment failed to be sent out.
6060 let events = nodes[0].node.get_and_clear_pending_events();
6061 assert_eq!(events.len(), 1);
6063 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6064 assert_eq!(our_payment_hash.clone(), *payment_hash);
6065 assert_eq!(*rejected_by_dest, false);
6066 assert_eq!(*error_code, None);
6067 assert_eq!(*error_data, None);
6069 _ => panic!("Unexpected event"),
6073 // Test that if multiple HTLCs are released from the holding cell and one is
6074 // valid but the other is no longer valid upon release, the valid HTLC can be
6075 // successfully completed while the other one fails as expected.
6077 fn test_free_and_fail_holding_cell_htlcs() {
6078 let chanmon_cfgs = create_chanmon_cfgs(2);
6079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6081 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6082 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6083 let logger = test_utils::TestLogger::new();
6085 // First nodes[0] generates an update_fee, setting the channel's
6086 // pending_update_fee.
6087 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6088 check_added_monitors!(nodes[0], 1);
6090 let events = nodes[0].node.get_and_clear_pending_msg_events();
6091 assert_eq!(events.len(), 1);
6092 let (update_msg, commitment_signed) = match events[0] {
6093 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6094 (update_fee.as_ref(), commitment_signed)
6096 _ => panic!("Unexpected event"),
6099 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6101 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6102 let channel_reserve = chan_stat.channel_reserve_msat;
6103 let feerate = get_feerate!(nodes[0], chan.2);
6105 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6106 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6108 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6109 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6110 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6111 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();
6112 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();
6114 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6115 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6116 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6117 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6118 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6119 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6120 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6122 // Flush the pending fee update.
6123 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6124 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6125 check_added_monitors!(nodes[1], 1);
6126 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6127 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6128 check_added_monitors!(nodes[0], 2);
6130 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6131 // but now that the fee has been raised the second payment will now fail, causing us
6132 // to surface its failure to the user. The first payment should succeed.
6133 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6134 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6135 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6136 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);
6137 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6139 // Check that the second payment failed to be sent out.
6140 let events = nodes[0].node.get_and_clear_pending_events();
6141 assert_eq!(events.len(), 1);
6143 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6144 assert_eq!(payment_hash_2.clone(), *payment_hash);
6145 assert_eq!(*rejected_by_dest, false);
6146 assert_eq!(*error_code, None);
6147 assert_eq!(*error_data, None);
6149 _ => panic!("Unexpected event"),
6152 // Complete the first payment and the RAA from the fee update.
6153 let (payment_event, send_raa_event) = {
6154 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6155 assert_eq!(msgs.len(), 2);
6156 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6158 let raa = match send_raa_event {
6159 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6160 _ => panic!("Unexpected event"),
6162 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6163 check_added_monitors!(nodes[1], 1);
6164 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6165 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6166 let events = nodes[1].node.get_and_clear_pending_events();
6167 assert_eq!(events.len(), 1);
6169 Event::PendingHTLCsForwardable { .. } => {},
6170 _ => panic!("Unexpected event"),
6172 nodes[1].node.process_pending_htlc_forwards();
6173 let events = nodes[1].node.get_and_clear_pending_events();
6174 assert_eq!(events.len(), 1);
6176 Event::PaymentReceived { .. } => {},
6177 _ => panic!("Unexpected event"),
6179 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6180 check_added_monitors!(nodes[1], 1);
6181 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6182 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6183 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6184 let events = nodes[0].node.get_and_clear_pending_events();
6185 assert_eq!(events.len(), 1);
6187 Event::PaymentSent { ref payment_preimage } => {
6188 assert_eq!(*payment_preimage, payment_preimage_1);
6190 _ => panic!("Unexpected event"),
6194 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6195 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6196 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6199 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6200 let chanmon_cfgs = create_chanmon_cfgs(3);
6201 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6202 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6203 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6204 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6205 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6206 let logger = test_utils::TestLogger::new();
6208 // First nodes[1] generates an update_fee, setting the channel's
6209 // pending_update_fee.
6210 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6211 check_added_monitors!(nodes[1], 1);
6213 let events = nodes[1].node.get_and_clear_pending_msg_events();
6214 assert_eq!(events.len(), 1);
6215 let (update_msg, commitment_signed) = match events[0] {
6216 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6217 (update_fee.as_ref(), commitment_signed)
6219 _ => panic!("Unexpected event"),
6222 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6224 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6225 let channel_reserve = chan_stat.channel_reserve_msat;
6226 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6228 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6230 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6231 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6232 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6233 let payment_event = {
6234 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6235 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();
6236 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6237 check_added_monitors!(nodes[0], 1);
6239 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6240 assert_eq!(events.len(), 1);
6242 SendEvent::from_event(events.remove(0))
6244 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6245 check_added_monitors!(nodes[1], 0);
6246 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6247 expect_pending_htlcs_forwardable!(nodes[1]);
6249 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6250 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6252 // Flush the pending fee update.
6253 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6254 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6255 check_added_monitors!(nodes[2], 1);
6256 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6257 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6258 check_added_monitors!(nodes[1], 2);
6260 // A final RAA message is generated to finalize the fee update.
6261 let events = nodes[1].node.get_and_clear_pending_msg_events();
6262 assert_eq!(events.len(), 1);
6264 let raa_msg = match &events[0] {
6265 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6268 _ => panic!("Unexpected event"),
6271 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6272 check_added_monitors!(nodes[2], 1);
6273 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6275 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6276 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6277 assert_eq!(process_htlc_forwards_event.len(), 1);
6278 match &process_htlc_forwards_event[0] {
6279 &Event::PendingHTLCsForwardable { .. } => {},
6280 _ => panic!("Unexpected event"),
6283 // In response, we call ChannelManager's process_pending_htlc_forwards
6284 nodes[1].node.process_pending_htlc_forwards();
6285 check_added_monitors!(nodes[1], 1);
6287 // This causes the HTLC to be failed backwards.
6288 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6289 assert_eq!(fail_event.len(), 1);
6290 let (fail_msg, commitment_signed) = match &fail_event[0] {
6291 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6292 assert_eq!(updates.update_add_htlcs.len(), 0);
6293 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6294 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6295 assert_eq!(updates.update_fail_htlcs.len(), 1);
6296 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6298 _ => panic!("Unexpected event"),
6301 // Pass the failure messages back to nodes[0].
6302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6303 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6305 // Complete the HTLC failure+removal process.
6306 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6307 check_added_monitors!(nodes[0], 1);
6308 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6309 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6310 check_added_monitors!(nodes[1], 2);
6311 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6312 assert_eq!(final_raa_event.len(), 1);
6313 let raa = match &final_raa_event[0] {
6314 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6315 _ => panic!("Unexpected event"),
6317 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6318 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6319 assert_eq!(fail_msg_event.len(), 1);
6320 match &fail_msg_event[0] {
6321 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6322 _ => panic!("Unexpected event"),
6324 let failure_event = nodes[0].node.get_and_clear_pending_events();
6325 assert_eq!(failure_event.len(), 1);
6326 match &failure_event[0] {
6327 &Event::PaymentFailed { rejected_by_dest, .. } => {
6328 assert!(!rejected_by_dest);
6330 _ => panic!("Unexpected event"),
6332 check_added_monitors!(nodes[0], 1);
6335 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6336 // 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.
6337 //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.
6340 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6341 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6342 let chanmon_cfgs = create_chanmon_cfgs(2);
6343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6345 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6346 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6348 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6349 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6350 let logger = test_utils::TestLogger::new();
6351 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();
6352 route.paths[0][0].fee_msat = 100;
6354 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6355 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6356 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6357 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6361 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6362 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6363 let chanmon_cfgs = create_chanmon_cfgs(2);
6364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6368 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6370 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6371 let logger = test_utils::TestLogger::new();
6372 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();
6373 route.paths[0][0].fee_msat = 0;
6374 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6375 assert_eq!(err, "Cannot send 0-msat HTLC"));
6377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6378 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6382 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6383 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6384 let chanmon_cfgs = create_chanmon_cfgs(2);
6385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6387 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6388 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6390 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6391 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6392 let logger = test_utils::TestLogger::new();
6393 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();
6394 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6395 check_added_monitors!(nodes[0], 1);
6396 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6397 updates.update_add_htlcs[0].amount_msat = 0;
6399 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6400 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6401 check_closed_broadcast!(nodes[1], true).unwrap();
6402 check_added_monitors!(nodes[1], 1);
6406 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6407 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6408 //It is enforced when constructing a route.
6409 let chanmon_cfgs = create_chanmon_cfgs(2);
6410 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6411 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6412 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6413 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6414 let logger = test_utils::TestLogger::new();
6416 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6418 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6419 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();
6420 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6421 assert_eq!(err, &"Channel CLTV overflowed?"));
6425 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6426 //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.
6427 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6428 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6429 let chanmon_cfgs = create_chanmon_cfgs(2);
6430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6432 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6433 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6434 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6436 let logger = test_utils::TestLogger::new();
6437 for i in 0..max_accepted_htlcs {
6438 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6439 let payment_event = {
6440 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6441 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();
6442 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6443 check_added_monitors!(nodes[0], 1);
6445 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6446 assert_eq!(events.len(), 1);
6447 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6448 assert_eq!(htlcs[0].htlc_id, i);
6452 SendEvent::from_event(events.remove(0))
6454 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6455 check_added_monitors!(nodes[1], 0);
6456 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6458 expect_pending_htlcs_forwardable!(nodes[1]);
6459 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6461 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6462 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6463 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();
6464 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6465 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6467 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6468 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6472 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6473 //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.
6474 let chanmon_cfgs = create_chanmon_cfgs(2);
6475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6477 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6478 let channel_value = 100000;
6479 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6480 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6482 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6484 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6485 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6486 let logger = test_utils::TestLogger::new();
6487 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();
6488 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6489 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)));
6491 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6492 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);
6494 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6497 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6499 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6500 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6501 let chanmon_cfgs = create_chanmon_cfgs(2);
6502 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6503 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6504 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6505 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6506 let htlc_minimum_msat: u64;
6508 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6509 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6510 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6513 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6514 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6515 let logger = test_utils::TestLogger::new();
6516 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();
6517 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6518 check_added_monitors!(nodes[0], 1);
6519 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6520 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6521 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6522 assert!(nodes[1].node.list_channels().is_empty());
6523 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6524 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()));
6525 check_added_monitors!(nodes[1], 1);
6529 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6530 //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
6531 let chanmon_cfgs = create_chanmon_cfgs(2);
6532 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6533 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6534 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6535 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6536 let logger = test_utils::TestLogger::new();
6538 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6539 let channel_reserve = chan_stat.channel_reserve_msat;
6540 let feerate = get_feerate!(nodes[0], chan.2);
6541 // The 2* and +1 are for the fee spike reserve.
6542 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6544 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6545 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6546 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6547 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_can_send, TEST_FINAL_CLTV, &logger).unwrap();
6548 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6549 check_added_monitors!(nodes[0], 1);
6550 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6552 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6553 // at this time channel-initiatee receivers are not required to enforce that senders
6554 // respect the fee_spike_reserve.
6555 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6556 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6558 assert!(nodes[1].node.list_channels().is_empty());
6559 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6560 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6561 check_added_monitors!(nodes[1], 1);
6565 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6566 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6567 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6568 let chanmon_cfgs = create_chanmon_cfgs(2);
6569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6572 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6573 let logger = test_utils::TestLogger::new();
6575 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6576 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6578 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6579 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();
6581 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6582 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6583 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6584 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6586 let mut msg = msgs::UpdateAddHTLC {
6590 payment_hash: our_payment_hash,
6591 cltv_expiry: htlc_cltv,
6592 onion_routing_packet: onion_packet.clone(),
6595 for i in 0..super::channel::OUR_MAX_HTLCS {
6596 msg.htlc_id = i as u64;
6597 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6599 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6600 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6602 assert!(nodes[1].node.list_channels().is_empty());
6603 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6604 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6605 check_added_monitors!(nodes[1], 1);
6609 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6610 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6611 let chanmon_cfgs = create_chanmon_cfgs(2);
6612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6614 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6615 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6616 let logger = test_utils::TestLogger::new();
6618 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6619 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6620 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();
6621 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6622 check_added_monitors!(nodes[0], 1);
6623 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6624 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6625 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6627 assert!(nodes[1].node.list_channels().is_empty());
6628 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6629 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6630 check_added_monitors!(nodes[1], 1);
6634 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6635 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6636 let chanmon_cfgs = create_chanmon_cfgs(2);
6637 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6638 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6639 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6640 let logger = test_utils::TestLogger::new();
6642 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6643 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6644 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6645 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6646 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6647 check_added_monitors!(nodes[0], 1);
6648 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6649 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6650 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6652 assert!(nodes[1].node.list_channels().is_empty());
6653 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6654 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6655 check_added_monitors!(nodes[1], 1);
6659 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6660 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6661 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6662 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6663 let chanmon_cfgs = create_chanmon_cfgs(2);
6664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6666 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6667 let logger = test_utils::TestLogger::new();
6669 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6670 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6671 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6672 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();
6673 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6674 check_added_monitors!(nodes[0], 1);
6675 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6676 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6678 //Disconnect and Reconnect
6679 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6680 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6681 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6682 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6683 assert_eq!(reestablish_1.len(), 1);
6684 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6685 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6686 assert_eq!(reestablish_2.len(), 1);
6687 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6688 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6689 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6690 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6693 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6694 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6695 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6696 check_added_monitors!(nodes[1], 1);
6697 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6699 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6701 assert!(nodes[1].node.list_channels().is_empty());
6702 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6703 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6704 check_added_monitors!(nodes[1], 1);
6708 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6709 //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.
6711 let chanmon_cfgs = create_chanmon_cfgs(2);
6712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6715 let logger = test_utils::TestLogger::new();
6716 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6717 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6718 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6719 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();
6720 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6722 check_added_monitors!(nodes[0], 1);
6723 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6724 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6726 let update_msg = msgs::UpdateFulfillHTLC{
6729 payment_preimage: our_payment_preimage,
6732 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6734 assert!(nodes[0].node.list_channels().is_empty());
6735 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6736 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()));
6737 check_added_monitors!(nodes[0], 1);
6741 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6742 //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.
6744 let chanmon_cfgs = create_chanmon_cfgs(2);
6745 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6746 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6747 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6748 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6749 let logger = test_utils::TestLogger::new();
6751 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6752 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6753 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();
6754 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6755 check_added_monitors!(nodes[0], 1);
6756 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6757 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6759 let update_msg = msgs::UpdateFailHTLC{
6762 reason: msgs::OnionErrorPacket { data: Vec::new()},
6765 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6767 assert!(nodes[0].node.list_channels().is_empty());
6768 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6769 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()));
6770 check_added_monitors!(nodes[0], 1);
6774 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6775 //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.
6777 let chanmon_cfgs = create_chanmon_cfgs(2);
6778 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6779 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6780 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6781 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6782 let logger = test_utils::TestLogger::new();
6784 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6785 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6786 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();
6787 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6788 check_added_monitors!(nodes[0], 1);
6789 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6790 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6792 let update_msg = msgs::UpdateFailMalformedHTLC{
6795 sha256_of_onion: [1; 32],
6796 failure_code: 0x8000,
6799 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6801 assert!(nodes[0].node.list_channels().is_empty());
6802 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6803 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()));
6804 check_added_monitors!(nodes[0], 1);
6808 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6809 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6811 let chanmon_cfgs = create_chanmon_cfgs(2);
6812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6814 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6815 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6817 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6819 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6820 check_added_monitors!(nodes[1], 1);
6822 let events = nodes[1].node.get_and_clear_pending_msg_events();
6823 assert_eq!(events.len(), 1);
6824 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6826 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, .. } } => {
6827 assert!(update_add_htlcs.is_empty());
6828 assert_eq!(update_fulfill_htlcs.len(), 1);
6829 assert!(update_fail_htlcs.is_empty());
6830 assert!(update_fail_malformed_htlcs.is_empty());
6831 assert!(update_fee.is_none());
6832 update_fulfill_htlcs[0].clone()
6834 _ => panic!("Unexpected event"),
6838 update_fulfill_msg.htlc_id = 1;
6840 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6842 assert!(nodes[0].node.list_channels().is_empty());
6843 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6844 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6845 check_added_monitors!(nodes[0], 1);
6849 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6850 //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.
6852 let chanmon_cfgs = create_chanmon_cfgs(2);
6853 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6854 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6855 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6856 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6858 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6860 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6861 check_added_monitors!(nodes[1], 1);
6863 let events = nodes[1].node.get_and_clear_pending_msg_events();
6864 assert_eq!(events.len(), 1);
6865 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6867 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, .. } } => {
6868 assert!(update_add_htlcs.is_empty());
6869 assert_eq!(update_fulfill_htlcs.len(), 1);
6870 assert!(update_fail_htlcs.is_empty());
6871 assert!(update_fail_malformed_htlcs.is_empty());
6872 assert!(update_fee.is_none());
6873 update_fulfill_htlcs[0].clone()
6875 _ => panic!("Unexpected event"),
6879 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6881 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6883 assert!(nodes[0].node.list_channels().is_empty());
6884 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6885 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6886 check_added_monitors!(nodes[0], 1);
6890 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6891 //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.
6893 let chanmon_cfgs = create_chanmon_cfgs(2);
6894 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6895 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6896 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6897 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6898 let logger = test_utils::TestLogger::new();
6900 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6901 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6902 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();
6903 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6904 check_added_monitors!(nodes[0], 1);
6906 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6907 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6909 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6910 check_added_monitors!(nodes[1], 0);
6911 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6913 let events = nodes[1].node.get_and_clear_pending_msg_events();
6915 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6917 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, .. } } => {
6918 assert!(update_add_htlcs.is_empty());
6919 assert!(update_fulfill_htlcs.is_empty());
6920 assert!(update_fail_htlcs.is_empty());
6921 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6922 assert!(update_fee.is_none());
6923 update_fail_malformed_htlcs[0].clone()
6925 _ => panic!("Unexpected event"),
6928 update_msg.failure_code &= !0x8000;
6929 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6931 assert!(nodes[0].node.list_channels().is_empty());
6932 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6933 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6934 check_added_monitors!(nodes[0], 1);
6938 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6939 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6940 // * 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.
6942 let chanmon_cfgs = create_chanmon_cfgs(3);
6943 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6944 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6945 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6946 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6947 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6948 let logger = test_utils::TestLogger::new();
6950 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6953 let mut payment_event = {
6954 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6955 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();
6956 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6957 check_added_monitors!(nodes[0], 1);
6958 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6959 assert_eq!(events.len(), 1);
6960 SendEvent::from_event(events.remove(0))
6962 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6963 check_added_monitors!(nodes[1], 0);
6964 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6965 expect_pending_htlcs_forwardable!(nodes[1]);
6966 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6967 assert_eq!(events_2.len(), 1);
6968 check_added_monitors!(nodes[1], 1);
6969 payment_event = SendEvent::from_event(events_2.remove(0));
6970 assert_eq!(payment_event.msgs.len(), 1);
6973 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6974 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6975 check_added_monitors!(nodes[2], 0);
6976 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6978 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6979 assert_eq!(events_3.len(), 1);
6980 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6982 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 } } => {
6983 assert!(update_add_htlcs.is_empty());
6984 assert!(update_fulfill_htlcs.is_empty());
6985 assert!(update_fail_htlcs.is_empty());
6986 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6987 assert!(update_fee.is_none());
6988 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6990 _ => panic!("Unexpected event"),
6994 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6996 check_added_monitors!(nodes[1], 0);
6997 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6998 expect_pending_htlcs_forwardable!(nodes[1]);
6999 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7000 assert_eq!(events_4.len(), 1);
7002 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7004 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, .. } } => {
7005 assert!(update_add_htlcs.is_empty());
7006 assert!(update_fulfill_htlcs.is_empty());
7007 assert_eq!(update_fail_htlcs.len(), 1);
7008 assert!(update_fail_malformed_htlcs.is_empty());
7009 assert!(update_fee.is_none());
7011 _ => panic!("Unexpected event"),
7014 check_added_monitors!(nodes[1], 1);
7017 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7018 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7019 // 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
7020 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7022 let chanmon_cfgs = create_chanmon_cfgs(2);
7023 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7024 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7025 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7026 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7028 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7030 // We route 2 dust-HTLCs between A and B
7031 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7032 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7033 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7035 // Cache one local commitment tx as previous
7036 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7038 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7039 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7040 check_added_monitors!(nodes[1], 0);
7041 expect_pending_htlcs_forwardable!(nodes[1]);
7042 check_added_monitors!(nodes[1], 1);
7044 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7045 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7046 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7047 check_added_monitors!(nodes[0], 1);
7049 // Cache one local commitment tx as lastest
7050 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7052 let events = nodes[0].node.get_and_clear_pending_msg_events();
7054 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7055 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7057 _ => panic!("Unexpected event"),
7060 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7061 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7063 _ => panic!("Unexpected event"),
7066 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7067 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7068 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7070 if announce_latest {
7071 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7073 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7076 check_closed_broadcast!(nodes[0], false);
7077 check_added_monitors!(nodes[0], 1);
7079 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7080 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7081 let events = nodes[0].node.get_and_clear_pending_events();
7082 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7083 assert_eq!(events.len(), 2);
7084 let mut first_failed = false;
7085 for event in events {
7087 Event::PaymentFailed { payment_hash, .. } => {
7088 if payment_hash == payment_hash_1 {
7089 assert!(!first_failed);
7090 first_failed = true;
7092 assert_eq!(payment_hash, payment_hash_2);
7095 _ => panic!("Unexpected event"),
7101 fn test_failure_delay_dust_htlc_local_commitment() {
7102 do_test_failure_delay_dust_htlc_local_commitment(true);
7103 do_test_failure_delay_dust_htlc_local_commitment(false);
7107 fn test_no_failure_dust_htlc_local_commitment() {
7108 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7109 // prone to error, we test here that a dummy transaction don't fail them.
7111 let chanmon_cfgs = create_chanmon_cfgs(2);
7112 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7113 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7114 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7115 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7118 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7120 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7121 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7123 // We route 2 dust-HTLCs between A and B
7124 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7125 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7127 // Build a dummy invalid transaction trying to spend a commitment tx
7129 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7130 script_sig: Script::new(),
7132 witness: Vec::new(),
7136 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7140 let dummy_tx = Transaction {
7147 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7148 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
7149 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7150 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7151 // We broadcast a few more block to check everything is all right
7152 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.block_hash());
7153 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7154 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7156 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7157 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7160 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7161 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7162 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7163 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7164 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7165 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7166 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7168 let chanmon_cfgs = create_chanmon_cfgs(3);
7169 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7170 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7171 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7172 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7174 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7176 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7177 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7179 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7180 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7182 // We revoked bs_commitment_tx
7184 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7185 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7188 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7189 let mut timeout_tx = Vec::new();
7191 // We fail dust-HTLC 1 by broadcast of local commitment tx
7192 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7193 check_closed_broadcast!(nodes[0], false);
7194 check_added_monitors!(nodes[0], 1);
7195 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7196 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7197 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7198 expect_payment_failed!(nodes[0], dust_hash, true);
7199 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7200 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7201 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7202 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7203 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7204 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7205 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7206 expect_payment_failed!(nodes[0], non_dust_hash, true);
7208 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7209 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7210 check_closed_broadcast!(nodes[0], false);
7211 check_added_monitors!(nodes[0], 1);
7212 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7213 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7214 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7215 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7217 expect_payment_failed!(nodes[0], dust_hash, true);
7218 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7219 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7220 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7221 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7222 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7223 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7224 expect_payment_failed!(nodes[0], non_dust_hash, true);
7226 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7228 let events = nodes[0].node.get_and_clear_pending_events();
7229 assert_eq!(events.len(), 2);
7232 Event::PaymentFailed { payment_hash, .. } => {
7233 if payment_hash == dust_hash { first = true; }
7234 else { first = false; }
7236 _ => panic!("Unexpected event"),
7239 Event::PaymentFailed { payment_hash, .. } => {
7240 if first { assert_eq!(payment_hash, non_dust_hash); }
7241 else { assert_eq!(payment_hash, dust_hash); }
7243 _ => panic!("Unexpected event"),
7250 fn test_sweep_outbound_htlc_failure_update() {
7251 do_test_sweep_outbound_htlc_failure_update(false, true);
7252 do_test_sweep_outbound_htlc_failure_update(false, false);
7253 do_test_sweep_outbound_htlc_failure_update(true, false);
7257 fn test_upfront_shutdown_script() {
7258 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7259 // enforce it at shutdown message
7261 let mut config = UserConfig::default();
7262 config.channel_options.announced_channel = true;
7263 config.peer_channel_config_limits.force_announced_channel_preference = false;
7264 config.channel_options.commit_upfront_shutdown_pubkey = false;
7265 let user_cfgs = [None, Some(config), None];
7266 let chanmon_cfgs = create_chanmon_cfgs(3);
7267 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7268 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7269 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7271 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7272 let flags = InitFeatures::known();
7273 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7274 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7275 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7276 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7277 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7278 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7279 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()));
7280 check_added_monitors!(nodes[2], 1);
7282 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7283 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7284 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7285 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7286 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7287 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7288 let events = nodes[2].node.get_and_clear_pending_msg_events();
7289 assert_eq!(events.len(), 1);
7291 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7292 _ => panic!("Unexpected event"),
7295 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7296 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7297 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7298 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7299 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7300 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7301 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7302 let events = nodes[1].node.get_and_clear_pending_msg_events();
7303 assert_eq!(events.len(), 1);
7305 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7306 _ => panic!("Unexpected event"),
7309 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7310 // channel smoothly, opt-out is from channel initiator here
7311 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7312 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7313 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7314 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7315 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7316 let events = nodes[0].node.get_and_clear_pending_msg_events();
7317 assert_eq!(events.len(), 1);
7319 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7320 _ => panic!("Unexpected event"),
7323 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7324 //// channel smoothly
7325 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7326 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7327 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7328 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7329 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7330 let events = nodes[0].node.get_and_clear_pending_msg_events();
7331 assert_eq!(events.len(), 2);
7333 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7334 _ => panic!("Unexpected event"),
7337 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7338 _ => panic!("Unexpected event"),
7343 fn test_user_configurable_csv_delay() {
7344 // We test our channel constructors yield errors when we pass them absurd csv delay
7346 let mut low_our_to_self_config = UserConfig::default();
7347 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7348 let mut high_their_to_self_config = UserConfig::default();
7349 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7350 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7351 let chanmon_cfgs = create_chanmon_cfgs(2);
7352 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7353 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7354 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7356 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7357 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7358 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) {
7360 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())); },
7361 _ => panic!("Unexpected event"),
7363 } else { assert!(false) }
7365 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7366 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7367 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7368 open_channel.to_self_delay = 200;
7369 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) {
7371 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())); },
7372 _ => panic!("Unexpected event"),
7374 } else { assert!(false); }
7376 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7377 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7378 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()));
7379 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7380 accept_channel.to_self_delay = 200;
7381 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7382 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7384 &ErrorAction::SendErrorMessage { ref msg } => {
7385 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()));
7387 _ => { assert!(false); }
7389 } else { assert!(false); }
7391 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7392 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7393 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7394 open_channel.to_self_delay = 200;
7395 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) {
7397 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())); },
7398 _ => panic!("Unexpected event"),
7400 } else { assert!(false); }
7404 fn test_data_loss_protect() {
7405 // We want to be sure that :
7406 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7407 // * we close channel in case of detecting other being fallen behind
7408 // * we are able to claim our own outputs thanks to to_remote being static
7416 let chanmon_cfgs = create_chanmon_cfgs(2);
7417 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7418 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7419 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7421 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7423 // Cache node A state before any channel update
7424 let previous_node_state = nodes[0].node.encode();
7425 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7426 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7428 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7429 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7431 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7432 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7434 // Restore node A from previous state
7435 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7436 let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7437 chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7438 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7439 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7440 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7441 monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7443 let mut channel_monitors = HashMap::new();
7444 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7445 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7446 keys_manager: &keys_manager,
7447 fee_estimator: &fee_estimator,
7450 tx_broadcaster: &tx_broadcaster,
7451 default_config: UserConfig::default(),
7455 nodes[0].node = &node_state_0;
7456 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7457 nodes[0].chan_monitor = &monitor;
7458 nodes[0].chain_monitor = &chain_monitor;
7460 nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7461 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7462 nodes[0].block_notifier.register_listener(nodes[0].node);
7464 check_added_monitors!(nodes[0], 1);
7466 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7467 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7469 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7471 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7472 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7473 check_added_monitors!(nodes[0], 1);
7476 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7477 assert_eq!(node_txn.len(), 0);
7480 let mut reestablish_1 = Vec::with_capacity(1);
7481 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7482 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7483 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7484 reestablish_1.push(msg.clone());
7485 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7486 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7488 &ErrorAction::SendErrorMessage { ref msg } => {
7489 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");
7491 _ => panic!("Unexpected event!"),
7494 panic!("Unexpected event")
7498 // Check we close channel detecting A is fallen-behind
7499 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7500 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7501 check_added_monitors!(nodes[1], 1);
7504 // Check A is able to claim to_remote output
7505 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7506 assert_eq!(node_txn.len(), 1);
7507 check_spends!(node_txn[0], chan.3);
7508 assert_eq!(node_txn[0].output.len(), 2);
7509 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7510 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7511 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7512 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7513 assert_eq!(spend_txn.len(), 1);
7514 check_spends!(spend_txn[0], node_txn[0]);
7518 fn test_check_htlc_underpaying() {
7519 // Send payment through A -> B but A is maliciously
7520 // sending a probe payment (i.e less than expected value0
7521 // to B, B should refuse payment.
7523 let chanmon_cfgs = create_chanmon_cfgs(2);
7524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7528 // Create some initial channels
7529 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7531 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7533 // Node 3 is expecting payment of 100_000 but receive 10_000,
7534 // fail htlc like we didn't know the preimage.
7535 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7536 nodes[1].node.process_pending_htlc_forwards();
7538 let events = nodes[1].node.get_and_clear_pending_msg_events();
7539 assert_eq!(events.len(), 1);
7540 let (update_fail_htlc, commitment_signed) = match events[0] {
7541 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 } } => {
7542 assert!(update_add_htlcs.is_empty());
7543 assert!(update_fulfill_htlcs.is_empty());
7544 assert_eq!(update_fail_htlcs.len(), 1);
7545 assert!(update_fail_malformed_htlcs.is_empty());
7546 assert!(update_fee.is_none());
7547 (update_fail_htlcs[0].clone(), commitment_signed)
7549 _ => panic!("Unexpected event"),
7551 check_added_monitors!(nodes[1], 1);
7553 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7554 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7556 // 10_000 msat as u64, followed by a height of 99 as u32
7557 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7558 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7559 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7560 nodes[1].node.get_and_clear_pending_events();
7564 fn test_announce_disable_channels() {
7565 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7566 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7568 let chanmon_cfgs = create_chanmon_cfgs(2);
7569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7573 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7574 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7575 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7578 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7579 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7581 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7582 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7583 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7584 assert_eq!(msg_events.len(), 3);
7585 for e in msg_events {
7587 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7588 let short_id = msg.contents.short_channel_id;
7589 // Check generated channel_update match list in PendingChannelUpdate
7590 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7591 panic!("Generated ChannelUpdate for wrong chan!");
7594 _ => panic!("Unexpected event"),
7598 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7599 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7600 assert_eq!(reestablish_1.len(), 3);
7601 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7602 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7603 assert_eq!(reestablish_2.len(), 3);
7605 // Reestablish chan_1
7606 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7607 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7608 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7609 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7610 // Reestablish chan_2
7611 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7612 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7613 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7614 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7615 // Reestablish chan_3
7616 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7617 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7618 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7619 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7621 nodes[0].node.timer_chan_freshness_every_min();
7622 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7626 fn test_bump_penalty_txn_on_revoked_commitment() {
7627 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7628 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7630 let chanmon_cfgs = create_chanmon_cfgs(2);
7631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7633 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7635 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7636 let logger = test_utils::TestLogger::new();
7639 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7640 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7641 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();
7642 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7644 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7645 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7646 assert_eq!(revoked_txn[0].output.len(), 4);
7647 assert_eq!(revoked_txn[0].input.len(), 1);
7648 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7649 let revoked_txid = revoked_txn[0].txid();
7651 let mut penalty_sum = 0;
7652 for outp in revoked_txn[0].output.iter() {
7653 if outp.script_pubkey.is_v0_p2wsh() {
7654 penalty_sum += outp.value;
7658 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7659 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7661 // Actually revoke tx by claiming a HTLC
7662 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7663 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7664 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7665 check_added_monitors!(nodes[1], 1);
7667 // One or more justice tx should have been broadcast, check it
7671 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7672 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7673 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7674 assert_eq!(node_txn[0].output.len(), 1);
7675 check_spends!(node_txn[0], revoked_txn[0]);
7676 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7677 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7678 penalty_1 = node_txn[0].txid();
7682 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7683 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.block_hash());
7684 let mut penalty_2 = penalty_1;
7685 let mut feerate_2 = 0;
7687 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7688 assert_eq!(node_txn.len(), 1);
7689 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7690 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7691 assert_eq!(node_txn[0].output.len(), 1);
7692 check_spends!(node_txn[0], revoked_txn[0]);
7693 penalty_2 = node_txn[0].txid();
7694 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7695 assert_ne!(penalty_2, penalty_1);
7696 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7697 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7698 // Verify 25% bump heuristic
7699 assert!(feerate_2 * 100 >= feerate_1 * 125);
7703 assert_ne!(feerate_2, 0);
7705 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7706 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7708 let mut feerate_3 = 0;
7710 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7711 assert_eq!(node_txn.len(), 1);
7712 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7713 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7714 assert_eq!(node_txn[0].output.len(), 1);
7715 check_spends!(node_txn[0], revoked_txn[0]);
7716 penalty_3 = node_txn[0].txid();
7717 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7718 assert_ne!(penalty_3, penalty_2);
7719 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7720 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7721 // Verify 25% bump heuristic
7722 assert!(feerate_3 * 100 >= feerate_2 * 125);
7726 assert_ne!(feerate_3, 0);
7728 nodes[1].node.get_and_clear_pending_events();
7729 nodes[1].node.get_and_clear_pending_msg_events();
7733 fn test_bump_penalty_txn_on_revoked_htlcs() {
7734 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7735 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7737 let chanmon_cfgs = create_chanmon_cfgs(2);
7738 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7739 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7740 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7742 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7743 // Lock HTLC in both directions
7744 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7745 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7747 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7748 assert_eq!(revoked_local_txn[0].input.len(), 1);
7749 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7751 // Revoke local commitment tx
7752 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7754 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7755 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7756 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7757 check_closed_broadcast!(nodes[1], false);
7758 check_added_monitors!(nodes[1], 1);
7760 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7761 assert_eq!(revoked_htlc_txn.len(), 4);
7762 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7763 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7764 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7765 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7766 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7767 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7768 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7769 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7770 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7771 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7772 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7773 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7776 // Broadcast set of revoked txn on A
7777 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.block_hash());
7778 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7780 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7781 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7786 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7787 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7788 // Verify claim tx are spending revoked HTLC txn
7789 assert_eq!(node_txn[4].input.len(), 2);
7790 assert_eq!(node_txn[4].output.len(), 1);
7791 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7792 first = node_txn[4].txid();
7793 // Store both feerates for later comparison
7794 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7795 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7796 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7800 // Connect three more block to see if bumped penalty are issued for HTLC txn
7801 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7802 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7804 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7805 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7807 check_spends!(node_txn[0], revoked_local_txn[0]);
7808 check_spends!(node_txn[1], revoked_local_txn[0]);
7813 // Few more blocks to confirm penalty txn
7814 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.block_hash());
7815 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7816 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7818 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7819 assert_eq!(node_txn.len(), 1);
7821 assert_eq!(node_txn[0].input.len(), 2);
7822 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7823 // Verify bumped tx is different and 25% bump heuristic
7824 assert_ne!(first, node_txn[0].txid());
7825 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7826 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7827 assert!(feerate_2 * 100 > feerate_1 * 125);
7828 let txn = vec![node_txn[0].clone()];
7832 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7833 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7834 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7835 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.block_hash());
7837 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7838 // We verify than no new transaction has been broadcast because previously
7839 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7840 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7841 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7842 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7843 // up bumped justice generation.
7844 assert_eq!(node_txn.len(), 0);
7847 check_closed_broadcast!(nodes[0], false);
7848 check_added_monitors!(nodes[0], 1);
7852 fn test_bump_penalty_txn_on_remote_commitment() {
7853 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7854 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7857 // Provide preimage for one
7858 // Check aggregation
7860 let chanmon_cfgs = create_chanmon_cfgs(2);
7861 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7862 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7863 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7865 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7866 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7867 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7869 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7870 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7871 assert_eq!(remote_txn[0].output.len(), 4);
7872 assert_eq!(remote_txn[0].input.len(), 1);
7873 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7875 // Claim a HTLC without revocation (provide B monitor with preimage)
7876 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7877 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7878 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7879 check_added_monitors!(nodes[1], 2);
7881 // One or more claim tx should have been broadcast, check it
7884 let feerate_timeout;
7885 let feerate_preimage;
7887 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7888 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7889 assert_eq!(node_txn[0].input.len(), 1);
7890 assert_eq!(node_txn[1].input.len(), 1);
7891 check_spends!(node_txn[0], remote_txn[0]);
7892 check_spends!(node_txn[1], remote_txn[0]);
7893 check_spends!(node_txn[2], chan.3);
7894 check_spends!(node_txn[3], node_txn[2]);
7895 check_spends!(node_txn[4], node_txn[2]);
7896 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7897 timeout = node_txn[0].txid();
7898 let index = node_txn[0].input[0].previous_output.vout;
7899 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7900 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7902 preimage = node_txn[1].txid();
7903 let index = node_txn[1].input[0].previous_output.vout;
7904 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7905 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7907 timeout = node_txn[1].txid();
7908 let index = node_txn[1].input[0].previous_output.vout;
7909 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7910 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7912 preimage = node_txn[0].txid();
7913 let index = node_txn[0].input[0].previous_output.vout;
7914 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7915 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7919 assert_ne!(feerate_timeout, 0);
7920 assert_ne!(feerate_preimage, 0);
7922 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7923 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.block_hash());
7925 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7926 assert_eq!(node_txn.len(), 2);
7927 assert_eq!(node_txn[0].input.len(), 1);
7928 assert_eq!(node_txn[1].input.len(), 1);
7929 check_spends!(node_txn[0], remote_txn[0]);
7930 check_spends!(node_txn[1], remote_txn[0]);
7931 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7932 let index = node_txn[0].input[0].previous_output.vout;
7933 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7934 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7935 assert!(new_feerate * 100 > feerate_timeout * 125);
7936 assert_ne!(timeout, node_txn[0].txid());
7938 let index = node_txn[1].input[0].previous_output.vout;
7939 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7940 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7941 assert!(new_feerate * 100 > feerate_preimage * 125);
7942 assert_ne!(preimage, node_txn[1].txid());
7944 let index = node_txn[1].input[0].previous_output.vout;
7945 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7946 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7947 assert!(new_feerate * 100 > feerate_timeout * 125);
7948 assert_ne!(timeout, node_txn[1].txid());
7950 let index = node_txn[0].input[0].previous_output.vout;
7951 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7952 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7953 assert!(new_feerate * 100 > feerate_preimage * 125);
7954 assert_ne!(preimage, node_txn[0].txid());
7959 nodes[1].node.get_and_clear_pending_events();
7960 nodes[1].node.get_and_clear_pending_msg_events();
7964 fn test_set_outpoints_partial_claiming() {
7965 // - remote party claim tx, new bump tx
7966 // - disconnect remote claiming tx, new bump
7967 // - disconnect tx, see no tx anymore
7968 let chanmon_cfgs = create_chanmon_cfgs(2);
7969 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7970 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7971 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7973 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7974 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7975 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7977 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7978 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7979 assert_eq!(remote_txn.len(), 3);
7980 assert_eq!(remote_txn[0].output.len(), 4);
7981 assert_eq!(remote_txn[0].input.len(), 1);
7982 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7983 check_spends!(remote_txn[1], remote_txn[0]);
7984 check_spends!(remote_txn[2], remote_txn[0]);
7986 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7987 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7988 // Provide node A with both preimage
7989 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7990 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7991 check_added_monitors!(nodes[0], 2);
7992 nodes[0].node.get_and_clear_pending_events();
7993 nodes[0].node.get_and_clear_pending_msg_events();
7995 // Connect blocks on node A commitment transaction
7996 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7997 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7998 check_closed_broadcast!(nodes[0], false);
7999 check_added_monitors!(nodes[0], 1);
8000 // Verify node A broadcast tx claiming both HTLCs
8002 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8003 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8004 assert_eq!(node_txn.len(), 4);
8005 check_spends!(node_txn[0], remote_txn[0]);
8006 check_spends!(node_txn[1], chan.3);
8007 check_spends!(node_txn[2], node_txn[1]);
8008 check_spends!(node_txn[3], node_txn[1]);
8009 assert_eq!(node_txn[0].input.len(), 2);
8013 // Connect blocks on node B
8014 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
8015 check_closed_broadcast!(nodes[1], false);
8016 check_added_monitors!(nodes[1], 1);
8017 // Verify node B broadcast 2 HTLC-timeout txn
8018 let partial_claim_tx = {
8019 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8020 assert_eq!(node_txn.len(), 3);
8021 check_spends!(node_txn[1], node_txn[0]);
8022 check_spends!(node_txn[2], node_txn[0]);
8023 assert_eq!(node_txn[1].input.len(), 1);
8024 assert_eq!(node_txn[2].input.len(), 1);
8028 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8029 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8030 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8032 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8033 assert_eq!(node_txn.len(), 1);
8034 check_spends!(node_txn[0], remote_txn[0]);
8035 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8038 nodes[0].node.get_and_clear_pending_msg_events();
8040 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8041 nodes[0].block_notifier.block_disconnected(&header, 102);
8043 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8044 assert_eq!(node_txn.len(), 1);
8045 check_spends!(node_txn[0], remote_txn[0]);
8046 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8050 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8051 nodes[0].block_notifier.block_disconnected(&header, 101);
8052 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
8054 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8055 assert_eq!(node_txn.len(), 0);
8061 fn test_counterparty_raa_skip_no_crash() {
8062 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8063 // commitment transaction, we would have happily carried on and provided them the next
8064 // commitment transaction based on one RAA forward. This would probably eventually have led to
8065 // channel closure, but it would not have resulted in funds loss. Still, our
8066 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8067 // check simply that the channel is closed in response to such an RAA, but don't check whether
8068 // we decide to punish our counterparty for revoking their funds (as we don't currently
8070 let chanmon_cfgs = create_chanmon_cfgs(2);
8071 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8072 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8073 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8074 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8076 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8077 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8078 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8079 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8080 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8081 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8083 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8084 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8085 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8086 check_added_monitors!(nodes[1], 1);
8090 fn test_bump_txn_sanitize_tracking_maps() {
8091 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8092 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8094 let chanmon_cfgs = create_chanmon_cfgs(2);
8095 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8096 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8097 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8099 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8100 // Lock HTLC in both directions
8101 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8102 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8104 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8105 assert_eq!(revoked_local_txn[0].input.len(), 1);
8106 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8108 // Revoke local commitment tx
8109 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8111 // Broadcast set of revoked txn on A
8112 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
8113 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8115 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8116 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8117 check_closed_broadcast!(nodes[0], false);
8118 check_added_monitors!(nodes[0], 1);
8120 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8121 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8122 check_spends!(node_txn[0], revoked_local_txn[0]);
8123 check_spends!(node_txn[1], revoked_local_txn[0]);
8124 check_spends!(node_txn[2], revoked_local_txn[0]);
8125 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8129 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8130 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
8131 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.block_hash());
8133 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8134 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8135 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8136 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8142 fn test_override_channel_config() {
8143 let chanmon_cfgs = create_chanmon_cfgs(2);
8144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8146 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8148 // Node0 initiates a channel to node1 using the override config.
8149 let mut override_config = UserConfig::default();
8150 override_config.own_channel_config.our_to_self_delay = 200;
8152 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8154 // Assert the channel created by node0 is using the override config.
8155 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8156 assert_eq!(res.channel_flags, 0);
8157 assert_eq!(res.to_self_delay, 200);
8161 fn test_override_0msat_htlc_minimum() {
8162 let mut zero_config = UserConfig::default();
8163 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8164 let chanmon_cfgs = create_chanmon_cfgs(2);
8165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8169 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8170 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8171 assert_eq!(res.htlc_minimum_msat, 1);
8173 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8174 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8175 assert_eq!(res.htlc_minimum_msat, 1);
8179 fn test_simple_payment_secret() {
8180 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8181 // features, however.
8182 let chanmon_cfgs = create_chanmon_cfgs(3);
8183 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8184 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8185 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8187 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8188 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8189 let logger = test_utils::TestLogger::new();
8191 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8192 let payment_secret = PaymentSecret([0xdb; 32]);
8193 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8194 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();
8195 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8196 // Claiming with all the correct values but the wrong secret should result in nothing...
8197 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8198 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8199 // ...but with the right secret we should be able to claim all the way back
8200 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8204 fn test_simple_mpp() {
8205 // Simple test of sending a multi-path payment.
8206 let chanmon_cfgs = create_chanmon_cfgs(4);
8207 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8208 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8209 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8211 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8212 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8213 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8214 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8215 let logger = test_utils::TestLogger::new();
8217 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8218 let payment_secret = PaymentSecret([0xdb; 32]);
8219 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8220 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();
8221 let path = route.paths[0].clone();
8222 route.paths.push(path);
8223 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8224 route.paths[0][0].short_channel_id = chan_1_id;
8225 route.paths[0][1].short_channel_id = chan_3_id;
8226 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8227 route.paths[1][0].short_channel_id = chan_2_id;
8228 route.paths[1][1].short_channel_id = chan_4_id;
8229 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8230 // Claiming with all the correct values but the wrong secret should result in nothing...
8231 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8232 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8233 // ...but with the right secret we should be able to claim all the way back
8234 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8238 fn test_update_err_monitor_lockdown() {
8239 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8240 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8241 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8243 // This scenario may happen in a watchtower setup, where watchtower process a block height
8244 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8245 // commitment at same time.
8247 let chanmon_cfgs = create_chanmon_cfgs(2);
8248 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8249 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8250 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8252 // Create some initial channel
8253 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8254 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8256 // Rebalance the network to generate htlc in the two directions
8257 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8259 // Route a HTLC from node 0 to node 1 (but don't settle)
8260 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8262 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8263 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8264 let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8266 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8267 let monitor = monitors.get(&outpoint).unwrap();
8268 let mut w = test_utils::TestVecWriter(Vec::new());
8269 monitor.write_for_disk(&mut w).unwrap();
8270 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8271 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8272 assert!(new_monitor == *monitor);
8273 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8274 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8277 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8278 watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
8280 // Try to update ChannelMonitor
8281 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8282 check_added_monitors!(nodes[1], 1);
8283 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8284 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8285 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8286 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8287 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8288 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8289 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8290 } else { assert!(false); }
8291 } else { assert!(false); };
8292 // Our local monitor is in-sync and hasn't processed yet timeout
8293 check_added_monitors!(nodes[0], 1);
8294 let events = nodes[0].node.get_and_clear_pending_events();
8295 assert_eq!(events.len(), 1);
8299 fn test_concurrent_monitor_claim() {
8300 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8301 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8302 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8303 // state N+1 confirms. Alice claims output from state N+1.
8305 let chanmon_cfgs = create_chanmon_cfgs(2);
8306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8308 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8310 // Create some initial channel
8311 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8312 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8314 // Rebalance the network to generate htlc in the two directions
8315 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8317 // Route a HTLC from node 0 to node 1 (but don't settle)
8318 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8320 // Copy SimpleManyChannelMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8321 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8322 let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8323 let watchtower_alice = {
8324 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8325 let monitor = monitors.get(&outpoint).unwrap();
8326 let mut w = test_utils::TestVecWriter(Vec::new());
8327 monitor.write_for_disk(&mut w).unwrap();
8328 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8329 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8330 assert!(new_monitor == *monitor);
8331 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8332 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8335 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8336 watchtower_alice.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8338 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8340 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8341 assert_eq!(txn.len(), 2);
8345 // Copy SimpleManyChannelMonitor to simulate watchtower Bob and make it receive a commitment update first.
8346 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8347 let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8348 let watchtower_bob = {
8349 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8350 let monitor = monitors.get(&outpoint).unwrap();
8351 let mut w = test_utils::TestVecWriter(Vec::new());
8352 monitor.write_for_disk(&mut w).unwrap();
8353 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8354 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8355 assert!(new_monitor == *monitor);
8356 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8357 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8360 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8361 watchtower_bob.simple_monitor.block_connected(&header, 134, &vec![], &vec![]);
8363 // Route another payment to generate another update with still previous HTLC pending
8364 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8366 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8367 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();
8368 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8370 check_added_monitors!(nodes[1], 1);
8372 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8373 assert_eq!(updates.update_add_htlcs.len(), 1);
8374 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8375 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8376 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8377 // Watchtower Alice should already have seen the block and reject the update
8378 if let Err(_) = watchtower_alice.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8379 if let Ok(_) = watchtower_bob.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8380 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8381 } else { assert!(false); }
8382 } else { assert!(false); };
8383 // Our local monitor is in-sync and hasn't processed yet timeout
8384 check_added_monitors!(nodes[0], 1);
8386 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8387 watchtower_bob.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8389 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8392 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8393 assert_eq!(txn.len(), 2);
8394 bob_state_y = txn[0].clone();
8398 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8399 watchtower_alice.simple_monitor.block_connected(&header, 136, &vec![&bob_state_y][..], &vec![]);
8401 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8402 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8403 // the onchain detection of the HTLC output
8404 assert_eq!(htlc_txn.len(), 2);
8405 check_spends!(htlc_txn[0], bob_state_y);
8406 check_spends!(htlc_txn[1], bob_state_y);