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(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
5041 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5042 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5043 // transactions next...
5044 assert_eq!(node_txn[0].input.len(), 2);
5045 check_spends!(node_txn[0], revoked_local_txn[0]);
5047 check_spends!(node_txn[1], chan_1.3);
5049 assert_eq!(node_txn[2].input.len(), 1);
5050 check_spends!(node_txn[2], revoked_htlc_txn[0]);
5051 assert_eq!(node_txn[3].input.len(), 1);
5052 check_spends!(node_txn[3], revoked_local_txn[0]);
5054 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5055 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[2].clone(), node_txn[3].clone()] }, 1);
5056 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5058 // Note that nodes[1]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5059 // didn't try to generate any new transactions.
5061 // Check B's ChannelMonitor was able to generate the right spendable output descriptor which
5062 // allows the user to spend the newly-confirmed outputs.
5063 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5064 assert_eq!(spend_txn.len(), 2);
5065 check_spends!(spend_txn[0], node_txn[2]);
5066 check_spends!(spend_txn[1], node_txn[3]);
5070 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5071 let chanmon_cfgs = create_chanmon_cfgs(2);
5072 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5073 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5074 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5076 // Create some initial channels
5077 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5079 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5080 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5081 assert_eq!(revoked_local_txn[0].input.len(), 1);
5082 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5084 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5086 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5087 // B will generate HTLC-Success from revoked commitment tx
5088 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5089 check_closed_broadcast!(nodes[1], false);
5090 check_added_monitors!(nodes[1], 1);
5091 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5093 assert_eq!(revoked_htlc_txn.len(), 2);
5094 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5095 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5096 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5098 // A will generate justice tx from B's revoked commitment/HTLC tx
5099 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5100 check_closed_broadcast!(nodes[0], false);
5101 check_added_monitors!(nodes[0], 1);
5103 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5104 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5105 assert_eq!(node_txn[2].input.len(), 1);
5106 check_spends!(node_txn[2], revoked_htlc_txn[0]);
5108 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5109 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
5110 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5112 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5113 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5114 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
5115 assert_eq!(spend_txn[0], spend_txn[1]);
5116 assert_eq!(spend_txn[0], spend_txn[2]);
5117 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5118 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
5119 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
5123 fn test_onchain_to_onchain_claim() {
5124 // Test that in case of channel closure, we detect the state of output thanks to
5125 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
5126 // First, have C claim an HTLC against its own latest commitment transaction.
5127 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5129 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5132 let chanmon_cfgs = create_chanmon_cfgs(3);
5133 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5134 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5135 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5137 // Create some initial channels
5138 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5139 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5141 // Rebalance the network a bit by relaying one payment through all the channels ...
5142 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5143 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5145 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5146 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5147 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5148 check_spends!(commitment_tx[0], chan_2.3);
5149 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5150 check_added_monitors!(nodes[2], 1);
5151 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5152 assert!(updates.update_add_htlcs.is_empty());
5153 assert!(updates.update_fail_htlcs.is_empty());
5154 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5155 assert!(updates.update_fail_malformed_htlcs.is_empty());
5157 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5158 check_closed_broadcast!(nodes[2], false);
5159 check_added_monitors!(nodes[2], 1);
5161 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5162 assert_eq!(c_txn.len(), 3);
5163 assert_eq!(c_txn[0], c_txn[2]);
5164 assert_eq!(commitment_tx[0], c_txn[1]);
5165 check_spends!(c_txn[1], chan_2.3);
5166 check_spends!(c_txn[2], c_txn[1]);
5167 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5168 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5169 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5170 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5172 // 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
5173 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5175 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5176 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5177 assert_eq!(b_txn.len(), 3);
5178 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5179 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5180 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5181 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5182 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5183 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
5184 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5185 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5186 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5189 check_added_monitors!(nodes[1], 1);
5190 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5191 check_added_monitors!(nodes[1], 1);
5192 match msg_events[0] {
5193 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5194 _ => panic!("Unexpected event"),
5196 match msg_events[1] {
5197 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, .. } } => {
5198 assert!(update_add_htlcs.is_empty());
5199 assert!(update_fail_htlcs.is_empty());
5200 assert_eq!(update_fulfill_htlcs.len(), 1);
5201 assert!(update_fail_malformed_htlcs.is_empty());
5202 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5204 _ => panic!("Unexpected event"),
5206 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5207 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5208 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5209 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5210 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5211 assert_eq!(b_txn.len(), 3);
5212 check_spends!(b_txn[1], chan_1.3);
5213 check_spends!(b_txn[2], b_txn[1]);
5214 check_spends!(b_txn[0], commitment_tx[0]);
5215 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5216 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5217 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5219 check_closed_broadcast!(nodes[1], false);
5220 check_added_monitors!(nodes[1], 1);
5224 fn test_duplicate_payment_hash_one_failure_one_success() {
5225 // Topology : A --> B --> C
5226 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5227 let chanmon_cfgs = create_chanmon_cfgs(3);
5228 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5229 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5230 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5232 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5233 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5235 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5236 *nodes[0].network_payment_count.borrow_mut() -= 1;
5237 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5239 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5240 assert_eq!(commitment_txn[0].input.len(), 1);
5241 check_spends!(commitment_txn[0], chan_2.3);
5243 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5244 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5245 check_closed_broadcast!(nodes[1], false);
5246 check_added_monitors!(nodes[1], 1);
5248 let htlc_timeout_tx;
5249 { // Extract one of the two HTLC-Timeout transaction
5250 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5251 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5252 assert_eq!(node_txn.len(), 5);
5253 check_spends!(node_txn[0], commitment_txn[0]);
5254 assert_eq!(node_txn[0].input.len(), 1);
5255 check_spends!(node_txn[1], commitment_txn[0]);
5256 assert_eq!(node_txn[1].input.len(), 1);
5257 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5258 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5259 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5260 check_spends!(node_txn[2], chan_2.3);
5261 check_spends!(node_txn[3], node_txn[2]);
5262 check_spends!(node_txn[4], node_txn[2]);
5263 htlc_timeout_tx = node_txn[1].clone();
5266 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5267 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5268 check_added_monitors!(nodes[2], 3);
5269 let events = nodes[2].node.get_and_clear_pending_msg_events();
5271 MessageSendEvent::UpdateHTLCs { .. } => {},
5272 _ => panic!("Unexpected event"),
5275 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5276 _ => panic!("Unexepected event"),
5278 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5279 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)
5280 check_spends!(htlc_success_txn[2], chan_2.3);
5281 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5282 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5283 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5284 assert_eq!(htlc_success_txn[0].input.len(), 1);
5285 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5286 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5287 assert_eq!(htlc_success_txn[1].input.len(), 1);
5288 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5289 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5290 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5291 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5293 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5294 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5295 expect_pending_htlcs_forwardable!(nodes[1]);
5296 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5297 assert!(htlc_updates.update_add_htlcs.is_empty());
5298 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5299 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5300 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5301 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5302 check_added_monitors!(nodes[1], 1);
5304 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5305 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5307 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5308 let events = nodes[0].node.get_and_clear_pending_msg_events();
5309 assert_eq!(events.len(), 1);
5311 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5313 _ => { panic!("Unexpected event"); }
5316 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5318 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5319 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5320 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5321 assert!(updates.update_add_htlcs.is_empty());
5322 assert!(updates.update_fail_htlcs.is_empty());
5323 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5324 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5325 assert!(updates.update_fail_malformed_htlcs.is_empty());
5326 check_added_monitors!(nodes[1], 1);
5328 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5329 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5331 let events = nodes[0].node.get_and_clear_pending_events();
5333 Event::PaymentSent { ref payment_preimage } => {
5334 assert_eq!(*payment_preimage, our_payment_preimage);
5336 _ => panic!("Unexpected event"),
5341 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5342 let chanmon_cfgs = create_chanmon_cfgs(2);
5343 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5344 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5345 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5347 // Create some initial channels
5348 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5350 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5351 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5352 assert_eq!(local_txn[0].input.len(), 1);
5353 check_spends!(local_txn[0], chan_1.3);
5355 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5356 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5357 check_added_monitors!(nodes[1], 1);
5358 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5359 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5360 check_added_monitors!(nodes[1], 1);
5361 let events = nodes[1].node.get_and_clear_pending_msg_events();
5363 MessageSendEvent::UpdateHTLCs { .. } => {},
5364 _ => panic!("Unexpected event"),
5367 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5368 _ => panic!("Unexepected event"),
5371 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5372 assert_eq!(node_txn[0].input.len(), 1);
5373 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5374 check_spends!(node_txn[0], local_txn[0]);
5375 vec![node_txn[0].clone(), node_txn[2].clone()]
5378 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5379 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
5380 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5382 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5383 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5384 assert_eq!(spend_txn.len(), 2);
5385 check_spends!(spend_txn[0], node_txn[0]);
5386 check_spends!(spend_txn[1], node_txn[1]);
5389 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5390 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5391 // unrevoked commitment transaction.
5392 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5393 // a remote RAA before they could be failed backwards (and combinations thereof).
5394 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5395 // use the same payment hashes.
5396 // Thus, we use a six-node network:
5401 // And test where C fails back to A/B when D announces its latest commitment transaction
5402 let chanmon_cfgs = create_chanmon_cfgs(6);
5403 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5404 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5405 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5406 let logger = test_utils::TestLogger::new();
5408 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5409 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5410 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5411 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5412 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5414 // Rebalance and check output sanity...
5415 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5416 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5417 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5419 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5421 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
5423 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
5424 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5425 let our_node_id = &nodes[1].node.get_our_node_id();
5426 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();
5428 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
5430 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
5432 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5434 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5435 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();
5437 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5439 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5442 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5444 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();
5445 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
5448 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
5450 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();
5451 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5453 // Double-check that six of the new HTLC were added
5454 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5455 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5456 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5457 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5459 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5460 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5461 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5462 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5463 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5464 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5465 check_added_monitors!(nodes[4], 0);
5466 expect_pending_htlcs_forwardable!(nodes[4]);
5467 check_added_monitors!(nodes[4], 1);
5469 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5470 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5471 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5472 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5473 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5474 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5476 // Fail 3rd below-dust and 7th above-dust HTLCs
5477 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5478 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5479 check_added_monitors!(nodes[5], 0);
5480 expect_pending_htlcs_forwardable!(nodes[5]);
5481 check_added_monitors!(nodes[5], 1);
5483 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5484 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5485 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5486 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5488 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5490 expect_pending_htlcs_forwardable!(nodes[3]);
5491 check_added_monitors!(nodes[3], 1);
5492 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5493 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5494 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5495 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5496 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5497 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5498 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5499 if deliver_last_raa {
5500 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5502 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5505 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5506 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5507 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5508 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5510 // We now broadcast the latest commitment transaction, which *should* result in failures for
5511 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5512 // the non-broadcast above-dust HTLCs.
5514 // Alternatively, we may broadcast the previous commitment transaction, which should only
5515 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5516 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5518 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5519 if announce_latest {
5520 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5522 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5524 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5525 check_closed_broadcast!(nodes[2], false);
5526 expect_pending_htlcs_forwardable!(nodes[2]);
5527 check_added_monitors!(nodes[2], 3);
5529 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5530 assert_eq!(cs_msgs.len(), 2);
5531 let mut a_done = false;
5532 for msg in cs_msgs {
5534 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5535 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5536 // should be failed-backwards here.
5537 let target = if *node_id == nodes[0].node.get_our_node_id() {
5538 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5539 for htlc in &updates.update_fail_htlcs {
5540 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 });
5542 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5547 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5548 for htlc in &updates.update_fail_htlcs {
5549 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5551 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5552 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5555 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5556 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5557 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5558 if announce_latest {
5559 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5560 if *node_id == nodes[0].node.get_our_node_id() {
5561 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5564 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5566 _ => panic!("Unexpected event"),
5570 let as_events = nodes[0].node.get_and_clear_pending_events();
5571 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5572 let mut as_failds = HashSet::new();
5573 for event in as_events.iter() {
5574 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5575 assert!(as_failds.insert(*payment_hash));
5576 if *payment_hash != payment_hash_2 {
5577 assert_eq!(*rejected_by_dest, deliver_last_raa);
5579 assert!(!rejected_by_dest);
5581 } else { panic!("Unexpected event"); }
5583 assert!(as_failds.contains(&payment_hash_1));
5584 assert!(as_failds.contains(&payment_hash_2));
5585 if announce_latest {
5586 assert!(as_failds.contains(&payment_hash_3));
5587 assert!(as_failds.contains(&payment_hash_5));
5589 assert!(as_failds.contains(&payment_hash_6));
5591 let bs_events = nodes[1].node.get_and_clear_pending_events();
5592 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5593 let mut bs_failds = HashSet::new();
5594 for event in bs_events.iter() {
5595 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5596 assert!(bs_failds.insert(*payment_hash));
5597 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5598 assert_eq!(*rejected_by_dest, deliver_last_raa);
5600 assert!(!rejected_by_dest);
5602 } else { panic!("Unexpected event"); }
5604 assert!(bs_failds.contains(&payment_hash_1));
5605 assert!(bs_failds.contains(&payment_hash_2));
5606 if announce_latest {
5607 assert!(bs_failds.contains(&payment_hash_4));
5609 assert!(bs_failds.contains(&payment_hash_5));
5611 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5612 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5613 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5614 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5615 // PaymentFailureNetworkUpdates.
5616 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5617 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5618 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5619 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5620 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5622 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5623 _ => panic!("Unexpected event"),
5629 fn test_fail_backwards_latest_remote_announce_a() {
5630 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5634 fn test_fail_backwards_latest_remote_announce_b() {
5635 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5639 fn test_fail_backwards_previous_remote_announce() {
5640 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5641 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5642 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5646 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5647 let chanmon_cfgs = create_chanmon_cfgs(2);
5648 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5649 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5650 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5652 // Create some initial channels
5653 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5655 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5656 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5657 assert_eq!(local_txn[0].input.len(), 1);
5658 check_spends!(local_txn[0], chan_1.3);
5660 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5661 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5662 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5663 check_closed_broadcast!(nodes[0], false);
5664 check_added_monitors!(nodes[0], 1);
5666 let htlc_timeout = {
5667 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5668 assert_eq!(node_txn[0].input.len(), 1);
5669 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5670 check_spends!(node_txn[0], local_txn[0]);
5674 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5675 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5676 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5677 expect_payment_failed!(nodes[0], our_payment_hash, true);
5679 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5680 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5681 assert_eq!(spend_txn.len(), 3);
5682 assert_eq!(spend_txn[0], spend_txn[1]);
5683 check_spends!(spend_txn[0], local_txn[0]);
5684 check_spends!(spend_txn[2], htlc_timeout);
5688 fn test_key_derivation_params() {
5689 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5690 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5691 // let us re-derive the channel key set to then derive a delayed_payment_key.
5693 let chanmon_cfgs = create_chanmon_cfgs(3);
5695 // We manually create the node configuration to backup the seed.
5696 let seed = [42; 32];
5697 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5698 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);
5699 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 };
5700 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5701 node_cfgs.remove(0);
5702 node_cfgs.insert(0, node);
5704 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5705 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5707 // Create some initial channels
5708 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5710 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5711 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5712 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5714 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5715 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5716 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5717 assert_eq!(local_txn_1[0].input.len(), 1);
5718 check_spends!(local_txn_1[0], chan_1.3);
5720 // We check funding pubkey are unique
5721 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]));
5722 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]));
5723 if from_0_funding_key_0 == from_1_funding_key_0
5724 || from_0_funding_key_0 == from_1_funding_key_1
5725 || from_0_funding_key_1 == from_1_funding_key_0
5726 || from_0_funding_key_1 == from_1_funding_key_1 {
5727 panic!("Funding pubkeys aren't unique");
5730 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5731 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5732 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5733 check_closed_broadcast!(nodes[0], false);
5734 check_added_monitors!(nodes[0], 1);
5736 let htlc_timeout = {
5737 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5738 assert_eq!(node_txn[0].input.len(), 1);
5739 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5740 check_spends!(node_txn[0], local_txn_1[0]);
5744 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5745 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5746 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5747 expect_payment_failed!(nodes[0], our_payment_hash, true);
5749 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5750 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5751 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5752 assert_eq!(spend_txn.len(), 3);
5753 assert_eq!(spend_txn[0], spend_txn[1]);
5754 check_spends!(spend_txn[0], local_txn_1[0]);
5755 check_spends!(spend_txn[2], htlc_timeout);
5759 fn test_static_output_closing_tx() {
5760 let chanmon_cfgs = create_chanmon_cfgs(2);
5761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5763 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5765 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5767 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5768 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5770 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5771 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5772 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5774 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5775 assert_eq!(spend_txn.len(), 1);
5776 check_spends!(spend_txn[0], closing_tx);
5778 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5779 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5781 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5782 assert_eq!(spend_txn.len(), 1);
5783 check_spends!(spend_txn[0], closing_tx);
5786 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5787 let chanmon_cfgs = create_chanmon_cfgs(2);
5788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5791 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5793 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5795 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5796 // present in B's local commitment transaction, but none of A's commitment transactions.
5797 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5798 check_added_monitors!(nodes[1], 1);
5800 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5801 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5802 let events = nodes[0].node.get_and_clear_pending_events();
5803 assert_eq!(events.len(), 1);
5805 Event::PaymentSent { payment_preimage } => {
5806 assert_eq!(payment_preimage, our_payment_preimage);
5808 _ => panic!("Unexpected event"),
5811 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5812 check_added_monitors!(nodes[0], 1);
5813 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5814 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5815 check_added_monitors!(nodes[1], 1);
5817 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5818 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5819 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5820 header.prev_blockhash = header.block_hash();
5822 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5823 check_closed_broadcast!(nodes[1], false);
5824 check_added_monitors!(nodes[1], 1);
5827 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5828 let chanmon_cfgs = create_chanmon_cfgs(2);
5829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5830 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5831 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5832 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5833 let logger = test_utils::TestLogger::new();
5835 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5836 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5837 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();
5838 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5839 check_added_monitors!(nodes[0], 1);
5841 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5843 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5844 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5845 // to "time out" the HTLC.
5847 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5849 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5850 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5851 header.prev_blockhash = header.block_hash();
5853 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5854 check_closed_broadcast!(nodes[0], false);
5855 check_added_monitors!(nodes[0], 1);
5858 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5859 let chanmon_cfgs = create_chanmon_cfgs(3);
5860 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5861 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5862 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5863 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5865 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5866 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5867 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5868 // actually revoked.
5869 let htlc_value = if use_dust { 50000 } else { 3000000 };
5870 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5871 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5872 expect_pending_htlcs_forwardable!(nodes[1]);
5873 check_added_monitors!(nodes[1], 1);
5875 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5876 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5877 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5878 check_added_monitors!(nodes[0], 1);
5879 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5880 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5881 check_added_monitors!(nodes[1], 1);
5882 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5883 check_added_monitors!(nodes[1], 1);
5884 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5886 if check_revoke_no_close {
5887 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5888 check_added_monitors!(nodes[0], 1);
5891 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5892 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5893 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5894 header.prev_blockhash = header.block_hash();
5896 if !check_revoke_no_close {
5897 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5898 check_closed_broadcast!(nodes[0], false);
5899 check_added_monitors!(nodes[0], 1);
5901 expect_payment_failed!(nodes[0], our_payment_hash, true);
5905 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5906 // There are only a few cases to test here:
5907 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5908 // broadcastable commitment transactions result in channel closure,
5909 // * its included in an unrevoked-but-previous remote commitment transaction,
5910 // * its included in the latest remote or local commitment transactions.
5911 // We test each of the three possible commitment transactions individually and use both dust and
5913 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5914 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5915 // tested for at least one of the cases in other tests.
5917 fn htlc_claim_single_commitment_only_a() {
5918 do_htlc_claim_local_commitment_only(true);
5919 do_htlc_claim_local_commitment_only(false);
5921 do_htlc_claim_current_remote_commitment_only(true);
5922 do_htlc_claim_current_remote_commitment_only(false);
5926 fn htlc_claim_single_commitment_only_b() {
5927 do_htlc_claim_previous_remote_commitment_only(true, false);
5928 do_htlc_claim_previous_remote_commitment_only(false, false);
5929 do_htlc_claim_previous_remote_commitment_only(true, true);
5930 do_htlc_claim_previous_remote_commitment_only(false, true);
5935 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5936 let chanmon_cfgs = create_chanmon_cfgs(2);
5937 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5938 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5939 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5940 //Force duplicate channel ids
5941 for node in nodes.iter() {
5942 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5945 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5946 let channel_value_satoshis=10000;
5947 let push_msat=10001;
5948 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5949 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5950 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5952 //Create a second channel with a channel_id collision
5953 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5957 fn bolt2_open_channel_sending_node_checks_part2() {
5958 let chanmon_cfgs = create_chanmon_cfgs(2);
5959 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5960 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5961 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5963 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5964 let channel_value_satoshis=2^24;
5965 let push_msat=10001;
5966 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5968 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5969 let channel_value_satoshis=10000;
5970 // Test when push_msat is equal to 1000 * funding_satoshis.
5971 let push_msat=1000*channel_value_satoshis+1;
5972 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5974 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5975 let channel_value_satoshis=10000;
5976 let push_msat=10001;
5977 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
5978 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5979 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5981 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5982 // 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
5983 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5985 // 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.
5986 assert!(BREAKDOWN_TIMEOUT>0);
5987 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5989 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5990 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
5991 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5993 // 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.
5994 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5995 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5996 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5997 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5998 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6001 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6002 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6003 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6004 // is no longer affordable once it's freed.
6006 fn test_fail_holding_cell_htlc_upon_free() {
6007 let chanmon_cfgs = create_chanmon_cfgs(2);
6008 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6009 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6010 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6011 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6012 let logger = test_utils::TestLogger::new();
6014 // First nodes[0] generates an update_fee, setting the channel's
6015 // pending_update_fee.
6016 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6017 check_added_monitors!(nodes[0], 1);
6019 let events = nodes[0].node.get_and_clear_pending_msg_events();
6020 assert_eq!(events.len(), 1);
6021 let (update_msg, commitment_signed) = match events[0] {
6022 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6023 (update_fee.as_ref(), commitment_signed)
6025 _ => panic!("Unexpected event"),
6028 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6030 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6031 let channel_reserve = chan_stat.channel_reserve_msat;
6032 let feerate = get_feerate!(nodes[0], chan.2);
6034 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6035 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6036 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6037 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6038 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();
6040 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6041 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6042 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6043 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6045 // Flush the pending fee update.
6046 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6047 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6048 check_added_monitors!(nodes[1], 1);
6049 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6050 check_added_monitors!(nodes[0], 1);
6052 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6053 // HTLC, but now that the fee has been raised the payment will now fail, causing
6054 // us to surface its failure to the user.
6055 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6056 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6057 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6058 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);
6059 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6061 // Check that the payment failed to be sent out.
6062 let events = nodes[0].node.get_and_clear_pending_events();
6063 assert_eq!(events.len(), 1);
6065 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6066 assert_eq!(our_payment_hash.clone(), *payment_hash);
6067 assert_eq!(*rejected_by_dest, false);
6068 assert_eq!(*error_code, None);
6069 assert_eq!(*error_data, None);
6071 _ => panic!("Unexpected event"),
6075 // Test that if multiple HTLCs are released from the holding cell and one is
6076 // valid but the other is no longer valid upon release, the valid HTLC can be
6077 // successfully completed while the other one fails as expected.
6079 fn test_free_and_fail_holding_cell_htlcs() {
6080 let chanmon_cfgs = create_chanmon_cfgs(2);
6081 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6082 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6083 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6084 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6085 let logger = test_utils::TestLogger::new();
6087 // First nodes[0] generates an update_fee, setting the channel's
6088 // pending_update_fee.
6089 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6090 check_added_monitors!(nodes[0], 1);
6092 let events = nodes[0].node.get_and_clear_pending_msg_events();
6093 assert_eq!(events.len(), 1);
6094 let (update_msg, commitment_signed) = match events[0] {
6095 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6096 (update_fee.as_ref(), commitment_signed)
6098 _ => panic!("Unexpected event"),
6101 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6103 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6104 let channel_reserve = chan_stat.channel_reserve_msat;
6105 let feerate = get_feerate!(nodes[0], chan.2);
6107 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6108 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6110 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6111 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6112 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6113 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();
6114 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();
6116 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6117 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6118 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6119 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6120 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6121 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6122 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6124 // Flush the pending fee update.
6125 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6126 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6127 check_added_monitors!(nodes[1], 1);
6128 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6129 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6130 check_added_monitors!(nodes[0], 2);
6132 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6133 // but now that the fee has been raised the second payment will now fail, causing us
6134 // to surface its failure to the user. The first payment should succeed.
6135 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6136 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6137 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6138 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);
6139 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6141 // Check that the second payment failed to be sent out.
6142 let events = nodes[0].node.get_and_clear_pending_events();
6143 assert_eq!(events.len(), 1);
6145 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6146 assert_eq!(payment_hash_2.clone(), *payment_hash);
6147 assert_eq!(*rejected_by_dest, false);
6148 assert_eq!(*error_code, None);
6149 assert_eq!(*error_data, None);
6151 _ => panic!("Unexpected event"),
6154 // Complete the first payment and the RAA from the fee update.
6155 let (payment_event, send_raa_event) = {
6156 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6157 assert_eq!(msgs.len(), 2);
6158 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6160 let raa = match send_raa_event {
6161 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6162 _ => panic!("Unexpected event"),
6164 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6165 check_added_monitors!(nodes[1], 1);
6166 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6167 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6168 let events = nodes[1].node.get_and_clear_pending_events();
6169 assert_eq!(events.len(), 1);
6171 Event::PendingHTLCsForwardable { .. } => {},
6172 _ => panic!("Unexpected event"),
6174 nodes[1].node.process_pending_htlc_forwards();
6175 let events = nodes[1].node.get_and_clear_pending_events();
6176 assert_eq!(events.len(), 1);
6178 Event::PaymentReceived { .. } => {},
6179 _ => panic!("Unexpected event"),
6181 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6182 check_added_monitors!(nodes[1], 1);
6183 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6184 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6185 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6186 let events = nodes[0].node.get_and_clear_pending_events();
6187 assert_eq!(events.len(), 1);
6189 Event::PaymentSent { ref payment_preimage } => {
6190 assert_eq!(*payment_preimage, payment_preimage_1);
6192 _ => panic!("Unexpected event"),
6196 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6197 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6198 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6201 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6202 let chanmon_cfgs = create_chanmon_cfgs(3);
6203 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6204 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6205 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6206 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6207 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6208 let logger = test_utils::TestLogger::new();
6210 // First nodes[1] generates an update_fee, setting the channel's
6211 // pending_update_fee.
6212 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6213 check_added_monitors!(nodes[1], 1);
6215 let events = nodes[1].node.get_and_clear_pending_msg_events();
6216 assert_eq!(events.len(), 1);
6217 let (update_msg, commitment_signed) = match events[0] {
6218 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6219 (update_fee.as_ref(), commitment_signed)
6221 _ => panic!("Unexpected event"),
6224 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6226 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6227 let channel_reserve = chan_stat.channel_reserve_msat;
6228 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6230 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6232 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6233 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6234 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6235 let payment_event = {
6236 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6237 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();
6238 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6239 check_added_monitors!(nodes[0], 1);
6241 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6242 assert_eq!(events.len(), 1);
6244 SendEvent::from_event(events.remove(0))
6246 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6247 check_added_monitors!(nodes[1], 0);
6248 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6249 expect_pending_htlcs_forwardable!(nodes[1]);
6251 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6252 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6254 // Flush the pending fee update.
6255 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6256 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6257 check_added_monitors!(nodes[2], 1);
6258 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6259 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6260 check_added_monitors!(nodes[1], 2);
6262 // A final RAA message is generated to finalize the fee update.
6263 let events = nodes[1].node.get_and_clear_pending_msg_events();
6264 assert_eq!(events.len(), 1);
6266 let raa_msg = match &events[0] {
6267 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6270 _ => panic!("Unexpected event"),
6273 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6274 check_added_monitors!(nodes[2], 1);
6275 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6277 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6278 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6279 assert_eq!(process_htlc_forwards_event.len(), 1);
6280 match &process_htlc_forwards_event[0] {
6281 &Event::PendingHTLCsForwardable { .. } => {},
6282 _ => panic!("Unexpected event"),
6285 // In response, we call ChannelManager's process_pending_htlc_forwards
6286 nodes[1].node.process_pending_htlc_forwards();
6287 check_added_monitors!(nodes[1], 1);
6289 // This causes the HTLC to be failed backwards.
6290 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6291 assert_eq!(fail_event.len(), 1);
6292 let (fail_msg, commitment_signed) = match &fail_event[0] {
6293 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6294 assert_eq!(updates.update_add_htlcs.len(), 0);
6295 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6296 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6297 assert_eq!(updates.update_fail_htlcs.len(), 1);
6298 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6300 _ => panic!("Unexpected event"),
6303 // Pass the failure messages back to nodes[0].
6304 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6305 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6307 // Complete the HTLC failure+removal process.
6308 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6309 check_added_monitors!(nodes[0], 1);
6310 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6311 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6312 check_added_monitors!(nodes[1], 2);
6313 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6314 assert_eq!(final_raa_event.len(), 1);
6315 let raa = match &final_raa_event[0] {
6316 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6317 _ => panic!("Unexpected event"),
6319 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6320 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6321 assert_eq!(fail_msg_event.len(), 1);
6322 match &fail_msg_event[0] {
6323 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6324 _ => panic!("Unexpected event"),
6326 let failure_event = nodes[0].node.get_and_clear_pending_events();
6327 assert_eq!(failure_event.len(), 1);
6328 match &failure_event[0] {
6329 &Event::PaymentFailed { rejected_by_dest, .. } => {
6330 assert!(!rejected_by_dest);
6332 _ => panic!("Unexpected event"),
6334 check_added_monitors!(nodes[0], 1);
6337 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6338 // 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.
6339 //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.
6342 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6343 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6344 let chanmon_cfgs = create_chanmon_cfgs(2);
6345 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6346 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6347 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6348 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6350 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6351 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6352 let logger = test_utils::TestLogger::new();
6353 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();
6354 route.paths[0][0].fee_msat = 100;
6356 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6357 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6358 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6359 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6363 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6364 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6365 let chanmon_cfgs = create_chanmon_cfgs(2);
6366 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6367 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6368 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6369 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6370 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6372 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6373 let logger = test_utils::TestLogger::new();
6374 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();
6375 route.paths[0][0].fee_msat = 0;
6376 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6377 assert_eq!(err, "Cannot send 0-msat HTLC"));
6379 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6380 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6384 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6385 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6386 let chanmon_cfgs = create_chanmon_cfgs(2);
6387 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6388 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6389 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6390 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6392 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6393 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6394 let logger = test_utils::TestLogger::new();
6395 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();
6396 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6397 check_added_monitors!(nodes[0], 1);
6398 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6399 updates.update_add_htlcs[0].amount_msat = 0;
6401 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6402 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6403 check_closed_broadcast!(nodes[1], true).unwrap();
6404 check_added_monitors!(nodes[1], 1);
6408 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6409 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6410 //It is enforced when constructing a route.
6411 let chanmon_cfgs = create_chanmon_cfgs(2);
6412 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6413 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6414 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6415 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6416 let logger = test_utils::TestLogger::new();
6418 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6420 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6421 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();
6422 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6423 assert_eq!(err, &"Channel CLTV overflowed?"));
6427 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6428 //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.
6429 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6430 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6431 let chanmon_cfgs = create_chanmon_cfgs(2);
6432 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6433 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6434 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6435 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6436 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6438 let logger = test_utils::TestLogger::new();
6439 for i in 0..max_accepted_htlcs {
6440 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6441 let payment_event = {
6442 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6443 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();
6444 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6445 check_added_monitors!(nodes[0], 1);
6447 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6448 assert_eq!(events.len(), 1);
6449 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6450 assert_eq!(htlcs[0].htlc_id, i);
6454 SendEvent::from_event(events.remove(0))
6456 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6457 check_added_monitors!(nodes[1], 0);
6458 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6460 expect_pending_htlcs_forwardable!(nodes[1]);
6461 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6463 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6464 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6465 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();
6466 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6467 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6469 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6470 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6474 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6475 //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.
6476 let chanmon_cfgs = create_chanmon_cfgs(2);
6477 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6478 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6479 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6480 let channel_value = 100000;
6481 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6482 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6484 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6486 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6487 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6488 let logger = test_utils::TestLogger::new();
6489 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6490 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6491 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)));
6493 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6494 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);
6496 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6499 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6501 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6502 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6503 let chanmon_cfgs = create_chanmon_cfgs(2);
6504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6506 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6507 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6508 let htlc_minimum_msat: u64;
6510 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6511 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6512 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6515 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6516 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6517 let logger = test_utils::TestLogger::new();
6518 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();
6519 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6520 check_added_monitors!(nodes[0], 1);
6521 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6522 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6523 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6524 assert!(nodes[1].node.list_channels().is_empty());
6525 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6526 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()));
6527 check_added_monitors!(nodes[1], 1);
6531 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6532 //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
6533 let chanmon_cfgs = create_chanmon_cfgs(2);
6534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6536 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6537 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6538 let logger = test_utils::TestLogger::new();
6540 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6541 let channel_reserve = chan_stat.channel_reserve_msat;
6542 let feerate = get_feerate!(nodes[0], chan.2);
6543 // The 2* and +1 are for the fee spike reserve.
6544 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6546 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6547 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6548 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6549 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();
6550 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6551 check_added_monitors!(nodes[0], 1);
6552 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6554 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6555 // at this time channel-initiatee receivers are not required to enforce that senders
6556 // respect the fee_spike_reserve.
6557 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6558 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6560 assert!(nodes[1].node.list_channels().is_empty());
6561 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6562 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6563 check_added_monitors!(nodes[1], 1);
6567 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6568 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6569 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6570 let chanmon_cfgs = create_chanmon_cfgs(2);
6571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6573 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6575 let logger = test_utils::TestLogger::new();
6577 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6578 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6580 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6581 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();
6583 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6584 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6585 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6586 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6588 let mut msg = msgs::UpdateAddHTLC {
6592 payment_hash: our_payment_hash,
6593 cltv_expiry: htlc_cltv,
6594 onion_routing_packet: onion_packet.clone(),
6597 for i in 0..super::channel::OUR_MAX_HTLCS {
6598 msg.htlc_id = i as u64;
6599 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6601 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6602 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6604 assert!(nodes[1].node.list_channels().is_empty());
6605 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6606 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6607 check_added_monitors!(nodes[1], 1);
6611 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6612 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6613 let chanmon_cfgs = create_chanmon_cfgs(2);
6614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6616 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6617 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6618 let logger = test_utils::TestLogger::new();
6620 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6621 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6622 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();
6623 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6624 check_added_monitors!(nodes[0], 1);
6625 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6626 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6627 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6629 assert!(nodes[1].node.list_channels().is_empty());
6630 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6631 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6632 check_added_monitors!(nodes[1], 1);
6636 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6637 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6638 let chanmon_cfgs = create_chanmon_cfgs(2);
6639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6642 let logger = test_utils::TestLogger::new();
6644 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6645 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6646 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6647 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();
6648 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6649 check_added_monitors!(nodes[0], 1);
6650 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6651 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6652 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6654 assert!(nodes[1].node.list_channels().is_empty());
6655 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6656 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6657 check_added_monitors!(nodes[1], 1);
6661 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6662 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6663 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6664 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6665 let chanmon_cfgs = create_chanmon_cfgs(2);
6666 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6667 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6668 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6669 let logger = test_utils::TestLogger::new();
6671 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6672 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6673 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6674 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();
6675 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6676 check_added_monitors!(nodes[0], 1);
6677 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6678 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6680 //Disconnect and Reconnect
6681 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6682 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6683 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6684 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6685 assert_eq!(reestablish_1.len(), 1);
6686 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6687 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6688 assert_eq!(reestablish_2.len(), 1);
6689 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6690 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6691 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6692 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6695 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6696 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6697 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6698 check_added_monitors!(nodes[1], 1);
6699 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6701 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6703 assert!(nodes[1].node.list_channels().is_empty());
6704 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6705 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6706 check_added_monitors!(nodes[1], 1);
6710 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6711 //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.
6713 let chanmon_cfgs = create_chanmon_cfgs(2);
6714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6716 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6717 let logger = test_utils::TestLogger::new();
6718 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6719 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6720 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6721 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();
6722 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6724 check_added_monitors!(nodes[0], 1);
6725 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6726 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6728 let update_msg = msgs::UpdateFulfillHTLC{
6731 payment_preimage: our_payment_preimage,
6734 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6736 assert!(nodes[0].node.list_channels().is_empty());
6737 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6738 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()));
6739 check_added_monitors!(nodes[0], 1);
6743 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6744 //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.
6746 let chanmon_cfgs = create_chanmon_cfgs(2);
6747 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6748 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6749 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6750 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6751 let logger = test_utils::TestLogger::new();
6753 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6754 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6755 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();
6756 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6757 check_added_monitors!(nodes[0], 1);
6758 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6759 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6761 let update_msg = msgs::UpdateFailHTLC{
6764 reason: msgs::OnionErrorPacket { data: Vec::new()},
6767 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6769 assert!(nodes[0].node.list_channels().is_empty());
6770 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6771 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()));
6772 check_added_monitors!(nodes[0], 1);
6776 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6777 //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.
6779 let chanmon_cfgs = create_chanmon_cfgs(2);
6780 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6781 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6782 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6783 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6784 let logger = test_utils::TestLogger::new();
6786 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6787 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6788 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();
6789 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6790 check_added_monitors!(nodes[0], 1);
6791 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6792 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6794 let update_msg = msgs::UpdateFailMalformedHTLC{
6797 sha256_of_onion: [1; 32],
6798 failure_code: 0x8000,
6801 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6803 assert!(nodes[0].node.list_channels().is_empty());
6804 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6805 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()));
6806 check_added_monitors!(nodes[0], 1);
6810 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6811 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6813 let chanmon_cfgs = create_chanmon_cfgs(2);
6814 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6815 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6816 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6817 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6819 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6821 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6822 check_added_monitors!(nodes[1], 1);
6824 let events = nodes[1].node.get_and_clear_pending_msg_events();
6825 assert_eq!(events.len(), 1);
6826 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6828 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, .. } } => {
6829 assert!(update_add_htlcs.is_empty());
6830 assert_eq!(update_fulfill_htlcs.len(), 1);
6831 assert!(update_fail_htlcs.is_empty());
6832 assert!(update_fail_malformed_htlcs.is_empty());
6833 assert!(update_fee.is_none());
6834 update_fulfill_htlcs[0].clone()
6836 _ => panic!("Unexpected event"),
6840 update_fulfill_msg.htlc_id = 1;
6842 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6844 assert!(nodes[0].node.list_channels().is_empty());
6845 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6846 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6847 check_added_monitors!(nodes[0], 1);
6851 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6852 //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.
6854 let chanmon_cfgs = create_chanmon_cfgs(2);
6855 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6856 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6857 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6858 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6860 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6862 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6863 check_added_monitors!(nodes[1], 1);
6865 let events = nodes[1].node.get_and_clear_pending_msg_events();
6866 assert_eq!(events.len(), 1);
6867 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6869 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, .. } } => {
6870 assert!(update_add_htlcs.is_empty());
6871 assert_eq!(update_fulfill_htlcs.len(), 1);
6872 assert!(update_fail_htlcs.is_empty());
6873 assert!(update_fail_malformed_htlcs.is_empty());
6874 assert!(update_fee.is_none());
6875 update_fulfill_htlcs[0].clone()
6877 _ => panic!("Unexpected event"),
6881 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6883 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6885 assert!(nodes[0].node.list_channels().is_empty());
6886 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6887 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6888 check_added_monitors!(nodes[0], 1);
6892 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6893 //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.
6895 let chanmon_cfgs = create_chanmon_cfgs(2);
6896 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6897 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6898 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6899 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6900 let logger = test_utils::TestLogger::new();
6902 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6903 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6904 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();
6905 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6906 check_added_monitors!(nodes[0], 1);
6908 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6909 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6911 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6912 check_added_monitors!(nodes[1], 0);
6913 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6915 let events = nodes[1].node.get_and_clear_pending_msg_events();
6917 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6919 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, .. } } => {
6920 assert!(update_add_htlcs.is_empty());
6921 assert!(update_fulfill_htlcs.is_empty());
6922 assert!(update_fail_htlcs.is_empty());
6923 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6924 assert!(update_fee.is_none());
6925 update_fail_malformed_htlcs[0].clone()
6927 _ => panic!("Unexpected event"),
6930 update_msg.failure_code &= !0x8000;
6931 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6933 assert!(nodes[0].node.list_channels().is_empty());
6934 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6935 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6936 check_added_monitors!(nodes[0], 1);
6940 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6941 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6942 // * 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.
6944 let chanmon_cfgs = create_chanmon_cfgs(3);
6945 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6946 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6947 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6948 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6949 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6950 let logger = test_utils::TestLogger::new();
6952 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6955 let mut payment_event = {
6956 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6957 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();
6958 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6959 check_added_monitors!(nodes[0], 1);
6960 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6961 assert_eq!(events.len(), 1);
6962 SendEvent::from_event(events.remove(0))
6964 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6965 check_added_monitors!(nodes[1], 0);
6966 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6967 expect_pending_htlcs_forwardable!(nodes[1]);
6968 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6969 assert_eq!(events_2.len(), 1);
6970 check_added_monitors!(nodes[1], 1);
6971 payment_event = SendEvent::from_event(events_2.remove(0));
6972 assert_eq!(payment_event.msgs.len(), 1);
6975 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6976 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6977 check_added_monitors!(nodes[2], 0);
6978 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6980 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6981 assert_eq!(events_3.len(), 1);
6982 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6984 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 } } => {
6985 assert!(update_add_htlcs.is_empty());
6986 assert!(update_fulfill_htlcs.is_empty());
6987 assert!(update_fail_htlcs.is_empty());
6988 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6989 assert!(update_fee.is_none());
6990 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6992 _ => panic!("Unexpected event"),
6996 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6998 check_added_monitors!(nodes[1], 0);
6999 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7000 expect_pending_htlcs_forwardable!(nodes[1]);
7001 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7002 assert_eq!(events_4.len(), 1);
7004 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7006 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, .. } } => {
7007 assert!(update_add_htlcs.is_empty());
7008 assert!(update_fulfill_htlcs.is_empty());
7009 assert_eq!(update_fail_htlcs.len(), 1);
7010 assert!(update_fail_malformed_htlcs.is_empty());
7011 assert!(update_fee.is_none());
7013 _ => panic!("Unexpected event"),
7016 check_added_monitors!(nodes[1], 1);
7019 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7020 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7021 // 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
7022 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7024 let chanmon_cfgs = create_chanmon_cfgs(2);
7025 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7026 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7027 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7028 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7030 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7032 // We route 2 dust-HTLCs between A and B
7033 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7034 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7035 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7037 // Cache one local commitment tx as previous
7038 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7040 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7041 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7042 check_added_monitors!(nodes[1], 0);
7043 expect_pending_htlcs_forwardable!(nodes[1]);
7044 check_added_monitors!(nodes[1], 1);
7046 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7047 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7048 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7049 check_added_monitors!(nodes[0], 1);
7051 // Cache one local commitment tx as lastest
7052 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7054 let events = nodes[0].node.get_and_clear_pending_msg_events();
7056 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7057 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7059 _ => panic!("Unexpected event"),
7062 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7063 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7065 _ => panic!("Unexpected event"),
7068 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7069 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7070 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7072 if announce_latest {
7073 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7075 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7078 check_closed_broadcast!(nodes[0], false);
7079 check_added_monitors!(nodes[0], 1);
7081 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7082 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7083 let events = nodes[0].node.get_and_clear_pending_events();
7084 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7085 assert_eq!(events.len(), 2);
7086 let mut first_failed = false;
7087 for event in events {
7089 Event::PaymentFailed { payment_hash, .. } => {
7090 if payment_hash == payment_hash_1 {
7091 assert!(!first_failed);
7092 first_failed = true;
7094 assert_eq!(payment_hash, payment_hash_2);
7097 _ => panic!("Unexpected event"),
7103 fn test_failure_delay_dust_htlc_local_commitment() {
7104 do_test_failure_delay_dust_htlc_local_commitment(true);
7105 do_test_failure_delay_dust_htlc_local_commitment(false);
7109 fn test_no_failure_dust_htlc_local_commitment() {
7110 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
7111 // prone to error, we test here that a dummy transaction don't fail them.
7113 let chanmon_cfgs = create_chanmon_cfgs(2);
7114 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7115 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7116 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7117 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7120 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7122 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7123 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7125 // We route 2 dust-HTLCs between A and B
7126 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7127 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
7129 // Build a dummy invalid transaction trying to spend a commitment tx
7131 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
7132 script_sig: Script::new(),
7134 witness: Vec::new(),
7138 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
7142 let dummy_tx = Transaction {
7149 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7150 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
7151 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7152 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7153 // We broadcast a few more block to check everything is all right
7154 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.block_hash());
7155 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7156 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
7158 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
7159 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
7162 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7163 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7164 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7165 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7166 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7167 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7168 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7170 let chanmon_cfgs = create_chanmon_cfgs(3);
7171 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7172 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7173 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7174 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7176 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7178 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7179 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7181 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7182 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7184 // We revoked bs_commitment_tx
7186 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7187 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7190 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7191 let mut timeout_tx = Vec::new();
7193 // We fail dust-HTLC 1 by broadcast of local commitment tx
7194 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7195 check_closed_broadcast!(nodes[0], false);
7196 check_added_monitors!(nodes[0], 1);
7197 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7198 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7199 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7200 expect_payment_failed!(nodes[0], dust_hash, true);
7201 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7202 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7203 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7204 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7205 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7206 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7207 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7208 expect_payment_failed!(nodes[0], non_dust_hash, true);
7210 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7211 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7212 check_closed_broadcast!(nodes[0], false);
7213 check_added_monitors!(nodes[0], 1);
7214 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7215 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7216 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7217 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7219 expect_payment_failed!(nodes[0], dust_hash, true);
7220 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7221 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7222 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7223 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7224 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7225 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7226 expect_payment_failed!(nodes[0], non_dust_hash, true);
7228 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7230 let events = nodes[0].node.get_and_clear_pending_events();
7231 assert_eq!(events.len(), 2);
7234 Event::PaymentFailed { payment_hash, .. } => {
7235 if payment_hash == dust_hash { first = true; }
7236 else { first = false; }
7238 _ => panic!("Unexpected event"),
7241 Event::PaymentFailed { payment_hash, .. } => {
7242 if first { assert_eq!(payment_hash, non_dust_hash); }
7243 else { assert_eq!(payment_hash, dust_hash); }
7245 _ => panic!("Unexpected event"),
7252 fn test_sweep_outbound_htlc_failure_update() {
7253 do_test_sweep_outbound_htlc_failure_update(false, true);
7254 do_test_sweep_outbound_htlc_failure_update(false, false);
7255 do_test_sweep_outbound_htlc_failure_update(true, false);
7259 fn test_upfront_shutdown_script() {
7260 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7261 // enforce it at shutdown message
7263 let mut config = UserConfig::default();
7264 config.channel_options.announced_channel = true;
7265 config.peer_channel_config_limits.force_announced_channel_preference = false;
7266 config.channel_options.commit_upfront_shutdown_pubkey = false;
7267 let user_cfgs = [None, Some(config), None];
7268 let chanmon_cfgs = create_chanmon_cfgs(3);
7269 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7270 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7271 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7273 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7274 let flags = InitFeatures::known();
7275 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7276 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7277 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7278 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7279 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7280 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7281 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()));
7282 check_added_monitors!(nodes[2], 1);
7284 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7285 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7286 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7287 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7288 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7289 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7290 let events = nodes[2].node.get_and_clear_pending_msg_events();
7291 assert_eq!(events.len(), 1);
7293 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7294 _ => panic!("Unexpected event"),
7297 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7298 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7299 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7300 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7301 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7302 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7303 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7304 let events = nodes[1].node.get_and_clear_pending_msg_events();
7305 assert_eq!(events.len(), 1);
7307 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7308 _ => panic!("Unexpected event"),
7311 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7312 // channel smoothly, opt-out is from channel initiator here
7313 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7314 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7315 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7316 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7317 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7318 let events = nodes[0].node.get_and_clear_pending_msg_events();
7319 assert_eq!(events.len(), 1);
7321 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7322 _ => panic!("Unexpected event"),
7325 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7326 //// channel smoothly
7327 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7328 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7329 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7330 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7331 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7332 let events = nodes[0].node.get_and_clear_pending_msg_events();
7333 assert_eq!(events.len(), 2);
7335 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7336 _ => panic!("Unexpected event"),
7339 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7340 _ => panic!("Unexpected event"),
7345 fn test_user_configurable_csv_delay() {
7346 // We test our channel constructors yield errors when we pass them absurd csv delay
7348 let mut low_our_to_self_config = UserConfig::default();
7349 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7350 let mut high_their_to_self_config = UserConfig::default();
7351 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7352 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7353 let chanmon_cfgs = create_chanmon_cfgs(2);
7354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7356 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7358 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7359 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7360 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) {
7362 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())); },
7363 _ => panic!("Unexpected event"),
7365 } else { assert!(false) }
7367 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7368 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7369 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7370 open_channel.to_self_delay = 200;
7371 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) {
7373 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())); },
7374 _ => panic!("Unexpected event"),
7376 } else { assert!(false); }
7378 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7379 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7380 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()));
7381 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7382 accept_channel.to_self_delay = 200;
7383 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7384 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7386 &ErrorAction::SendErrorMessage { ref msg } => {
7387 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()));
7389 _ => { assert!(false); }
7391 } else { assert!(false); }
7393 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7394 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7395 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7396 open_channel.to_self_delay = 200;
7397 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) {
7399 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())); },
7400 _ => panic!("Unexpected event"),
7402 } else { assert!(false); }
7406 fn test_data_loss_protect() {
7407 // We want to be sure that :
7408 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7409 // * we close channel in case of detecting other being fallen behind
7410 // * we are able to claim our own outputs thanks to to_remote being static
7418 let chanmon_cfgs = create_chanmon_cfgs(2);
7419 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7420 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7421 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7423 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7425 // Cache node A state before any channel update
7426 let previous_node_state = nodes[0].node.encode();
7427 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7428 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7430 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7431 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7433 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7434 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7436 // Restore node A from previous state
7437 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7438 let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7439 chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7440 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7441 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7442 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7443 monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7445 let mut channel_monitors = HashMap::new();
7446 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7447 <(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 {
7448 keys_manager: &keys_manager,
7449 fee_estimator: &fee_estimator,
7452 tx_broadcaster: &tx_broadcaster,
7453 default_config: UserConfig::default(),
7457 nodes[0].node = &node_state_0;
7458 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7459 nodes[0].chan_monitor = &monitor;
7460 nodes[0].chain_monitor = &chain_monitor;
7462 nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7463 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7464 nodes[0].block_notifier.register_listener(nodes[0].node);
7466 check_added_monitors!(nodes[0], 1);
7468 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7469 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7471 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7473 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7474 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7475 check_added_monitors!(nodes[0], 1);
7478 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7479 assert_eq!(node_txn.len(), 0);
7482 let mut reestablish_1 = Vec::with_capacity(1);
7483 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7484 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7485 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7486 reestablish_1.push(msg.clone());
7487 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7488 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7490 &ErrorAction::SendErrorMessage { ref msg } => {
7491 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");
7493 _ => panic!("Unexpected event!"),
7496 panic!("Unexpected event")
7500 // Check we close channel detecting A is fallen-behind
7501 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7502 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7503 check_added_monitors!(nodes[1], 1);
7506 // Check A is able to claim to_remote output
7507 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7508 assert_eq!(node_txn.len(), 1);
7509 check_spends!(node_txn[0], chan.3);
7510 assert_eq!(node_txn[0].output.len(), 2);
7511 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7512 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7513 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7514 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7515 assert_eq!(spend_txn.len(), 1);
7516 check_spends!(spend_txn[0], node_txn[0]);
7520 fn test_check_htlc_underpaying() {
7521 // Send payment through A -> B but A is maliciously
7522 // sending a probe payment (i.e less than expected value0
7523 // to B, B should refuse payment.
7525 let chanmon_cfgs = create_chanmon_cfgs(2);
7526 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7527 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7528 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7530 // Create some initial channels
7531 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7533 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7535 // Node 3 is expecting payment of 100_000 but receive 10_000,
7536 // fail htlc like we didn't know the preimage.
7537 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7538 nodes[1].node.process_pending_htlc_forwards();
7540 let events = nodes[1].node.get_and_clear_pending_msg_events();
7541 assert_eq!(events.len(), 1);
7542 let (update_fail_htlc, commitment_signed) = match events[0] {
7543 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 } } => {
7544 assert!(update_add_htlcs.is_empty());
7545 assert!(update_fulfill_htlcs.is_empty());
7546 assert_eq!(update_fail_htlcs.len(), 1);
7547 assert!(update_fail_malformed_htlcs.is_empty());
7548 assert!(update_fee.is_none());
7549 (update_fail_htlcs[0].clone(), commitment_signed)
7551 _ => panic!("Unexpected event"),
7553 check_added_monitors!(nodes[1], 1);
7555 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7556 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7558 // 10_000 msat as u64, followed by a height of 99 as u32
7559 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7560 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7561 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7562 nodes[1].node.get_and_clear_pending_events();
7566 fn test_announce_disable_channels() {
7567 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7568 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7570 let chanmon_cfgs = create_chanmon_cfgs(2);
7571 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7572 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7573 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7575 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7576 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7577 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7580 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7581 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7583 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7584 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7585 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7586 assert_eq!(msg_events.len(), 3);
7587 for e in msg_events {
7589 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7590 let short_id = msg.contents.short_channel_id;
7591 // Check generated channel_update match list in PendingChannelUpdate
7592 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7593 panic!("Generated ChannelUpdate for wrong chan!");
7596 _ => panic!("Unexpected event"),
7600 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7601 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7602 assert_eq!(reestablish_1.len(), 3);
7603 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7604 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7605 assert_eq!(reestablish_2.len(), 3);
7607 // Reestablish chan_1
7608 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7609 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7610 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7611 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7612 // Reestablish chan_2
7613 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7614 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7615 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7616 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7617 // Reestablish chan_3
7618 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7619 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7620 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7621 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7623 nodes[0].node.timer_chan_freshness_every_min();
7624 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7628 fn test_bump_penalty_txn_on_revoked_commitment() {
7629 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7630 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7632 let chanmon_cfgs = create_chanmon_cfgs(2);
7633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7635 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7637 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7638 let logger = test_utils::TestLogger::new();
7641 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7642 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7643 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();
7644 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7646 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7647 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7648 assert_eq!(revoked_txn[0].output.len(), 4);
7649 assert_eq!(revoked_txn[0].input.len(), 1);
7650 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7651 let revoked_txid = revoked_txn[0].txid();
7653 let mut penalty_sum = 0;
7654 for outp in revoked_txn[0].output.iter() {
7655 if outp.script_pubkey.is_v0_p2wsh() {
7656 penalty_sum += outp.value;
7660 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7661 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7663 // Actually revoke tx by claiming a HTLC
7664 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7665 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7666 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7667 check_added_monitors!(nodes[1], 1);
7669 // One or more justice tx should have been broadcast, check it
7673 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7674 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7675 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7676 assert_eq!(node_txn[0].output.len(), 1);
7677 check_spends!(node_txn[0], revoked_txn[0]);
7678 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7679 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7680 penalty_1 = node_txn[0].txid();
7684 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7685 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.block_hash());
7686 let mut penalty_2 = penalty_1;
7687 let mut feerate_2 = 0;
7689 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7690 assert_eq!(node_txn.len(), 1);
7691 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7692 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7693 assert_eq!(node_txn[0].output.len(), 1);
7694 check_spends!(node_txn[0], revoked_txn[0]);
7695 penalty_2 = node_txn[0].txid();
7696 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7697 assert_ne!(penalty_2, penalty_1);
7698 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7699 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7700 // Verify 25% bump heuristic
7701 assert!(feerate_2 * 100 >= feerate_1 * 125);
7705 assert_ne!(feerate_2, 0);
7707 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7708 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7710 let mut feerate_3 = 0;
7712 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7713 assert_eq!(node_txn.len(), 1);
7714 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7715 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7716 assert_eq!(node_txn[0].output.len(), 1);
7717 check_spends!(node_txn[0], revoked_txn[0]);
7718 penalty_3 = node_txn[0].txid();
7719 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7720 assert_ne!(penalty_3, penalty_2);
7721 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7722 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7723 // Verify 25% bump heuristic
7724 assert!(feerate_3 * 100 >= feerate_2 * 125);
7728 assert_ne!(feerate_3, 0);
7730 nodes[1].node.get_and_clear_pending_events();
7731 nodes[1].node.get_and_clear_pending_msg_events();
7735 fn test_bump_penalty_txn_on_revoked_htlcs() {
7736 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7737 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7739 let chanmon_cfgs = create_chanmon_cfgs(2);
7740 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7741 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7742 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7745 // Lock HTLC in both directions
7746 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7747 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7749 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7750 assert_eq!(revoked_local_txn[0].input.len(), 1);
7751 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7753 // Revoke local commitment tx
7754 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7756 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7757 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7758 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7759 check_closed_broadcast!(nodes[1], false);
7760 check_added_monitors!(nodes[1], 1);
7762 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7763 assert_eq!(revoked_htlc_txn.len(), 4);
7764 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7765 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7766 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7767 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7768 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7769 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7770 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7771 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7772 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7773 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7774 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7775 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7778 // Broadcast set of revoked txn on A
7779 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.block_hash());
7780 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7782 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7783 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);
7788 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7789 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7790 // Verify claim tx are spending revoked HTLC txn
7791 assert_eq!(node_txn[4].input.len(), 2);
7792 assert_eq!(node_txn[4].output.len(), 1);
7793 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7794 first = node_txn[4].txid();
7795 // Store both feerates for later comparison
7796 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7797 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7798 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7802 // Connect three more block to see if bumped penalty are issued for HTLC txn
7803 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7804 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7806 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7807 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7809 check_spends!(node_txn[0], revoked_local_txn[0]);
7810 check_spends!(node_txn[1], revoked_local_txn[0]);
7815 // Few more blocks to confirm penalty txn
7816 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.block_hash());
7817 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7818 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7820 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7821 assert_eq!(node_txn.len(), 1);
7823 assert_eq!(node_txn[0].input.len(), 2);
7824 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7825 // Verify bumped tx is different and 25% bump heuristic
7826 assert_ne!(first, node_txn[0].txid());
7827 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7828 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7829 assert!(feerate_2 * 100 > feerate_1 * 125);
7830 let txn = vec![node_txn[0].clone()];
7834 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7835 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7836 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7837 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.block_hash());
7839 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7840 // We verify than no new transaction has been broadcast because previously
7841 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7842 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7843 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7844 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7845 // up bumped justice generation.
7846 assert_eq!(node_txn.len(), 0);
7849 check_closed_broadcast!(nodes[0], false);
7850 check_added_monitors!(nodes[0], 1);
7854 fn test_bump_penalty_txn_on_remote_commitment() {
7855 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7856 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7859 // Provide preimage for one
7860 // Check aggregation
7862 let chanmon_cfgs = create_chanmon_cfgs(2);
7863 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7864 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7865 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7867 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7868 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7869 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7871 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7872 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7873 assert_eq!(remote_txn[0].output.len(), 4);
7874 assert_eq!(remote_txn[0].input.len(), 1);
7875 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7877 // Claim a HTLC without revocation (provide B monitor with preimage)
7878 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7879 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7880 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7881 check_added_monitors!(nodes[1], 2);
7883 // One or more claim tx should have been broadcast, check it
7886 let feerate_timeout;
7887 let feerate_preimage;
7889 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7890 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7891 assert_eq!(node_txn[0].input.len(), 1);
7892 assert_eq!(node_txn[1].input.len(), 1);
7893 check_spends!(node_txn[0], remote_txn[0]);
7894 check_spends!(node_txn[1], remote_txn[0]);
7895 check_spends!(node_txn[2], chan.3);
7896 check_spends!(node_txn[3], node_txn[2]);
7897 check_spends!(node_txn[4], node_txn[2]);
7898 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7899 timeout = node_txn[0].txid();
7900 let index = node_txn[0].input[0].previous_output.vout;
7901 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7902 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7904 preimage = node_txn[1].txid();
7905 let index = node_txn[1].input[0].previous_output.vout;
7906 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7907 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7909 timeout = node_txn[1].txid();
7910 let index = node_txn[1].input[0].previous_output.vout;
7911 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7912 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7914 preimage = node_txn[0].txid();
7915 let index = node_txn[0].input[0].previous_output.vout;
7916 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7917 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7921 assert_ne!(feerate_timeout, 0);
7922 assert_ne!(feerate_preimage, 0);
7924 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7925 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.block_hash());
7927 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7928 assert_eq!(node_txn.len(), 2);
7929 assert_eq!(node_txn[0].input.len(), 1);
7930 assert_eq!(node_txn[1].input.len(), 1);
7931 check_spends!(node_txn[0], remote_txn[0]);
7932 check_spends!(node_txn[1], remote_txn[0]);
7933 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7934 let index = node_txn[0].input[0].previous_output.vout;
7935 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7936 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7937 assert!(new_feerate * 100 > feerate_timeout * 125);
7938 assert_ne!(timeout, node_txn[0].txid());
7940 let index = node_txn[1].input[0].previous_output.vout;
7941 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7942 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7943 assert!(new_feerate * 100 > feerate_preimage * 125);
7944 assert_ne!(preimage, node_txn[1].txid());
7946 let index = node_txn[1].input[0].previous_output.vout;
7947 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7948 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7949 assert!(new_feerate * 100 > feerate_timeout * 125);
7950 assert_ne!(timeout, node_txn[1].txid());
7952 let index = node_txn[0].input[0].previous_output.vout;
7953 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7954 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7955 assert!(new_feerate * 100 > feerate_preimage * 125);
7956 assert_ne!(preimage, node_txn[0].txid());
7961 nodes[1].node.get_and_clear_pending_events();
7962 nodes[1].node.get_and_clear_pending_msg_events();
7966 fn test_set_outpoints_partial_claiming() {
7967 // - remote party claim tx, new bump tx
7968 // - disconnect remote claiming tx, new bump
7969 // - disconnect tx, see no tx anymore
7970 let chanmon_cfgs = create_chanmon_cfgs(2);
7971 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7972 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7973 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7975 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7976 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7977 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7979 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7980 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7981 assert_eq!(remote_txn.len(), 3);
7982 assert_eq!(remote_txn[0].output.len(), 4);
7983 assert_eq!(remote_txn[0].input.len(), 1);
7984 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7985 check_spends!(remote_txn[1], remote_txn[0]);
7986 check_spends!(remote_txn[2], remote_txn[0]);
7988 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7989 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7990 // Provide node A with both preimage
7991 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7992 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7993 check_added_monitors!(nodes[0], 2);
7994 nodes[0].node.get_and_clear_pending_events();
7995 nodes[0].node.get_and_clear_pending_msg_events();
7997 // Connect blocks on node A commitment transaction
7998 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7999 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8000 check_closed_broadcast!(nodes[0], false);
8001 check_added_monitors!(nodes[0], 1);
8002 // Verify node A broadcast tx claiming both HTLCs
8004 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8005 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8006 assert_eq!(node_txn.len(), 4);
8007 check_spends!(node_txn[0], remote_txn[0]);
8008 check_spends!(node_txn[1], chan.3);
8009 check_spends!(node_txn[2], node_txn[1]);
8010 check_spends!(node_txn[3], node_txn[1]);
8011 assert_eq!(node_txn[0].input.len(), 2);
8015 // Connect blocks on node B
8016 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
8017 check_closed_broadcast!(nodes[1], false);
8018 check_added_monitors!(nodes[1], 1);
8019 // Verify node B broadcast 2 HTLC-timeout txn
8020 let partial_claim_tx = {
8021 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8022 assert_eq!(node_txn.len(), 3);
8023 check_spends!(node_txn[1], node_txn[0]);
8024 check_spends!(node_txn[2], node_txn[0]);
8025 assert_eq!(node_txn[1].input.len(), 1);
8026 assert_eq!(node_txn[2].input.len(), 1);
8030 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8031 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8032 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8034 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8035 assert_eq!(node_txn.len(), 1);
8036 check_spends!(node_txn[0], remote_txn[0]);
8037 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8040 nodes[0].node.get_and_clear_pending_msg_events();
8042 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8043 nodes[0].block_notifier.block_disconnected(&header, 102);
8045 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8046 assert_eq!(node_txn.len(), 1);
8047 check_spends!(node_txn[0], remote_txn[0]);
8048 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8052 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8053 nodes[0].block_notifier.block_disconnected(&header, 101);
8054 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
8056 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8057 assert_eq!(node_txn.len(), 0);
8063 fn test_counterparty_raa_skip_no_crash() {
8064 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8065 // commitment transaction, we would have happily carried on and provided them the next
8066 // commitment transaction based on one RAA forward. This would probably eventually have led to
8067 // channel closure, but it would not have resulted in funds loss. Still, our
8068 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8069 // check simply that the channel is closed in response to such an RAA, but don't check whether
8070 // we decide to punish our counterparty for revoking their funds (as we don't currently
8072 let chanmon_cfgs = create_chanmon_cfgs(2);
8073 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8074 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8075 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8076 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8078 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8079 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8080 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8081 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8082 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8083 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8085 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8086 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8087 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8088 check_added_monitors!(nodes[1], 1);
8092 fn test_bump_txn_sanitize_tracking_maps() {
8093 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8094 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8096 let chanmon_cfgs = create_chanmon_cfgs(2);
8097 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8098 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8099 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8101 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8102 // Lock HTLC in both directions
8103 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8104 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8106 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8107 assert_eq!(revoked_local_txn[0].input.len(), 1);
8108 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8110 // Revoke local commitment tx
8111 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8113 // Broadcast set of revoked txn on A
8114 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
8115 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8117 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8118 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8119 check_closed_broadcast!(nodes[0], false);
8120 check_added_monitors!(nodes[0], 1);
8122 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8123 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8124 check_spends!(node_txn[0], revoked_local_txn[0]);
8125 check_spends!(node_txn[1], revoked_local_txn[0]);
8126 check_spends!(node_txn[2], revoked_local_txn[0]);
8127 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8131 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8132 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
8133 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.block_hash());
8135 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8136 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8137 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8138 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8144 fn test_override_channel_config() {
8145 let chanmon_cfgs = create_chanmon_cfgs(2);
8146 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8147 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8148 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8150 // Node0 initiates a channel to node1 using the override config.
8151 let mut override_config = UserConfig::default();
8152 override_config.own_channel_config.our_to_self_delay = 200;
8154 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8156 // Assert the channel created by node0 is using the override config.
8157 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8158 assert_eq!(res.channel_flags, 0);
8159 assert_eq!(res.to_self_delay, 200);
8163 fn test_override_0msat_htlc_minimum() {
8164 let mut zero_config = UserConfig::default();
8165 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8166 let chanmon_cfgs = create_chanmon_cfgs(2);
8167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8169 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8171 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8172 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8173 assert_eq!(res.htlc_minimum_msat, 1);
8175 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8176 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8177 assert_eq!(res.htlc_minimum_msat, 1);
8181 fn test_simple_payment_secret() {
8182 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8183 // features, however.
8184 let chanmon_cfgs = create_chanmon_cfgs(3);
8185 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8186 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8187 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8189 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8190 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8191 let logger = test_utils::TestLogger::new();
8193 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8194 let payment_secret = PaymentSecret([0xdb; 32]);
8195 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8196 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();
8197 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8198 // Claiming with all the correct values but the wrong secret should result in nothing...
8199 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8200 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8201 // ...but with the right secret we should be able to claim all the way back
8202 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8206 fn test_simple_mpp() {
8207 // Simple test of sending a multi-path payment.
8208 let chanmon_cfgs = create_chanmon_cfgs(4);
8209 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8210 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8211 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8213 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8214 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8215 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8216 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8217 let logger = test_utils::TestLogger::new();
8219 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8220 let payment_secret = PaymentSecret([0xdb; 32]);
8221 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8222 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();
8223 let path = route.paths[0].clone();
8224 route.paths.push(path);
8225 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8226 route.paths[0][0].short_channel_id = chan_1_id;
8227 route.paths[0][1].short_channel_id = chan_3_id;
8228 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8229 route.paths[1][0].short_channel_id = chan_2_id;
8230 route.paths[1][1].short_channel_id = chan_4_id;
8231 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8232 // Claiming with all the correct values but the wrong secret should result in nothing...
8233 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8234 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8235 // ...but with the right secret we should be able to claim all the way back
8236 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8240 fn test_update_err_monitor_lockdown() {
8241 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8242 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8243 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8245 // This scenario may happen in a watchtower setup, where watchtower process a block height
8246 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8247 // commitment at same time.
8249 let chanmon_cfgs = create_chanmon_cfgs(2);
8250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8252 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8254 // Create some initial channel
8255 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8256 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8258 // Rebalance the network to generate htlc in the two directions
8259 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8261 // Route a HTLC from node 0 to node 1 (but don't settle)
8262 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8264 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8265 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8266 let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8268 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8269 let monitor = monitors.get(&outpoint).unwrap();
8270 let mut w = test_utils::TestVecWriter(Vec::new());
8271 monitor.write_for_disk(&mut w).unwrap();
8272 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8273 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8274 assert!(new_monitor == *monitor);
8275 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8276 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8279 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8280 watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
8282 // Try to update ChannelMonitor
8283 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8284 check_added_monitors!(nodes[1], 1);
8285 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8286 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8287 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8288 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8289 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8290 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8291 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8292 } else { assert!(false); }
8293 } else { assert!(false); };
8294 // Our local monitor is in-sync and hasn't processed yet timeout
8295 check_added_monitors!(nodes[0], 1);
8296 let events = nodes[0].node.get_and_clear_pending_events();
8297 assert_eq!(events.len(), 1);
8301 fn test_concurrent_monitor_claim() {
8302 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8303 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8304 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8305 // state N+1 confirms. Alice claims output from state N+1.
8307 let chanmon_cfgs = create_chanmon_cfgs(2);
8308 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8309 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8310 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8312 // Create some initial channel
8313 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8314 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8316 // Rebalance the network to generate htlc in the two directions
8317 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8319 // Route a HTLC from node 0 to node 1 (but don't settle)
8320 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8322 // Copy SimpleManyChannelMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8323 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8324 let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8325 let watchtower_alice = {
8326 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8327 let monitor = monitors.get(&outpoint).unwrap();
8328 let mut w = test_utils::TestVecWriter(Vec::new());
8329 monitor.write_for_disk(&mut w).unwrap();
8330 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8331 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8332 assert!(new_monitor == *monitor);
8333 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8334 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8337 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8338 watchtower_alice.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8340 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8342 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8343 assert_eq!(txn.len(), 2);
8347 // Copy SimpleManyChannelMonitor to simulate watchtower Bob and make it receive a commitment update first.
8348 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8349 let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
8350 let watchtower_bob = {
8351 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
8352 let monitor = monitors.get(&outpoint).unwrap();
8353 let mut w = test_utils::TestVecWriter(Vec::new());
8354 monitor.write_for_disk(&mut w).unwrap();
8355 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8356 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8357 assert!(new_monitor == *monitor);
8358 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
8359 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
8362 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8363 watchtower_bob.simple_monitor.block_connected(&header, 134, &vec![], &vec![]);
8365 // Route another payment to generate another update with still previous HTLC pending
8366 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8368 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8369 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();
8370 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8372 check_added_monitors!(nodes[1], 1);
8374 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8375 assert_eq!(updates.update_add_htlcs.len(), 1);
8376 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8377 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8378 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8379 // Watchtower Alice should already have seen the block and reject the update
8380 if let Err(_) = watchtower_alice.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8381 if let Ok(_) = watchtower_bob.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
8382 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
8383 } else { assert!(false); }
8384 } else { assert!(false); };
8385 // Our local monitor is in-sync and hasn't processed yet timeout
8386 check_added_monitors!(nodes[0], 1);
8388 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8389 watchtower_bob.simple_monitor.block_connected(&header, 135, &vec![], &vec![]);
8391 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8394 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8395 assert_eq!(txn.len(), 2);
8396 bob_state_y = txn[0].clone();
8400 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8401 watchtower_alice.simple_monitor.block_connected(&header, 136, &vec![&bob_state_y][..], &vec![]);
8403 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8404 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8405 // the onchain detection of the HTLC output
8406 assert_eq!(htlc_txn.len(), 2);
8407 check_spends!(htlc_txn[0], bob_state_y);
8408 check_spends!(htlc_txn[1], bob_state_y);