1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
15 use chain::channelmonitor;
16 use chain::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
17 use chain::transaction::OutPoint;
18 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
19 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
20 use ln::channelmanager::{ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
21 use ln::channel::{Channel, ChannelError};
22 use ln::{chan_utils, onion_utils};
23 use routing::router::{Route, RouteHop, get_route};
24 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
26 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
27 use util::enforcing_trait_impls::EnforcingChannelKeys;
28 use util::{byte_utils, test_utils};
29 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
30 use util::errors::APIError;
31 use util::ser::{Writeable, ReadableArgs, Readable};
32 use util::config::UserConfig;
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hashes::HashEngine;
36 use bitcoin::hash_types::{Txid, BlockHash, WPubkeyHash};
37 use bitcoin::util::bip143;
38 use bitcoin::util::address::Address;
39 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
40 use bitcoin::blockdata::block::{Block, BlockHeader};
41 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
42 use bitcoin::blockdata::script::{Builder, Script};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::genesis_block;
45 use bitcoin::network::constants::Network;
47 use bitcoin::hashes::sha256::Hash as Sha256;
48 use bitcoin::hashes::Hash;
50 use bitcoin::secp256k1::{Secp256k1, Message};
51 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
55 use std::collections::{BTreeSet, HashMap, HashSet};
56 use std::default::Default;
57 use std::sync::{Arc, Mutex};
58 use std::sync::atomic::Ordering;
61 use ln::functional_test_utils::*;
62 use ln::chan_utils::PreCalculatedTxCreationKeys;
65 fn test_insane_channel_opens() {
66 // Stand up a network of 2 nodes
67 let chanmon_cfgs = create_chanmon_cfgs(2);
68 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
69 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
70 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
72 // Instantiate channel parameters where we push the maximum msats given our
74 let channel_value_sat = 31337; // same as funding satoshis
75 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
76 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
78 // Have node0 initiate a channel to node1 with aforementioned parameters
79 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
81 // Extract the channel open message from node0 to node1
82 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
84 // Test helper that asserts we get the correct error string given a mutator
85 // that supposedly makes the channel open message insane
86 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
87 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
88 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
89 assert_eq!(msg_events.len(), 1);
90 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
91 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
93 &ErrorAction::SendErrorMessage { .. } => {
94 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
96 _ => panic!("unexpected event!"),
98 } else { assert!(false); }
101 use ln::channel::MAX_FUNDING_SATOSHIS;
102 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
104 // Test all mutations that would make the channel open message insane
105 insane_open_helper(format!("Funding must be smaller than {}. It was {}", MAX_FUNDING_SATOSHIS, MAX_FUNDING_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
107 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
109 insane_open_helper(r"push_msat \d+ was larger than funding value \d+", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
111 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
113 insane_open_helper(r"Bogus; channel reserve \(\d+\) is less than dust limit \(\d+\)", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
115 insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
117 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
119 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
121 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
125 fn test_async_inbound_update_fee() {
126 let chanmon_cfgs = create_chanmon_cfgs(2);
127 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
128 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
129 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
130 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
131 let logger = test_utils::TestLogger::new();
132 let channel_id = chan.2;
135 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
139 // send (1) commitment_signed -.
140 // <- update_add_htlc/commitment_signed
141 // send (2) RAA (awaiting remote revoke) -.
142 // (1) commitment_signed is delivered ->
143 // .- send (3) RAA (awaiting remote revoke)
144 // (2) RAA is delivered ->
145 // .- send (4) commitment_signed
146 // <- (3) RAA is delivered
147 // send (5) commitment_signed -.
148 // <- (4) commitment_signed is delivered
150 // (5) commitment_signed is delivered ->
152 // (6) RAA is delivered ->
154 // First nodes[0] generates an update_fee
155 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
156 check_added_monitors!(nodes[0], 1);
158 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
159 assert_eq!(events_0.len(), 1);
160 let (update_msg, commitment_signed) = match events_0[0] { // (1)
161 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
162 (update_fee.as_ref(), commitment_signed)
164 _ => panic!("Unexpected event"),
167 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
169 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
170 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
171 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
172 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
173 check_added_monitors!(nodes[1], 1);
175 let payment_event = {
176 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
177 assert_eq!(events_1.len(), 1);
178 SendEvent::from_event(events_1.remove(0))
180 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
181 assert_eq!(payment_event.msgs.len(), 1);
183 // ...now when the messages get delivered everyone should be happy
184 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
185 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
186 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
187 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
188 check_added_monitors!(nodes[0], 1);
190 // deliver(1), generate (3):
191 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
192 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
193 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
194 check_added_monitors!(nodes[1], 1);
196 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
197 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
198 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
199 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
202 assert!(bs_update.update_fee.is_none()); // (4)
203 check_added_monitors!(nodes[1], 1);
205 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
206 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
207 assert!(as_update.update_add_htlcs.is_empty()); // (5)
208 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
211 assert!(as_update.update_fee.is_none()); // (5)
212 check_added_monitors!(nodes[0], 1);
214 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
215 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
216 // only (6) so get_event_msg's assert(len == 1) passes
217 check_added_monitors!(nodes[0], 1);
219 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
220 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
221 check_added_monitors!(nodes[1], 1);
223 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
224 check_added_monitors!(nodes[0], 1);
226 let events_2 = nodes[0].node.get_and_clear_pending_events();
227 assert_eq!(events_2.len(), 1);
229 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
230 _ => panic!("Unexpected event"),
233 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
234 check_added_monitors!(nodes[1], 1);
238 fn test_update_fee_unordered_raa() {
239 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
240 // crash in an earlier version of the update_fee patch)
241 let chanmon_cfgs = create_chanmon_cfgs(2);
242 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
243 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
244 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
245 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
246 let channel_id = chan.2;
247 let logger = test_utils::TestLogger::new();
250 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
252 // First nodes[0] generates an update_fee
253 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
254 check_added_monitors!(nodes[0], 1);
256 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257 assert_eq!(events_0.len(), 1);
258 let update_msg = match events_0[0] { // (1)
259 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
262 _ => panic!("Unexpected event"),
265 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
267 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
269 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
270 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
271 check_added_monitors!(nodes[1], 1);
273 let payment_event = {
274 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275 assert_eq!(events_1.len(), 1);
276 SendEvent::from_event(events_1.remove(0))
278 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279 assert_eq!(payment_event.msgs.len(), 1);
281 // ...now when the messages get delivered everyone should be happy
282 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286 check_added_monitors!(nodes[0], 1);
288 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
289 check_added_monitors!(nodes[1], 1);
291 // We can't continue, sadly, because our (1) now has a bogus signature
295 fn test_multi_flight_update_fee() {
296 let chanmon_cfgs = create_chanmon_cfgs(2);
297 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
298 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
299 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
300 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
301 let channel_id = chan.2;
304 // update_fee/commitment_signed ->
305 // .- send (1) RAA and (2) commitment_signed
306 // update_fee (never committed) ->
308 // We have to manually generate the above update_fee, it is allowed by the protocol but we
309 // don't track which updates correspond to which revoke_and_ack responses so we're in
310 // AwaitingRAA mode and will not generate the update_fee yet.
311 // <- (1) RAA delivered
312 // (3) is generated and send (4) CS -.
313 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
314 // know the per_commitment_point to use for it.
315 // <- (2) commitment_signed delivered
317 // B should send no response here
318 // (4) commitment_signed delivered ->
319 // <- RAA/commitment_signed delivered
322 // First nodes[0] generates an update_fee
323 let initial_feerate = get_feerate!(nodes[0], channel_id);
324 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
325 check_added_monitors!(nodes[0], 1);
327 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
328 assert_eq!(events_0.len(), 1);
329 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
330 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
331 (update_fee.as_ref().unwrap(), commitment_signed)
333 _ => panic!("Unexpected event"),
336 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
337 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
338 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
339 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
340 check_added_monitors!(nodes[1], 1);
342 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
344 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
345 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
346 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
348 // Create the (3) update_fee message that nodes[0] will generate before it does...
349 let mut update_msg_2 = msgs::UpdateFee {
350 channel_id: update_msg_1.channel_id.clone(),
351 feerate_per_kw: (initial_feerate + 30) as u32,
354 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
356 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
358 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
360 // Deliver (1), generating (3) and (4)
361 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
362 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
363 check_added_monitors!(nodes[0], 1);
364 assert!(as_second_update.update_add_htlcs.is_empty());
365 assert!(as_second_update.update_fulfill_htlcs.is_empty());
366 assert!(as_second_update.update_fail_htlcs.is_empty());
367 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
368 // Check that the update_fee newly generated matches what we delivered:
369 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
370 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
372 // Deliver (2) commitment_signed
373 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
374 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
375 check_added_monitors!(nodes[0], 1);
376 // No commitment_signed so get_event_msg's assert(len == 1) passes
378 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
379 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
380 check_added_monitors!(nodes[1], 1);
383 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
384 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
385 check_added_monitors!(nodes[1], 1);
387 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
388 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
389 check_added_monitors!(nodes[0], 1);
391 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
392 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
393 // No commitment_signed so get_event_msg's assert(len == 1) passes
394 check_added_monitors!(nodes[0], 1);
396 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
397 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
398 check_added_monitors!(nodes[1], 1);
402 fn test_1_conf_open() {
403 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
404 // tests that we properly send one in that case.
405 let mut alice_config = UserConfig::default();
406 alice_config.own_channel_config.minimum_depth = 1;
407 alice_config.channel_options.announced_channel = true;
408 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
409 let mut bob_config = UserConfig::default();
410 bob_config.own_channel_config.minimum_depth = 1;
411 bob_config.channel_options.announced_channel = true;
412 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
413 let chanmon_cfgs = create_chanmon_cfgs(2);
414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
416 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
418 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
420 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
423 connect_block(&nodes[1], &block, 1);
424 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
426 connect_block(&nodes[0], &block, 1);
427 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
428 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
431 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
432 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
433 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
437 fn do_test_sanity_on_in_flight_opens(steps: u8) {
438 // Previously, we had issues deserializing channels when we hadn't connected the first block
439 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
440 // serialization round-trips and simply do steps towards opening a channel and then drop the
443 let chanmon_cfgs = create_chanmon_cfgs(2);
444 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
445 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
446 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
448 if steps & 0b1000_0000 != 0{
450 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
453 connect_block(&nodes[0], &block, 1);
454 connect_block(&nodes[1], &block, 1);
457 if steps & 0x0f == 0 { return; }
458 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
459 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
461 if steps & 0x0f == 1 { return; }
462 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
463 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
465 if steps & 0x0f == 2 { return; }
466 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
468 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
470 if steps & 0x0f == 3 { return; }
471 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
472 check_added_monitors!(nodes[0], 0);
473 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
475 if steps & 0x0f == 4 { return; }
476 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
478 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
479 assert_eq!(added_monitors.len(), 1);
480 assert_eq!(added_monitors[0].0, funding_output);
481 added_monitors.clear();
483 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
485 if steps & 0x0f == 5 { return; }
486 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
488 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
489 assert_eq!(added_monitors.len(), 1);
490 assert_eq!(added_monitors[0].0, funding_output);
491 added_monitors.clear();
494 let events_4 = nodes[0].node.get_and_clear_pending_events();
495 assert_eq!(events_4.len(), 1);
497 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
498 assert_eq!(user_channel_id, 42);
499 assert_eq!(*funding_txo, funding_output);
501 _ => panic!("Unexpected event"),
504 if steps & 0x0f == 6 { return; }
505 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
507 if steps & 0x0f == 7 { return; }
508 confirm_transaction(&nodes[0], &tx);
509 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
513 fn test_sanity_on_in_flight_opens() {
514 do_test_sanity_on_in_flight_opens(0);
515 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(1);
517 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
518 do_test_sanity_on_in_flight_opens(2);
519 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
520 do_test_sanity_on_in_flight_opens(3);
521 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
522 do_test_sanity_on_in_flight_opens(4);
523 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
524 do_test_sanity_on_in_flight_opens(5);
525 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
526 do_test_sanity_on_in_flight_opens(6);
527 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
528 do_test_sanity_on_in_flight_opens(7);
529 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
530 do_test_sanity_on_in_flight_opens(8);
531 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
535 fn test_update_fee_vanilla() {
536 let chanmon_cfgs = create_chanmon_cfgs(2);
537 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
538 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
539 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
540 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
541 let channel_id = chan.2;
543 let feerate = get_feerate!(nodes[0], channel_id);
544 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
545 check_added_monitors!(nodes[0], 1);
547 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
548 assert_eq!(events_0.len(), 1);
549 let (update_msg, commitment_signed) = match events_0[0] {
550 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
551 (update_fee.as_ref(), commitment_signed)
553 _ => panic!("Unexpected event"),
555 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
557 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
558 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
559 check_added_monitors!(nodes[1], 1);
561 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
562 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
563 check_added_monitors!(nodes[0], 1);
565 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
566 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
567 // No commitment_signed so get_event_msg's assert(len == 1) passes
568 check_added_monitors!(nodes[0], 1);
570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
571 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
572 check_added_monitors!(nodes[1], 1);
576 fn test_update_fee_that_funder_cannot_afford() {
577 let chanmon_cfgs = create_chanmon_cfgs(2);
578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
580 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
581 let channel_value = 1888;
582 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
583 let channel_id = chan.2;
586 nodes[0].node.update_fee(channel_id, feerate).unwrap();
587 check_added_monitors!(nodes[0], 1);
588 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
590 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
592 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
594 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
595 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
597 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
599 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
600 let num_htlcs = commitment_tx.output.len() - 2;
601 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
602 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
603 actual_fee = channel_value - actual_fee;
604 assert_eq!(total_fee, actual_fee);
607 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
608 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
609 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
610 check_added_monitors!(nodes[0], 1);
612 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
614 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
616 //While producing the commitment_signed response after handling a received update_fee request the
617 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
618 //Should produce and error.
619 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
620 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
621 check_added_monitors!(nodes[1], 1);
622 check_closed_broadcast!(nodes[1], true);
626 fn test_update_fee_with_fundee_update_add_htlc() {
627 let chanmon_cfgs = create_chanmon_cfgs(2);
628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
630 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
631 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
632 let channel_id = chan.2;
633 let logger = test_utils::TestLogger::new();
636 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
638 let feerate = get_feerate!(nodes[0], channel_id);
639 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
640 check_added_monitors!(nodes[0], 1);
642 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
643 assert_eq!(events_0.len(), 1);
644 let (update_msg, commitment_signed) = match events_0[0] {
645 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
646 (update_fee.as_ref(), commitment_signed)
648 _ => panic!("Unexpected event"),
650 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
651 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
652 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
653 check_added_monitors!(nodes[1], 1);
655 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
656 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
657 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
659 // nothing happens since node[1] is in AwaitingRemoteRevoke
660 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
662 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
663 assert_eq!(added_monitors.len(), 0);
664 added_monitors.clear();
666 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
667 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
668 // node[1] has nothing to do
670 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
671 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
672 check_added_monitors!(nodes[0], 1);
674 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
675 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
676 // No commitment_signed so get_event_msg's assert(len == 1) passes
677 check_added_monitors!(nodes[0], 1);
678 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
679 check_added_monitors!(nodes[1], 1);
680 // AwaitingRemoteRevoke ends here
682 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
683 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
684 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
685 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
686 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
687 assert_eq!(commitment_update.update_fee.is_none(), true);
689 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
690 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
691 check_added_monitors!(nodes[0], 1);
692 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
694 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
695 check_added_monitors!(nodes[1], 1);
696 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
698 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
699 check_added_monitors!(nodes[1], 1);
700 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
701 // No commitment_signed so get_event_msg's assert(len == 1) passes
703 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
704 check_added_monitors!(nodes[0], 1);
705 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
707 expect_pending_htlcs_forwardable!(nodes[0]);
709 let events = nodes[0].node.get_and_clear_pending_events();
710 assert_eq!(events.len(), 1);
712 Event::PaymentReceived { .. } => { },
713 _ => panic!("Unexpected event"),
716 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
718 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
719 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
720 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
724 fn test_update_fee() {
725 let chanmon_cfgs = create_chanmon_cfgs(2);
726 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
727 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
728 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
729 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
730 let channel_id = chan.2;
733 // (1) update_fee/commitment_signed ->
734 // <- (2) revoke_and_ack
735 // .- send (3) commitment_signed
736 // (4) update_fee/commitment_signed ->
737 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
738 // <- (3) commitment_signed delivered
739 // send (6) revoke_and_ack -.
740 // <- (5) deliver revoke_and_ack
741 // (6) deliver revoke_and_ack ->
742 // .- send (7) commitment_signed in response to (4)
743 // <- (7) deliver commitment_signed
746 // Create and deliver (1)...
747 let feerate = get_feerate!(nodes[0], channel_id);
748 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
749 check_added_monitors!(nodes[0], 1);
751 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
752 assert_eq!(events_0.len(), 1);
753 let (update_msg, commitment_signed) = match events_0[0] {
754 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
755 (update_fee.as_ref(), commitment_signed)
757 _ => panic!("Unexpected event"),
759 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
761 // Generate (2) and (3):
762 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
763 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
764 check_added_monitors!(nodes[1], 1);
767 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
768 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
769 check_added_monitors!(nodes[0], 1);
771 // Create and deliver (4)...
772 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
773 check_added_monitors!(nodes[0], 1);
774 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
775 assert_eq!(events_0.len(), 1);
776 let (update_msg, commitment_signed) = match events_0[0] {
777 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
778 (update_fee.as_ref(), commitment_signed)
780 _ => panic!("Unexpected event"),
783 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
784 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
785 check_added_monitors!(nodes[1], 1);
787 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
788 // No commitment_signed so get_event_msg's assert(len == 1) passes
790 // Handle (3), creating (6):
791 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
792 check_added_monitors!(nodes[0], 1);
793 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
794 // No commitment_signed so get_event_msg's assert(len == 1) passes
797 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
798 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
799 check_added_monitors!(nodes[0], 1);
801 // Deliver (6), creating (7):
802 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
803 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
804 assert!(commitment_update.update_add_htlcs.is_empty());
805 assert!(commitment_update.update_fulfill_htlcs.is_empty());
806 assert!(commitment_update.update_fail_htlcs.is_empty());
807 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
808 assert!(commitment_update.update_fee.is_none());
809 check_added_monitors!(nodes[1], 1);
812 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
813 check_added_monitors!(nodes[0], 1);
814 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
815 // No commitment_signed so get_event_msg's assert(len == 1) passes
817 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
818 check_added_monitors!(nodes[1], 1);
819 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
821 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
822 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
823 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
827 fn pre_funding_lock_shutdown_test() {
828 // Test sending a shutdown prior to funding_locked after funding generation
829 let chanmon_cfgs = create_chanmon_cfgs(2);
830 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
831 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
832 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
833 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
834 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
835 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
836 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
838 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
839 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
840 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
841 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
842 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
844 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
845 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
846 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
847 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
848 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
849 assert!(node_0_none.is_none());
851 assert!(nodes[0].node.list_channels().is_empty());
852 assert!(nodes[1].node.list_channels().is_empty());
856 fn updates_shutdown_wait() {
857 // Test sending a shutdown with outstanding updates pending
858 let chanmon_cfgs = create_chanmon_cfgs(3);
859 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
860 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
861 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
862 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
863 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
864 let logger = test_utils::TestLogger::new();
866 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
868 nodes[0].node.close_channel(&chan_1.2).unwrap();
869 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
870 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
871 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
872 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
874 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
875 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
877 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
879 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
880 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
881 let route_1 = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler0.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
882 let route_2 = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler1.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
883 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
884 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
886 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
887 check_added_monitors!(nodes[2], 1);
888 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
889 assert!(updates.update_add_htlcs.is_empty());
890 assert!(updates.update_fail_htlcs.is_empty());
891 assert!(updates.update_fail_malformed_htlcs.is_empty());
892 assert!(updates.update_fee.is_none());
893 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
894 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
895 check_added_monitors!(nodes[1], 1);
896 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
897 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
899 assert!(updates_2.update_add_htlcs.is_empty());
900 assert!(updates_2.update_fail_htlcs.is_empty());
901 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
902 assert!(updates_2.update_fee.is_none());
903 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
904 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
905 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
907 let events = nodes[0].node.get_and_clear_pending_events();
908 assert_eq!(events.len(), 1);
910 Event::PaymentSent { ref payment_preimage } => {
911 assert_eq!(our_payment_preimage, *payment_preimage);
913 _ => panic!("Unexpected event"),
916 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
917 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
918 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
919 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
920 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
921 assert!(node_0_none.is_none());
923 assert!(nodes[0].node.list_channels().is_empty());
925 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
926 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
927 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
928 assert!(nodes[1].node.list_channels().is_empty());
929 assert!(nodes[2].node.list_channels().is_empty());
933 fn htlc_fail_async_shutdown() {
934 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
935 let chanmon_cfgs = create_chanmon_cfgs(3);
936 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
937 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
938 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
939 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
940 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
941 let logger = test_utils::TestLogger::new();
943 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
944 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
945 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
946 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
947 check_added_monitors!(nodes[0], 1);
948 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
949 assert_eq!(updates.update_add_htlcs.len(), 1);
950 assert!(updates.update_fulfill_htlcs.is_empty());
951 assert!(updates.update_fail_htlcs.is_empty());
952 assert!(updates.update_fail_malformed_htlcs.is_empty());
953 assert!(updates.update_fee.is_none());
955 nodes[1].node.close_channel(&chan_1.2).unwrap();
956 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
957 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
958 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
960 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
961 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
962 check_added_monitors!(nodes[1], 1);
963 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
964 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
966 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
967 assert!(updates_2.update_add_htlcs.is_empty());
968 assert!(updates_2.update_fulfill_htlcs.is_empty());
969 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
970 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
971 assert!(updates_2.update_fee.is_none());
973 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
974 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
976 expect_payment_failed!(nodes[0], our_payment_hash, false);
978 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
979 assert_eq!(msg_events.len(), 2);
980 let node_0_closing_signed = match msg_events[0] {
981 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
982 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
985 _ => panic!("Unexpected event"),
987 match msg_events[1] {
988 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
989 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
991 _ => panic!("Unexpected event"),
994 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
995 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
996 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
997 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
998 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
999 assert!(node_0_none.is_none());
1001 assert!(nodes[0].node.list_channels().is_empty());
1003 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1004 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1005 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1006 assert!(nodes[1].node.list_channels().is_empty());
1007 assert!(nodes[2].node.list_channels().is_empty());
1010 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1011 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1012 // messages delivered prior to disconnect
1013 let chanmon_cfgs = create_chanmon_cfgs(3);
1014 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1015 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1016 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1017 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1018 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1020 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1022 nodes[1].node.close_channel(&chan_1.2).unwrap();
1023 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1025 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1026 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1028 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1032 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1033 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1035 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1036 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1037 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1038 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1040 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1041 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1042 assert!(node_1_shutdown == node_1_2nd_shutdown);
1044 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1045 let node_0_2nd_shutdown = if recv_count > 0 {
1046 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1047 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1050 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1051 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1052 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1054 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1056 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1057 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1059 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1060 check_added_monitors!(nodes[2], 1);
1061 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1062 assert!(updates.update_add_htlcs.is_empty());
1063 assert!(updates.update_fail_htlcs.is_empty());
1064 assert!(updates.update_fail_malformed_htlcs.is_empty());
1065 assert!(updates.update_fee.is_none());
1066 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1067 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1068 check_added_monitors!(nodes[1], 1);
1069 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1070 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1072 assert!(updates_2.update_add_htlcs.is_empty());
1073 assert!(updates_2.update_fail_htlcs.is_empty());
1074 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1075 assert!(updates_2.update_fee.is_none());
1076 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1077 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1078 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1080 let events = nodes[0].node.get_and_clear_pending_events();
1081 assert_eq!(events.len(), 1);
1083 Event::PaymentSent { ref payment_preimage } => {
1084 assert_eq!(our_payment_preimage, *payment_preimage);
1086 _ => panic!("Unexpected event"),
1089 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1091 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1092 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1093 assert!(node_1_closing_signed.is_some());
1096 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1097 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1099 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1100 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1101 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1102 if recv_count == 0 {
1103 // If all closing_signeds weren't delivered we can just resume where we left off...
1104 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1106 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1107 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1108 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1110 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1111 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1112 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1114 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1115 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1117 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1118 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1119 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1121 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1122 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1123 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1124 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1125 assert!(node_0_none.is_none());
1127 // If one node, however, received + responded with an identical closing_signed we end
1128 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1129 // There isn't really anything better we can do simply, but in the future we might
1130 // explore storing a set of recently-closed channels that got disconnected during
1131 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1132 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1134 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1136 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1137 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1138 assert_eq!(msg_events.len(), 1);
1139 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1141 &ErrorAction::SendErrorMessage { ref msg } => {
1142 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1143 assert_eq!(msg.channel_id, chan_1.2);
1145 _ => panic!("Unexpected event!"),
1147 } else { panic!("Needed SendErrorMessage close"); }
1149 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1150 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1151 // closing_signed so we do it ourselves
1152 check_closed_broadcast!(nodes[0], false);
1153 check_added_monitors!(nodes[0], 1);
1156 assert!(nodes[0].node.list_channels().is_empty());
1158 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1159 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1160 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1161 assert!(nodes[1].node.list_channels().is_empty());
1162 assert!(nodes[2].node.list_channels().is_empty());
1166 fn test_shutdown_rebroadcast() {
1167 do_test_shutdown_rebroadcast(0);
1168 do_test_shutdown_rebroadcast(1);
1169 do_test_shutdown_rebroadcast(2);
1173 fn fake_network_test() {
1174 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1175 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1176 let chanmon_cfgs = create_chanmon_cfgs(4);
1177 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1178 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1179 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1181 // Create some initial channels
1182 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1183 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1184 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1186 // Rebalance the network a bit by relaying one payment through all the channels...
1187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1189 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1190 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1192 // Send some more payments
1193 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1194 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1195 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1197 // Test failure packets
1198 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1199 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1201 // Add a new channel that skips 3
1202 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1204 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1205 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1206 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1209 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1210 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1212 // Do some rebalance loop payments, simultaneously
1213 let mut hops = Vec::with_capacity(3);
1214 hops.push(RouteHop {
1215 pubkey: nodes[2].node.get_our_node_id(),
1216 node_features: NodeFeatures::empty(),
1217 short_channel_id: chan_2.0.contents.short_channel_id,
1218 channel_features: ChannelFeatures::empty(),
1220 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1222 hops.push(RouteHop {
1223 pubkey: nodes[3].node.get_our_node_id(),
1224 node_features: NodeFeatures::empty(),
1225 short_channel_id: chan_3.0.contents.short_channel_id,
1226 channel_features: ChannelFeatures::empty(),
1228 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1230 hops.push(RouteHop {
1231 pubkey: nodes[1].node.get_our_node_id(),
1232 node_features: NodeFeatures::empty(),
1233 short_channel_id: chan_4.0.contents.short_channel_id,
1234 channel_features: ChannelFeatures::empty(),
1236 cltv_expiry_delta: TEST_FINAL_CLTV,
1238 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1239 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1240 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1242 let mut hops = Vec::with_capacity(3);
1243 hops.push(RouteHop {
1244 pubkey: nodes[3].node.get_our_node_id(),
1245 node_features: NodeFeatures::empty(),
1246 short_channel_id: chan_4.0.contents.short_channel_id,
1247 channel_features: ChannelFeatures::empty(),
1249 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1251 hops.push(RouteHop {
1252 pubkey: nodes[2].node.get_our_node_id(),
1253 node_features: NodeFeatures::empty(),
1254 short_channel_id: chan_3.0.contents.short_channel_id,
1255 channel_features: ChannelFeatures::empty(),
1257 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1259 hops.push(RouteHop {
1260 pubkey: nodes[1].node.get_our_node_id(),
1261 node_features: NodeFeatures::empty(),
1262 short_channel_id: chan_2.0.contents.short_channel_id,
1263 channel_features: ChannelFeatures::empty(),
1265 cltv_expiry_delta: TEST_FINAL_CLTV,
1267 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1268 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1269 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1271 // Claim the rebalances...
1272 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1273 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1275 // Add a duplicate new channel from 2 to 4
1276 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1278 // Send some payments across both channels
1279 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1281 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1284 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1285 let events = nodes[0].node.get_and_clear_pending_msg_events();
1286 assert_eq!(events.len(), 0);
1287 nodes[0].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap(), 1);
1289 //TODO: Test that routes work again here as we've been notified that the channel is full
1291 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1292 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1293 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1295 // Close down the channels...
1296 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1297 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1298 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1299 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1300 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1304 fn holding_cell_htlc_counting() {
1305 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1306 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1307 // commitment dance rounds.
1308 let chanmon_cfgs = create_chanmon_cfgs(3);
1309 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1310 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1311 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1312 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1313 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1314 let logger = test_utils::TestLogger::new();
1316 let mut payments = Vec::new();
1317 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1318 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1319 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1320 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1321 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1322 payments.push((payment_preimage, payment_hash));
1324 check_added_monitors!(nodes[1], 1);
1326 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1327 assert_eq!(events.len(), 1);
1328 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1329 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1331 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1332 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1334 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1336 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1337 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1338 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1339 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1340 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1341 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1344 // This should also be true if we try to forward a payment.
1345 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1347 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1348 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1349 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1350 check_added_monitors!(nodes[0], 1);
1353 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1354 assert_eq!(events.len(), 1);
1355 let payment_event = SendEvent::from_event(events.pop().unwrap());
1356 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1359 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1360 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1361 // fails), the second will process the resulting failure and fail the HTLC backward.
1362 expect_pending_htlcs_forwardable!(nodes[1]);
1363 expect_pending_htlcs_forwardable!(nodes[1]);
1364 check_added_monitors!(nodes[1], 1);
1366 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1367 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1368 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1370 let events = nodes[0].node.get_and_clear_pending_msg_events();
1371 assert_eq!(events.len(), 1);
1373 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1374 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1376 _ => panic!("Unexpected event"),
1379 expect_payment_failed!(nodes[0], payment_hash_2, false);
1381 // Now forward all the pending HTLCs and claim them back
1382 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1383 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1384 check_added_monitors!(nodes[2], 1);
1386 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1387 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1388 check_added_monitors!(nodes[1], 1);
1389 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1391 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1392 check_added_monitors!(nodes[1], 1);
1393 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1395 for ref update in as_updates.update_add_htlcs.iter() {
1396 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1398 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1399 check_added_monitors!(nodes[2], 1);
1400 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1401 check_added_monitors!(nodes[2], 1);
1402 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1404 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1405 check_added_monitors!(nodes[1], 1);
1406 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1407 check_added_monitors!(nodes[1], 1);
1408 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1410 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1411 check_added_monitors!(nodes[2], 1);
1413 expect_pending_htlcs_forwardable!(nodes[2]);
1415 let events = nodes[2].node.get_and_clear_pending_events();
1416 assert_eq!(events.len(), payments.len());
1417 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1419 &Event::PaymentReceived { ref payment_hash, .. } => {
1420 assert_eq!(*payment_hash, *hash);
1422 _ => panic!("Unexpected event"),
1426 for (preimage, _) in payments.drain(..) {
1427 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1430 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1434 fn duplicate_htlc_test() {
1435 // Test that we accept duplicate payment_hash HTLCs across the network and that
1436 // claiming/failing them are all separate and don't affect each other
1437 let chanmon_cfgs = create_chanmon_cfgs(6);
1438 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1439 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1440 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1442 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1443 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1444 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1445 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1446 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1447 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1449 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1451 *nodes[0].network_payment_count.borrow_mut() -= 1;
1452 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1454 *nodes[0].network_payment_count.borrow_mut() -= 1;
1455 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1457 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1458 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1459 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1463 fn test_duplicate_htlc_different_direction_onchain() {
1464 // Test that ChannelMonitor doesn't generate 2 preimage txn
1465 // when we have 2 HTLCs with same preimage that go across a node
1466 // in opposite directions.
1467 let chanmon_cfgs = create_chanmon_cfgs(2);
1468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1470 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1473 let logger = test_utils::TestLogger::new();
1476 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1478 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1480 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1481 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1482 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1484 // Provide preimage to node 0 by claiming payment
1485 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1486 check_added_monitors!(nodes[0], 1);
1488 // Broadcast node 1 commitment txn
1489 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1491 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1492 let mut has_both_htlcs = 0; // check htlcs match ones committed
1493 for outp in remote_txn[0].output.iter() {
1494 if outp.value == 800_000 / 1000 {
1495 has_both_htlcs += 1;
1496 } else if outp.value == 900_000 / 1000 {
1497 has_both_htlcs += 1;
1500 assert_eq!(has_both_htlcs, 2);
1502 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1503 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1504 check_added_monitors!(nodes[0], 1);
1506 // Check we only broadcast 1 timeout tx
1507 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1508 let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1509 assert_eq!(claim_txn.len(), 5);
1510 check_spends!(claim_txn[2], chan_1.3);
1511 check_spends!(claim_txn[3], claim_txn[2]);
1512 assert_eq!(htlc_pair.0.input.len(), 1);
1513 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1514 check_spends!(htlc_pair.0, remote_txn[0]);
1515 assert_eq!(htlc_pair.1.input.len(), 1);
1516 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1517 check_spends!(htlc_pair.1, remote_txn[0]);
1519 let events = nodes[0].node.get_and_clear_pending_msg_events();
1520 assert_eq!(events.len(), 2);
1523 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1524 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1525 assert!(update_add_htlcs.is_empty());
1526 assert!(update_fail_htlcs.is_empty());
1527 assert_eq!(update_fulfill_htlcs.len(), 1);
1528 assert!(update_fail_malformed_htlcs.is_empty());
1529 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1531 _ => panic!("Unexpected event"),
1537 fn test_basic_channel_reserve() {
1538 let chanmon_cfgs = create_chanmon_cfgs(2);
1539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1541 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1542 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1543 let logger = test_utils::TestLogger::new();
1545 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1546 let channel_reserve = chan_stat.channel_reserve_msat;
1548 // The 2* and +1 are for the fee spike reserve.
1549 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1550 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1551 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1552 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1553 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), max_can_send + 1, TEST_FINAL_CLTV, &logger).unwrap();
1554 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1556 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1558 &APIError::ChannelUnavailable{ref err} =>
1559 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1560 _ => panic!("Unexpected error variant"),
1563 _ => panic!("Unexpected error variant"),
1565 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1566 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1568 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1572 fn test_fee_spike_violation_fails_htlc() {
1573 let chanmon_cfgs = create_chanmon_cfgs(2);
1574 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1575 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1576 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1577 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1578 let logger = test_utils::TestLogger::new();
1580 macro_rules! get_route_and_payment_hash {
1581 ($recv_value: expr) => {{
1582 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1583 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1584 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1585 (route, payment_hash, payment_preimage)
1589 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1590 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1591 let secp_ctx = Secp256k1::new();
1592 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1594 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1596 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1597 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1598 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1599 let msg = msgs::UpdateAddHTLC {
1602 amount_msat: htlc_msat,
1603 payment_hash: payment_hash,
1604 cltv_expiry: htlc_cltv,
1605 onion_routing_packet: onion_packet,
1608 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1610 // Now manually create the commitment_signed message corresponding to the update_add
1611 // nodes[0] just sent. In the code for construction of this message, "local" refers
1612 // to the sender of the message, and "remote" refers to the receiver.
1614 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1616 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1618 // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1619 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1620 let (local_revocation_basepoint, local_htlc_basepoint, local_payment_point, local_secret, local_secret2) = {
1621 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1622 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1623 let chan_keys = local_chan.get_keys();
1624 let pubkeys = chan_keys.pubkeys();
1625 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1626 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER), chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2))
1628 let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_payment_point, remote_secret1) = {
1629 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
1630 let remote_chan = chan_lock.by_id.get(&chan.2).unwrap();
1631 let chan_keys = remote_chan.get_keys();
1632 let pubkeys = chan_keys.pubkeys();
1633 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint, pubkeys.payment_point,
1634 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1))
1637 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1638 let commitment_secret = SecretKey::from_slice(&remote_secret1).unwrap();
1639 let per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &commitment_secret);
1640 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &per_commitment_point, &remote_delayed_payment_basepoint,
1641 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1643 // Build the remote commitment transaction so we can sign it, and then later use the
1644 // signature for the commitment_signed message.
1645 let local_chan_balance = 1313;
1646 let static_payment_pk = local_payment_point.serialize();
1647 let remote_commit_tx_output = TxOut {
1648 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_PUSHBYTES_0)
1649 .push_slice(&WPubkeyHash::hash(&static_payment_pk)[..])
1651 value: local_chan_balance as u64
1654 let local_commit_tx_output = TxOut {
1655 script_pubkey: chan_utils::get_revokeable_redeemscript(&commit_tx_keys.revocation_key,
1657 &commit_tx_keys.broadcaster_delayed_payment_key).to_v0_p2wsh(),
1661 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1663 amount_msat: 3460001,
1664 cltv_expiry: htlc_cltv,
1665 payment_hash: payment_hash,
1666 transaction_output_index: Some(1),
1669 let htlc_output = TxOut {
1670 script_pubkey: chan_utils::get_htlc_redeemscript(&accepted_htlc_info, &commit_tx_keys).to_v0_p2wsh(),
1671 value: 3460001 / 1000
1674 let commit_tx_obscure_factor = {
1675 let mut sha = Sha256::engine();
1676 let remote_payment_point = &remote_payment_point.serialize();
1677 sha.input(&local_payment_point.serialize());
1678 sha.input(remote_payment_point);
1679 let res = Sha256::from_engine(sha).into_inner();
1681 ((res[26] as u64) << 5*8) |
1682 ((res[27] as u64) << 4*8) |
1683 ((res[28] as u64) << 3*8) |
1684 ((res[29] as u64) << 2*8) |
1685 ((res[30] as u64) << 1*8) |
1686 ((res[31] as u64) << 0*8)
1688 let commitment_number = 1;
1689 let obscured_commitment_transaction_number = commit_tx_obscure_factor ^ commitment_number;
1690 let lock_time = ((0x20 as u32) << 8*3) | ((obscured_commitment_transaction_number & 0xffffffu64) as u32);
1692 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
1693 script_sig: Script::new(),
1694 sequence: ((0x80 as u32) << 8*3) | ((obscured_commitment_transaction_number >> 3*8) as u32),
1695 witness: Vec::new(),
1698 let commit_tx = Transaction {
1702 output: vec![remote_commit_tx_output, htlc_output, local_commit_tx_output],
1705 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1706 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1707 let local_chan_keys = local_chan.get_keys();
1708 let pre_commit_tx_keys = PreCalculatedTxCreationKeys::new(commit_tx_keys);
1709 local_chan_keys.sign_counterparty_commitment(feerate_per_kw, &commit_tx, &pre_commit_tx_keys, &[&accepted_htlc_info], &secp_ctx).unwrap()
1712 let commit_signed_msg = msgs::CommitmentSigned {
1715 htlc_signatures: res.1
1718 // Send the commitment_signed message to the nodes[1].
1719 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1720 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1722 // Send the RAA to nodes[1].
1723 let per_commitment_secret = local_secret;
1724 let next_secret = SecretKey::from_slice(&local_secret2).unwrap();
1725 let next_per_commitment_point = PublicKey::from_secret_key(&secp_ctx, &next_secret);
1726 let raa_msg = msgs::RevokeAndACK{ channel_id: chan.2, per_commitment_secret, next_per_commitment_point};
1727 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1729 let events = nodes[1].node.get_and_clear_pending_msg_events();
1730 assert_eq!(events.len(), 1);
1731 // Make sure the HTLC failed in the way we expect.
1733 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1734 assert_eq!(update_fail_htlcs.len(), 1);
1735 update_fail_htlcs[0].clone()
1737 _ => panic!("Unexpected event"),
1739 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1741 check_added_monitors!(nodes[1], 2);
1745 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1746 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1747 // Set the fee rate for the channel very high, to the point where the fundee
1748 // sending any amount would result in a channel reserve violation. In this test
1749 // we check that we would be prevented from sending an HTLC in this situation.
1750 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1751 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1752 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1753 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1754 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1755 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1756 let logger = test_utils::TestLogger::new();
1758 macro_rules! get_route_and_payment_hash {
1759 ($recv_value: expr) => {{
1760 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1761 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1762 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1763 (route, payment_hash, payment_preimage)
1767 let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1768 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1769 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1771 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put counterparty balance under holder-announced channel reserve value".to_string(), 1);
1775 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1776 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1777 // Set the fee rate for the channel very high, to the point where the funder
1778 // receiving 1 update_add_htlc would result in them closing the channel due
1779 // to channel reserve violation. This close could also happen if the fee went
1780 // up a more realistic amount, but many HTLCs were outstanding at the time of
1781 // the update_add_htlc.
1782 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1783 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1786 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1787 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1788 let logger = test_utils::TestLogger::new();
1790 macro_rules! get_route_and_payment_hash {
1791 ($recv_value: expr) => {{
1792 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1793 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1794 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.first().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1795 (route, payment_hash, payment_preimage)
1799 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1800 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1801 let secp_ctx = Secp256k1::new();
1802 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1803 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1804 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1805 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1806 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1807 let msg = msgs::UpdateAddHTLC {
1810 amount_msat: htlc_msat + 1,
1811 payment_hash: payment_hash,
1812 cltv_expiry: htlc_cltv,
1813 onion_routing_packet: onion_packet,
1816 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1817 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1818 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string(), 1);
1819 assert_eq!(nodes[0].node.list_channels().len(), 0);
1820 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1821 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1822 check_added_monitors!(nodes[0], 1);
1826 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1827 let chanmon_cfgs = create_chanmon_cfgs(3);
1828 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1829 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1830 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1831 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1832 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1833 let logger = test_utils::TestLogger::new();
1835 macro_rules! get_route_and_payment_hash {
1836 ($recv_value: expr) => {{
1837 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1838 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1839 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1840 (route, payment_hash, payment_preimage)
1845 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1846 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1847 let feerate = get_feerate!(nodes[0], chan.2);
1849 // Add a 2* and +1 for the fee spike reserve.
1850 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1851 let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1852 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1854 // Add a pending HTLC.
1855 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1856 let payment_event_1 = {
1857 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1858 check_added_monitors!(nodes[0], 1);
1860 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1861 assert_eq!(events.len(), 1);
1862 SendEvent::from_event(events.remove(0))
1864 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1866 // Attempt to trigger a channel reserve violation --> payment failure.
1867 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1868 let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1869 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1870 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1872 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1873 let secp_ctx = Secp256k1::new();
1874 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1875 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1876 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1877 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1878 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1879 let msg = msgs::UpdateAddHTLC {
1882 amount_msat: htlc_msat + 1,
1883 payment_hash: our_payment_hash_1,
1884 cltv_expiry: htlc_cltv,
1885 onion_routing_packet: onion_packet,
1888 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1889 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1890 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1891 assert_eq!(nodes[1].node.list_channels().len(), 1);
1892 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1893 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1894 check_added_monitors!(nodes[1], 1);
1898 fn test_inbound_outbound_capacity_is_not_zero() {
1899 let chanmon_cfgs = create_chanmon_cfgs(2);
1900 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1901 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1902 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1903 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1904 let channels0 = node_chanmgrs[0].list_channels();
1905 let channels1 = node_chanmgrs[1].list_channels();
1906 assert_eq!(channels0.len(), 1);
1907 assert_eq!(channels1.len(), 1);
1909 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1910 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1912 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1913 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1916 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1917 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1921 fn test_channel_reserve_holding_cell_htlcs() {
1922 let chanmon_cfgs = create_chanmon_cfgs(3);
1923 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1924 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1925 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1926 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1927 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1928 let logger = test_utils::TestLogger::new();
1930 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1931 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1933 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1934 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1936 macro_rules! get_route_and_payment_hash {
1937 ($recv_value: expr) => {{
1938 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1939 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1940 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1941 (route, payment_hash, payment_preimage)
1945 macro_rules! expect_forward {
1947 let mut events = $node.node.get_and_clear_pending_msg_events();
1948 assert_eq!(events.len(), 1);
1949 check_added_monitors!($node, 1);
1950 let payment_event = SendEvent::from_event(events.remove(0));
1955 let feemsat = 239; // somehow we know?
1956 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1957 let feerate = get_feerate!(nodes[0], chan_1.2);
1959 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1961 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1963 let (mut route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0);
1964 route.paths[0].last_mut().unwrap().fee_msat += 1;
1965 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1966 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1967 assert!(regex::Regex::new(r"Cannot send value that would put us over the max HTLC value in flight our peer will accept \(\d+\)").unwrap().is_match(err)));
1968 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1969 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1972 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1973 // nodes[0]'s wealth
1975 let amt_msat = recv_value_0 + total_fee_msat;
1976 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1977 // Also, ensure that each payment has enough to be over the dust limit to
1978 // ensure it'll be included in each commit tx fee calculation.
1979 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1980 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1981 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1984 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1986 let (stat01_, stat11_, stat12_, stat22_) = (
1987 get_channel_value_stat!(nodes[0], chan_1.2),
1988 get_channel_value_stat!(nodes[1], chan_1.2),
1989 get_channel_value_stat!(nodes[1], chan_2.2),
1990 get_channel_value_stat!(nodes[2], chan_2.2),
1993 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1994 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1995 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1996 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1997 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
2000 // adding pending output.
2001 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
2002 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
2003 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
2004 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
2005 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
2006 // cases where 1 msat over X amount will cause a payment failure, but anything less than
2007 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
2008 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
2009 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
2011 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
2012 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
2013 let amt_msat_1 = recv_value_1 + total_fee_msat;
2015 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
2016 let payment_event_1 = {
2017 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
2018 check_added_monitors!(nodes[0], 1);
2020 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2021 assert_eq!(events.len(), 1);
2022 SendEvent::from_event(events.remove(0))
2024 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
2026 // channel reserve test with htlc pending output > 0
2027 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
2029 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
2030 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2031 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2032 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2035 // split the rest to test holding cell
2036 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
2037 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
2038 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
2039 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2041 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2042 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
2045 // now see if they go through on both sides
2046 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2047 // but this will stuck in the holding cell
2048 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2049 check_added_monitors!(nodes[0], 0);
2050 let events = nodes[0].node.get_and_clear_pending_events();
2051 assert_eq!(events.len(), 0);
2053 // test with outbound holding cell amount > 0
2055 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2056 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2057 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2058 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2059 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 2);
2062 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2063 // this will also stuck in the holding cell
2064 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2065 check_added_monitors!(nodes[0], 0);
2066 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2067 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2069 // flush the pending htlc
2070 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2071 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2072 check_added_monitors!(nodes[1], 1);
2074 // the pending htlc should be promoted to committed
2075 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2076 check_added_monitors!(nodes[0], 1);
2077 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2079 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2080 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2081 // No commitment_signed so get_event_msg's assert(len == 1) passes
2082 check_added_monitors!(nodes[0], 1);
2084 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2085 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2086 check_added_monitors!(nodes[1], 1);
2088 expect_pending_htlcs_forwardable!(nodes[1]);
2090 let ref payment_event_11 = expect_forward!(nodes[1]);
2091 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2092 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2094 expect_pending_htlcs_forwardable!(nodes[2]);
2095 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2097 // flush the htlcs in the holding cell
2098 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2099 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2100 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2101 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2102 expect_pending_htlcs_forwardable!(nodes[1]);
2104 let ref payment_event_3 = expect_forward!(nodes[1]);
2105 assert_eq!(payment_event_3.msgs.len(), 2);
2106 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2107 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2109 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2110 expect_pending_htlcs_forwardable!(nodes[2]);
2112 let events = nodes[2].node.get_and_clear_pending_events();
2113 assert_eq!(events.len(), 2);
2115 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2116 assert_eq!(our_payment_hash_21, *payment_hash);
2117 assert_eq!(*payment_secret, None);
2118 assert_eq!(recv_value_21, amt);
2120 _ => panic!("Unexpected event"),
2123 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2124 assert_eq!(our_payment_hash_22, *payment_hash);
2125 assert_eq!(None, *payment_secret);
2126 assert_eq!(recv_value_22, amt);
2128 _ => panic!("Unexpected event"),
2131 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2132 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2133 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2135 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2136 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2138 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2139 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2141 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2143 &APIError::ChannelUnavailable{ref err} =>
2144 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2145 _ => panic!("Unexpected error variant"),
2148 _ => panic!("Unexpected error variant"),
2150 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2151 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send value that would put our balance under counterparty-announced channel reserve value".to_string(), 3);
2154 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2156 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2157 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2158 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2159 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2160 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2162 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2163 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2167 fn channel_reserve_in_flight_removes() {
2168 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2169 // can send to its counterparty, but due to update ordering, the other side may not yet have
2170 // considered those HTLCs fully removed.
2171 // This tests that we don't count HTLCs which will not be included in the next remote
2172 // commitment transaction towards the reserve value (as it implies no commitment transaction
2173 // will be generated which violates the remote reserve value).
2174 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2176 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2177 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2178 // you only consider the value of the first HTLC, it may not),
2179 // * start routing a third HTLC from A to B,
2180 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2181 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2182 // * deliver the first fulfill from B
2183 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2185 // * deliver A's response CS and RAA.
2186 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2187 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2188 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2189 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2190 let chanmon_cfgs = create_chanmon_cfgs(2);
2191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2193 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2194 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2195 let logger = test_utils::TestLogger::new();
2197 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2198 // Route the first two HTLCs.
2199 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2200 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2202 // Start routing the third HTLC (this is just used to get everyone in the right state).
2203 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2205 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2206 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
2207 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2208 check_added_monitors!(nodes[0], 1);
2209 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2210 assert_eq!(events.len(), 1);
2211 SendEvent::from_event(events.remove(0))
2214 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2215 // initial fulfill/CS.
2216 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2217 check_added_monitors!(nodes[1], 1);
2218 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2220 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2221 // remove the second HTLC when we send the HTLC back from B to A.
2222 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2223 check_added_monitors!(nodes[1], 1);
2224 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2226 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2227 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2228 check_added_monitors!(nodes[0], 1);
2229 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2230 expect_payment_sent!(nodes[0], payment_preimage_1);
2232 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2233 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2234 check_added_monitors!(nodes[1], 1);
2235 // B is already AwaitingRAA, so cant generate a CS here
2236 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2238 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2239 check_added_monitors!(nodes[1], 1);
2240 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2242 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2243 check_added_monitors!(nodes[0], 1);
2244 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2246 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2247 check_added_monitors!(nodes[1], 1);
2248 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2250 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2251 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2252 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2253 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2254 // on-chain as necessary).
2255 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2256 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2257 check_added_monitors!(nodes[0], 1);
2258 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2259 expect_payment_sent!(nodes[0], payment_preimage_2);
2261 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2262 check_added_monitors!(nodes[1], 1);
2263 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2265 expect_pending_htlcs_forwardable!(nodes[1]);
2266 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2268 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2269 // resolve the second HTLC from A's point of view.
2270 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2271 check_added_monitors!(nodes[0], 1);
2272 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2274 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2275 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2276 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2278 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2279 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
2280 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2281 check_added_monitors!(nodes[1], 1);
2282 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2283 assert_eq!(events.len(), 1);
2284 SendEvent::from_event(events.remove(0))
2287 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2288 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2289 check_added_monitors!(nodes[0], 1);
2290 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2292 // Now just resolve all the outstanding messages/HTLCs for completeness...
2294 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2295 check_added_monitors!(nodes[1], 1);
2296 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2298 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2299 check_added_monitors!(nodes[1], 1);
2301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2302 check_added_monitors!(nodes[0], 1);
2303 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2305 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2306 check_added_monitors!(nodes[1], 1);
2307 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2309 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2310 check_added_monitors!(nodes[0], 1);
2312 expect_pending_htlcs_forwardable!(nodes[0]);
2313 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2315 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2316 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2320 fn channel_monitor_network_test() {
2321 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2322 // tests that ChannelMonitor is able to recover from various states.
2323 let chanmon_cfgs = create_chanmon_cfgs(5);
2324 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2325 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2326 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2328 // Create some initial channels
2329 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2330 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2331 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2332 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2334 // Rebalance the network a bit by relaying one payment through all the channels...
2335 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2336 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2337 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2338 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2340 // Simple case with no pending HTLCs:
2341 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2342 check_added_monitors!(nodes[1], 1);
2344 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2345 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2346 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2347 check_added_monitors!(nodes[0], 1);
2348 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2350 get_announce_close_broadcast_events(&nodes, 0, 1);
2351 assert_eq!(nodes[0].node.list_channels().len(), 0);
2352 assert_eq!(nodes[1].node.list_channels().len(), 1);
2354 // One pending HTLC is discarded by the force-close:
2355 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2357 // Simple case of one pending HTLC to HTLC-Timeout
2358 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2359 check_added_monitors!(nodes[1], 1);
2361 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2362 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2363 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2364 check_added_monitors!(nodes[2], 1);
2365 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2367 get_announce_close_broadcast_events(&nodes, 1, 2);
2368 assert_eq!(nodes[1].node.list_channels().len(), 0);
2369 assert_eq!(nodes[2].node.list_channels().len(), 1);
2371 macro_rules! claim_funds {
2372 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2374 assert!($node.node.claim_funds($preimage, &None, $amount));
2375 check_added_monitors!($node, 1);
2377 let events = $node.node.get_and_clear_pending_msg_events();
2378 assert_eq!(events.len(), 1);
2380 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2381 assert!(update_add_htlcs.is_empty());
2382 assert!(update_fail_htlcs.is_empty());
2383 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2385 _ => panic!("Unexpected event"),
2391 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2392 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2393 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2394 check_added_monitors!(nodes[2], 1);
2395 let node2_commitment_txid;
2397 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2398 node2_commitment_txid = node_txn[0].txid();
2400 // Claim the payment on nodes[3], giving it knowledge of the preimage
2401 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2403 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2404 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2405 check_added_monitors!(nodes[3], 1);
2407 check_preimage_claim(&nodes[3], &node_txn);
2409 get_announce_close_broadcast_events(&nodes, 2, 3);
2410 assert_eq!(nodes[2].node.list_channels().len(), 0);
2411 assert_eq!(nodes[3].node.list_channels().len(), 1);
2413 { // Cheat and reset nodes[4]'s height to 1
2414 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2415 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2418 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2419 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2420 // One pending HTLC to time out:
2421 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2422 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2425 let (close_chan_update_1, close_chan_update_2) = {
2426 let mut block = Block {
2427 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2430 connect_block(&nodes[3], &block, 2);
2431 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2433 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2436 connect_block(&nodes[3], &block, i);
2438 let events = nodes[3].node.get_and_clear_pending_msg_events();
2439 assert_eq!(events.len(), 1);
2440 let close_chan_update_1 = match events[0] {
2441 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2444 _ => panic!("Unexpected event"),
2446 check_added_monitors!(nodes[3], 1);
2448 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2450 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2451 node_txn.retain(|tx| {
2452 if tx.input[0].previous_output.txid == node2_commitment_txid {
2458 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2460 // Claim the payment on nodes[4], giving it knowledge of the preimage
2461 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2464 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2468 connect_block(&nodes[4], &block, 2);
2469 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2471 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2474 connect_block(&nodes[4], &block, i);
2476 let events = nodes[4].node.get_and_clear_pending_msg_events();
2477 assert_eq!(events.len(), 1);
2478 let close_chan_update_2 = match events[0] {
2479 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2482 _ => panic!("Unexpected event"),
2484 check_added_monitors!(nodes[4], 1);
2485 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2488 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2489 txdata: vec![node_txn[0].clone()],
2491 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2493 check_preimage_claim(&nodes[4], &node_txn);
2494 (close_chan_update_1, close_chan_update_2)
2496 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2497 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2498 assert_eq!(nodes[3].node.list_channels().len(), 0);
2499 assert_eq!(nodes[4].node.list_channels().len(), 0);
2503 fn test_justice_tx() {
2504 // Test justice txn built on revoked HTLC-Success tx, against both sides
2505 let mut alice_config = UserConfig::default();
2506 alice_config.channel_options.announced_channel = true;
2507 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2508 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2509 let mut bob_config = UserConfig::default();
2510 bob_config.channel_options.announced_channel = true;
2511 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2512 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2513 let user_cfgs = [Some(alice_config), Some(bob_config)];
2514 let chanmon_cfgs = create_chanmon_cfgs(2);
2515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2518 // Create some new channels:
2519 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2521 // A pending HTLC which will be revoked:
2522 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2523 // Get the will-be-revoked local txn from nodes[0]
2524 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2525 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2526 assert_eq!(revoked_local_txn[0].input.len(), 1);
2527 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2528 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2529 assert_eq!(revoked_local_txn[1].input.len(), 1);
2530 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2531 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2532 // Revoke the old state
2533 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2536 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2537 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2539 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2540 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2541 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2543 check_spends!(node_txn[0], revoked_local_txn[0]);
2544 node_txn.swap_remove(0);
2545 node_txn.truncate(1);
2547 check_added_monitors!(nodes[1], 1);
2548 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2550 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2551 // Verify broadcast of revoked HTLC-timeout
2552 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2553 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2554 check_added_monitors!(nodes[0], 1);
2555 // Broadcast revoked HTLC-timeout on node 1
2556 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2557 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2559 get_announce_close_broadcast_events(&nodes, 0, 1);
2561 assert_eq!(nodes[0].node.list_channels().len(), 0);
2562 assert_eq!(nodes[1].node.list_channels().len(), 0);
2564 // We test justice_tx build by A on B's revoked HTLC-Success tx
2565 // Create some new channels:
2566 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2568 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2572 // A pending HTLC which will be revoked:
2573 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2574 // Get the will-be-revoked local txn from B
2575 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2576 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2577 assert_eq!(revoked_local_txn[0].input.len(), 1);
2578 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2579 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2580 // Revoke the old state
2581 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2583 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2584 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2586 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2587 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2588 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2590 check_spends!(node_txn[0], revoked_local_txn[0]);
2591 node_txn.swap_remove(0);
2593 check_added_monitors!(nodes[0], 1);
2594 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2596 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2597 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2598 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2599 check_added_monitors!(nodes[1], 1);
2600 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2601 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2603 get_announce_close_broadcast_events(&nodes, 0, 1);
2604 assert_eq!(nodes[0].node.list_channels().len(), 0);
2605 assert_eq!(nodes[1].node.list_channels().len(), 0);
2609 fn revoked_output_claim() {
2610 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2611 // transaction is broadcast by its counterparty
2612 let chanmon_cfgs = create_chanmon_cfgs(2);
2613 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2614 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2615 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2616 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2617 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2618 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2619 assert_eq!(revoked_local_txn.len(), 1);
2620 // Only output is the full channel value back to nodes[0]:
2621 assert_eq!(revoked_local_txn[0].output.len(), 1);
2622 // Send a payment through, updating everyone's latest commitment txn
2623 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2625 // Inform nodes[1] that nodes[0] broadcast a stale tx
2626 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2627 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2628 check_added_monitors!(nodes[1], 1);
2629 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2630 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2632 check_spends!(node_txn[0], revoked_local_txn[0]);
2633 check_spends!(node_txn[1], chan_1.3);
2635 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2636 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2637 get_announce_close_broadcast_events(&nodes, 0, 1);
2638 check_added_monitors!(nodes[0], 1)
2642 fn claim_htlc_outputs_shared_tx() {
2643 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2644 let chanmon_cfgs = create_chanmon_cfgs(2);
2645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2649 // Create some new channel:
2650 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2652 // Rebalance the network to generate htlc in the two directions
2653 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2654 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2655 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2656 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2658 // Get the will-be-revoked local txn from node[0]
2659 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2660 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2661 assert_eq!(revoked_local_txn[0].input.len(), 1);
2662 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2663 assert_eq!(revoked_local_txn[1].input.len(), 1);
2664 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2665 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2666 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2668 //Revoke the old state
2669 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2672 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2673 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2674 check_added_monitors!(nodes[0], 1);
2675 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2676 check_added_monitors!(nodes[1], 1);
2677 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2678 expect_payment_failed!(nodes[1], payment_hash_2, true);
2680 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2681 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2683 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2684 check_spends!(node_txn[0], revoked_local_txn[0]);
2686 let mut witness_lens = BTreeSet::new();
2687 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2688 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2689 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2690 assert_eq!(witness_lens.len(), 3);
2691 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2692 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2693 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2695 // Next nodes[1] broadcasts its current local tx state:
2696 assert_eq!(node_txn[1].input.len(), 1);
2697 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2699 assert_eq!(node_txn[2].input.len(), 1);
2700 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2701 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2702 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2703 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2704 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2706 get_announce_close_broadcast_events(&nodes, 0, 1);
2707 assert_eq!(nodes[0].node.list_channels().len(), 0);
2708 assert_eq!(nodes[1].node.list_channels().len(), 0);
2712 fn claim_htlc_outputs_single_tx() {
2713 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2714 let chanmon_cfgs = create_chanmon_cfgs(2);
2715 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2716 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2717 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2719 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2721 // Rebalance the network to generate htlc in the two directions
2722 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2723 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2724 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2725 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2726 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2728 // Get the will-be-revoked local txn from node[0]
2729 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2731 //Revoke the old state
2732 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2735 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2736 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2737 check_added_monitors!(nodes[0], 1);
2738 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2739 check_added_monitors!(nodes[1], 1);
2740 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2742 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2743 expect_payment_failed!(nodes[1], payment_hash_2, true);
2745 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2746 assert_eq!(node_txn.len(), 9);
2747 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2748 // ChannelManager: local commmitment + local HTLC-timeout (2)
2749 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2750 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2752 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2753 assert_eq!(node_txn[2].input.len(), 1);
2754 check_spends!(node_txn[2], chan_1.3);
2755 assert_eq!(node_txn[3].input.len(), 1);
2756 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2757 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2758 check_spends!(node_txn[3], node_txn[2]);
2760 // Justice transactions are indices 1-2-4
2761 assert_eq!(node_txn[0].input.len(), 1);
2762 assert_eq!(node_txn[1].input.len(), 1);
2763 assert_eq!(node_txn[4].input.len(), 1);
2765 check_spends!(node_txn[0], revoked_local_txn[0]);
2766 check_spends!(node_txn[1], revoked_local_txn[0]);
2767 check_spends!(node_txn[4], revoked_local_txn[0]);
2769 let mut witness_lens = BTreeSet::new();
2770 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2771 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2772 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2773 assert_eq!(witness_lens.len(), 3);
2774 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2775 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2776 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2778 get_announce_close_broadcast_events(&nodes, 0, 1);
2779 assert_eq!(nodes[0].node.list_channels().len(), 0);
2780 assert_eq!(nodes[1].node.list_channels().len(), 0);
2784 fn test_htlc_on_chain_success() {
2785 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2786 // the preimage backward accordingly. So here we test that ChannelManager is
2787 // broadcasting the right event to other nodes in payment path.
2788 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2789 // A --------------------> B ----------------------> C (preimage)
2790 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2791 // commitment transaction was broadcast.
2792 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2794 // B should be able to claim via preimage if A then broadcasts its local tx.
2795 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2796 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2797 // PaymentSent event).
2799 let chanmon_cfgs = create_chanmon_cfgs(3);
2800 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2801 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2802 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2804 // Create some initial channels
2805 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2806 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2808 // Rebalance the network a bit by relaying one payment through all the channels...
2809 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2810 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2812 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2813 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2814 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2816 // Broadcast legit commitment tx from C on B's chain
2817 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2818 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2819 assert_eq!(commitment_tx.len(), 1);
2820 check_spends!(commitment_tx[0], chan_2.3);
2821 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2822 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2823 check_added_monitors!(nodes[2], 2);
2824 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2825 assert!(updates.update_add_htlcs.is_empty());
2826 assert!(updates.update_fail_htlcs.is_empty());
2827 assert!(updates.update_fail_malformed_htlcs.is_empty());
2828 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2830 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2831 check_closed_broadcast!(nodes[2], false);
2832 check_added_monitors!(nodes[2], 1);
2833 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2834 assert_eq!(node_txn.len(), 5);
2835 assert_eq!(node_txn[0], node_txn[3]);
2836 assert_eq!(node_txn[1], node_txn[4]);
2837 assert_eq!(node_txn[2], commitment_tx[0]);
2838 check_spends!(node_txn[0], commitment_tx[0]);
2839 check_spends!(node_txn[1], commitment_tx[0]);
2840 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2841 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2842 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2843 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2844 assert_eq!(node_txn[0].lock_time, 0);
2845 assert_eq!(node_txn[1].lock_time, 0);
2847 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2848 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2850 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2851 assert_eq!(added_monitors.len(), 1);
2852 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2853 added_monitors.clear();
2855 let events = nodes[1].node.get_and_clear_pending_msg_events();
2857 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2858 assert_eq!(added_monitors.len(), 2);
2859 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2860 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2861 added_monitors.clear();
2863 assert_eq!(events.len(), 2);
2865 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2866 _ => panic!("Unexpected event"),
2869 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2870 assert!(update_add_htlcs.is_empty());
2871 assert!(update_fail_htlcs.is_empty());
2872 assert_eq!(update_fulfill_htlcs.len(), 1);
2873 assert!(update_fail_malformed_htlcs.is_empty());
2874 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2876 _ => panic!("Unexpected event"),
2878 macro_rules! check_tx_local_broadcast {
2879 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2880 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2881 assert_eq!(node_txn.len(), 5);
2882 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2883 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2884 check_spends!(node_txn[0], $commitment_tx);
2885 check_spends!(node_txn[1], $commitment_tx);
2886 assert_ne!(node_txn[0].lock_time, 0);
2887 assert_ne!(node_txn[1].lock_time, 0);
2889 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2890 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2891 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2892 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2894 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2895 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2896 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2897 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2899 check_spends!(node_txn[2], $chan_tx);
2900 check_spends!(node_txn[3], node_txn[2]);
2901 check_spends!(node_txn[4], node_txn[2]);
2902 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2903 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2904 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2905 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2906 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2907 assert_ne!(node_txn[3].lock_time, 0);
2908 assert_ne!(node_txn[4].lock_time, 0);
2912 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2913 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2914 // timeout-claim of the output that nodes[2] just claimed via success.
2915 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2917 // Broadcast legit commitment tx from A on B's chain
2918 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2919 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2920 check_spends!(commitment_tx[0], chan_1.3);
2921 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2922 check_closed_broadcast!(nodes[1], false);
2923 check_added_monitors!(nodes[1], 1);
2924 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2925 assert_eq!(node_txn.len(), 4);
2926 check_spends!(node_txn[0], commitment_tx[0]);
2927 assert_eq!(node_txn[0].input.len(), 2);
2928 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2929 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2930 assert_eq!(node_txn[0].lock_time, 0);
2931 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2932 check_spends!(node_txn[1], chan_1.3);
2933 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2934 check_spends!(node_txn[2], node_txn[1]);
2935 check_spends!(node_txn[3], node_txn[1]);
2936 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2937 // we already checked the same situation with A.
2939 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2940 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2941 check_closed_broadcast!(nodes[0], false);
2942 check_added_monitors!(nodes[0], 1);
2943 let events = nodes[0].node.get_and_clear_pending_events();
2944 assert_eq!(events.len(), 2);
2945 let mut first_claimed = false;
2946 for event in events {
2948 Event::PaymentSent { payment_preimage } => {
2949 if payment_preimage == our_payment_preimage {
2950 assert!(!first_claimed);
2951 first_claimed = true;
2953 assert_eq!(payment_preimage, our_payment_preimage_2);
2956 _ => panic!("Unexpected event"),
2959 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2963 fn test_htlc_on_chain_timeout() {
2964 // Test that in case of a unilateral close onchain, we detect the state of output and
2965 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2966 // broadcasting the right event to other nodes in payment path.
2967 // A ------------------> B ----------------------> C (timeout)
2968 // B's commitment tx C's commitment tx
2970 // B's HTLC timeout tx B's timeout tx
2972 let chanmon_cfgs = create_chanmon_cfgs(3);
2973 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2974 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2975 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2977 // Create some intial channels
2978 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2979 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2981 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2982 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2983 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2985 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2986 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2988 // Broadcast legit commitment tx from C on B's chain
2989 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2990 check_spends!(commitment_tx[0], chan_2.3);
2991 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2992 check_added_monitors!(nodes[2], 0);
2993 expect_pending_htlcs_forwardable!(nodes[2]);
2994 check_added_monitors!(nodes[2], 1);
2996 let events = nodes[2].node.get_and_clear_pending_msg_events();
2997 assert_eq!(events.len(), 1);
2999 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3000 assert!(update_add_htlcs.is_empty());
3001 assert!(!update_fail_htlcs.is_empty());
3002 assert!(update_fulfill_htlcs.is_empty());
3003 assert!(update_fail_malformed_htlcs.is_empty());
3004 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3006 _ => panic!("Unexpected event"),
3008 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3009 check_closed_broadcast!(nodes[2], false);
3010 check_added_monitors!(nodes[2], 1);
3011 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
3012 assert_eq!(node_txn.len(), 1);
3013 check_spends!(node_txn[0], chan_2.3);
3014 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
3016 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3017 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3018 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3021 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3022 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
3023 assert_eq!(node_txn[1], node_txn[3]);
3024 assert_eq!(node_txn[2], node_txn[4]);
3026 check_spends!(node_txn[0], commitment_tx[0]);
3027 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3029 check_spends!(node_txn[1], chan_2.3);
3030 check_spends!(node_txn[2], node_txn[1]);
3031 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3032 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3034 timeout_tx = node_txn[0].clone();
3038 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
3039 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3040 check_added_monitors!(nodes[1], 1);
3041 check_closed_broadcast!(nodes[1], false);
3043 expect_pending_htlcs_forwardable!(nodes[1]);
3044 check_added_monitors!(nodes[1], 1);
3045 let events = nodes[1].node.get_and_clear_pending_msg_events();
3046 assert_eq!(events.len(), 1);
3048 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3049 assert!(update_add_htlcs.is_empty());
3050 assert!(!update_fail_htlcs.is_empty());
3051 assert!(update_fulfill_htlcs.is_empty());
3052 assert!(update_fail_malformed_htlcs.is_empty());
3053 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3055 _ => panic!("Unexpected event"),
3057 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
3058 assert_eq!(node_txn.len(), 0);
3060 // Broadcast legit commitment tx from B on A's chain
3061 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3062 check_spends!(commitment_tx[0], chan_1.3);
3064 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3065 check_closed_broadcast!(nodes[0], false);
3066 check_added_monitors!(nodes[0], 1);
3067 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3068 assert_eq!(node_txn.len(), 3);
3069 check_spends!(node_txn[0], commitment_tx[0]);
3070 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3071 check_spends!(node_txn[1], chan_1.3);
3072 check_spends!(node_txn[2], node_txn[1]);
3073 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3074 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3078 fn test_simple_commitment_revoked_fail_backward() {
3079 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3080 // and fail backward accordingly.
3082 let chanmon_cfgs = create_chanmon_cfgs(3);
3083 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3084 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3085 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3087 // Create some initial channels
3088 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3089 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3091 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3092 // Get the will-be-revoked local txn from nodes[2]
3093 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3094 // Revoke the old state
3095 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3097 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3099 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3100 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3101 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3102 check_added_monitors!(nodes[1], 1);
3103 check_closed_broadcast!(nodes[1], false);
3105 expect_pending_htlcs_forwardable!(nodes[1]);
3106 check_added_monitors!(nodes[1], 1);
3107 let events = nodes[1].node.get_and_clear_pending_msg_events();
3108 assert_eq!(events.len(), 1);
3110 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3111 assert!(update_add_htlcs.is_empty());
3112 assert_eq!(update_fail_htlcs.len(), 1);
3113 assert!(update_fulfill_htlcs.is_empty());
3114 assert!(update_fail_malformed_htlcs.is_empty());
3115 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3117 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3118 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3120 let events = nodes[0].node.get_and_clear_pending_msg_events();
3121 assert_eq!(events.len(), 1);
3123 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3124 _ => panic!("Unexpected event"),
3126 expect_payment_failed!(nodes[0], payment_hash, false);
3128 _ => panic!("Unexpected event"),
3132 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3133 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3134 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3135 // commitment transaction anymore.
3136 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3137 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3138 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3139 // technically disallowed and we should probably handle it reasonably.
3140 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3141 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3143 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3144 // commitment_signed (implying it will be in the latest remote commitment transaction).
3145 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3146 // and once they revoke the previous commitment transaction (allowing us to send a new
3147 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3148 let chanmon_cfgs = create_chanmon_cfgs(3);
3149 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3150 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3151 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3153 // Create some initial channels
3154 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3155 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3157 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3158 // Get the will-be-revoked local txn from nodes[2]
3159 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3160 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3161 // Revoke the old state
3162 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3164 let value = if use_dust {
3165 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3166 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3167 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3170 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3171 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3172 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3174 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3175 expect_pending_htlcs_forwardable!(nodes[2]);
3176 check_added_monitors!(nodes[2], 1);
3177 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3178 assert!(updates.update_add_htlcs.is_empty());
3179 assert!(updates.update_fulfill_htlcs.is_empty());
3180 assert!(updates.update_fail_malformed_htlcs.is_empty());
3181 assert_eq!(updates.update_fail_htlcs.len(), 1);
3182 assert!(updates.update_fee.is_none());
3183 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3184 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3185 // Drop the last RAA from 3 -> 2
3187 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3188 expect_pending_htlcs_forwardable!(nodes[2]);
3189 check_added_monitors!(nodes[2], 1);
3190 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3191 assert!(updates.update_add_htlcs.is_empty());
3192 assert!(updates.update_fulfill_htlcs.is_empty());
3193 assert!(updates.update_fail_malformed_htlcs.is_empty());
3194 assert_eq!(updates.update_fail_htlcs.len(), 1);
3195 assert!(updates.update_fee.is_none());
3196 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3197 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3198 check_added_monitors!(nodes[1], 1);
3199 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3200 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3201 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3202 check_added_monitors!(nodes[2], 1);
3204 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3205 expect_pending_htlcs_forwardable!(nodes[2]);
3206 check_added_monitors!(nodes[2], 1);
3207 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3208 assert!(updates.update_add_htlcs.is_empty());
3209 assert!(updates.update_fulfill_htlcs.is_empty());
3210 assert!(updates.update_fail_malformed_htlcs.is_empty());
3211 assert_eq!(updates.update_fail_htlcs.len(), 1);
3212 assert!(updates.update_fee.is_none());
3213 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3214 // At this point first_payment_hash has dropped out of the latest two commitment
3215 // transactions that nodes[1] is tracking...
3216 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3217 check_added_monitors!(nodes[1], 1);
3218 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3219 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3220 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3221 check_added_monitors!(nodes[2], 1);
3223 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3224 // on nodes[2]'s RAA.
3225 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3226 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3227 let logger = test_utils::TestLogger::new();
3228 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3229 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3230 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3231 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3232 check_added_monitors!(nodes[1], 0);
3235 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3236 // One monitor for the new revocation preimage, no second on as we won't generate a new
3237 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3238 check_added_monitors!(nodes[1], 1);
3239 let events = nodes[1].node.get_and_clear_pending_events();
3240 assert_eq!(events.len(), 1);
3242 Event::PendingHTLCsForwardable { .. } => { },
3243 _ => panic!("Unexpected event"),
3245 // Deliberately don't process the pending fail-back so they all fail back at once after
3246 // block connection just like the !deliver_bs_raa case
3249 let mut failed_htlcs = HashSet::new();
3250 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3252 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3253 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3254 check_added_monitors!(nodes[1], 1);
3255 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3257 let events = nodes[1].node.get_and_clear_pending_events();
3258 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3260 Event::PaymentFailed { ref payment_hash, .. } => {
3261 assert_eq!(*payment_hash, fourth_payment_hash);
3263 _ => panic!("Unexpected event"),
3265 if !deliver_bs_raa {
3267 Event::PendingHTLCsForwardable { .. } => { },
3268 _ => panic!("Unexpected event"),
3271 nodes[1].node.process_pending_htlc_forwards();
3272 check_added_monitors!(nodes[1], 1);
3274 let events = nodes[1].node.get_and_clear_pending_msg_events();
3275 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3276 match events[if deliver_bs_raa { 1 } else { 0 }] {
3277 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3278 _ => panic!("Unexpected event"),
3282 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
3283 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3284 assert_eq!(update_add_htlcs.len(), 1);
3285 assert!(update_fulfill_htlcs.is_empty());
3286 assert!(update_fail_htlcs.is_empty());
3287 assert!(update_fail_malformed_htlcs.is_empty());
3289 _ => panic!("Unexpected event"),
3292 match events[if deliver_bs_raa { 2 } else { 1 }] {
3293 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
3294 assert!(update_add_htlcs.is_empty());
3295 assert_eq!(update_fail_htlcs.len(), 3);
3296 assert!(update_fulfill_htlcs.is_empty());
3297 assert!(update_fail_malformed_htlcs.is_empty());
3298 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3300 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3301 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3302 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3304 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3306 let events = nodes[0].node.get_and_clear_pending_msg_events();
3307 // If we delivered B's RAA we got an unknown preimage error, not something
3308 // that we should update our routing table for.
3309 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3310 for event in events {
3312 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3313 _ => panic!("Unexpected event"),
3316 let events = nodes[0].node.get_and_clear_pending_events();
3317 assert_eq!(events.len(), 3);
3319 Event::PaymentFailed { ref payment_hash, .. } => {
3320 assert!(failed_htlcs.insert(payment_hash.0));
3322 _ => panic!("Unexpected event"),
3325 Event::PaymentFailed { ref payment_hash, .. } => {
3326 assert!(failed_htlcs.insert(payment_hash.0));
3328 _ => panic!("Unexpected event"),
3331 Event::PaymentFailed { ref payment_hash, .. } => {
3332 assert!(failed_htlcs.insert(payment_hash.0));
3334 _ => panic!("Unexpected event"),
3337 _ => panic!("Unexpected event"),
3340 assert!(failed_htlcs.contains(&first_payment_hash.0));
3341 assert!(failed_htlcs.contains(&second_payment_hash.0));
3342 assert!(failed_htlcs.contains(&third_payment_hash.0));
3346 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3347 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3348 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3349 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3350 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3354 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3355 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3356 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3357 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3358 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3362 fn fail_backward_pending_htlc_upon_channel_failure() {
3363 let chanmon_cfgs = create_chanmon_cfgs(2);
3364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3367 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3368 let logger = test_utils::TestLogger::new();
3370 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3372 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3373 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3374 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3375 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3376 check_added_monitors!(nodes[0], 1);
3378 let payment_event = {
3379 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3380 assert_eq!(events.len(), 1);
3381 SendEvent::from_event(events.remove(0))
3383 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3384 assert_eq!(payment_event.msgs.len(), 1);
3387 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3388 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3390 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3391 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3392 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3393 check_added_monitors!(nodes[0], 0);
3395 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3398 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3400 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3402 let secp_ctx = Secp256k1::new();
3403 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3404 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3405 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3406 let route = get_route(&nodes[1].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
3407 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3408 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3409 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3411 // Send a 0-msat update_add_htlc to fail the channel.
3412 let update_add_htlc = msgs::UpdateAddHTLC {
3418 onion_routing_packet,
3420 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3423 // Check that Alice fails backward the pending HTLC from the second payment.
3424 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3425 check_closed_broadcast!(nodes[0], true);
3426 check_added_monitors!(nodes[0], 1);
3430 fn test_htlc_ignore_latest_remote_commitment() {
3431 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3432 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3433 let chanmon_cfgs = create_chanmon_cfgs(2);
3434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3436 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3437 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3439 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3440 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3441 check_closed_broadcast!(nodes[0], false);
3442 check_added_monitors!(nodes[0], 1);
3444 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3445 assert_eq!(node_txn.len(), 2);
3447 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3448 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3449 check_closed_broadcast!(nodes[1], false);
3450 check_added_monitors!(nodes[1], 1);
3452 // Duplicate the connect_block call since this may happen due to other listeners
3453 // registering new transactions
3454 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3458 fn test_force_close_fail_back() {
3459 // Check which HTLCs are failed-backwards on channel force-closure
3460 let chanmon_cfgs = create_chanmon_cfgs(3);
3461 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3462 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3463 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3464 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3465 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3466 let logger = test_utils::TestLogger::new();
3468 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3470 let mut payment_event = {
3471 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3472 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3473 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3474 check_added_monitors!(nodes[0], 1);
3476 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3477 assert_eq!(events.len(), 1);
3478 SendEvent::from_event(events.remove(0))
3481 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3482 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3484 expect_pending_htlcs_forwardable!(nodes[1]);
3486 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3487 assert_eq!(events_2.len(), 1);
3488 payment_event = SendEvent::from_event(events_2.remove(0));
3489 assert_eq!(payment_event.msgs.len(), 1);
3491 check_added_monitors!(nodes[1], 1);
3492 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3493 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3494 check_added_monitors!(nodes[2], 1);
3495 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3497 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3498 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3499 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3501 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3502 check_closed_broadcast!(nodes[2], false);
3503 check_added_monitors!(nodes[2], 1);
3505 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3506 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3507 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3508 // back to nodes[1] upon timeout otherwise.
3509 assert_eq!(node_txn.len(), 1);
3514 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3515 txdata: vec![tx.clone()],
3517 connect_block(&nodes[1], &block, 1);
3519 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3520 check_closed_broadcast!(nodes[1], false);
3521 check_added_monitors!(nodes[1], 1);
3523 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3525 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3526 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3527 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3529 connect_block(&nodes[2], &block, 1);
3530 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3531 assert_eq!(node_txn.len(), 1);
3532 assert_eq!(node_txn[0].input.len(), 1);
3533 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3534 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3535 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3537 check_spends!(node_txn[0], tx);
3541 fn test_unconf_chan() {
3542 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3543 let chanmon_cfgs = create_chanmon_cfgs(2);
3544 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3545 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3546 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3547 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3549 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3550 assert_eq!(channel_state.by_id.len(), 1);
3551 assert_eq!(channel_state.short_to_id.len(), 1);
3552 mem::drop(channel_state);
3554 let mut headers = Vec::new();
3555 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3556 headers.push(header.clone());
3558 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3559 headers.push(header.clone());
3561 while !headers.is_empty() {
3562 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3564 check_closed_broadcast!(nodes[0], false);
3565 check_added_monitors!(nodes[0], 1);
3566 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3567 assert_eq!(channel_state.by_id.len(), 0);
3568 assert_eq!(channel_state.short_to_id.len(), 0);
3572 fn test_simple_peer_disconnect() {
3573 // Test that we can reconnect when there are no lost messages
3574 let chanmon_cfgs = create_chanmon_cfgs(3);
3575 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3576 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3577 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3578 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3579 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3581 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3582 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3583 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3585 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3586 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3587 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3588 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3590 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3591 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3592 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3594 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3595 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3596 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3597 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3599 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3600 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3602 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3603 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3605 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3607 let events = nodes[0].node.get_and_clear_pending_events();
3608 assert_eq!(events.len(), 2);
3610 Event::PaymentSent { payment_preimage } => {
3611 assert_eq!(payment_preimage, payment_preimage_3);
3613 _ => panic!("Unexpected event"),
3616 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3617 assert_eq!(payment_hash, payment_hash_5);
3618 assert!(rejected_by_dest);
3620 _ => panic!("Unexpected event"),
3624 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3625 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3628 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3629 // Test that we can reconnect when in-flight HTLC updates get dropped
3630 let chanmon_cfgs = create_chanmon_cfgs(2);
3631 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3632 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3633 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3634 if messages_delivered == 0 {
3635 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3636 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3638 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3641 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3643 let logger = test_utils::TestLogger::new();
3644 let payment_event = {
3645 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3646 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3647 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3648 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3649 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3650 check_added_monitors!(nodes[0], 1);
3652 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3653 assert_eq!(events.len(), 1);
3654 SendEvent::from_event(events.remove(0))
3656 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3658 if messages_delivered < 2 {
3659 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3661 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3662 if messages_delivered >= 3 {
3663 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3664 check_added_monitors!(nodes[1], 1);
3665 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3667 if messages_delivered >= 4 {
3668 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3669 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3670 check_added_monitors!(nodes[0], 1);
3672 if messages_delivered >= 5 {
3673 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3674 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3675 // No commitment_signed so get_event_msg's assert(len == 1) passes
3676 check_added_monitors!(nodes[0], 1);
3678 if messages_delivered >= 6 {
3679 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3680 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3681 check_added_monitors!(nodes[1], 1);
3688 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3689 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3690 if messages_delivered < 3 {
3691 // Even if the funding_locked messages get exchanged, as long as nothing further was
3692 // received on either side, both sides will need to resend them.
3693 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3694 } else if messages_delivered == 3 {
3695 // nodes[0] still wants its RAA + commitment_signed
3696 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3697 } else if messages_delivered == 4 {
3698 // nodes[0] still wants its commitment_signed
3699 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3700 } else if messages_delivered == 5 {
3701 // nodes[1] still wants its final RAA
3702 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3703 } else if messages_delivered == 6 {
3704 // Everything was delivered...
3705 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3708 let events_1 = nodes[1].node.get_and_clear_pending_events();
3709 assert_eq!(events_1.len(), 1);
3711 Event::PendingHTLCsForwardable { .. } => { },
3712 _ => panic!("Unexpected event"),
3715 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3716 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3717 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3719 nodes[1].node.process_pending_htlc_forwards();
3721 let events_2 = nodes[1].node.get_and_clear_pending_events();
3722 assert_eq!(events_2.len(), 1);
3724 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3725 assert_eq!(payment_hash_1, *payment_hash);
3726 assert_eq!(*payment_secret, None);
3727 assert_eq!(amt, 1000000);
3729 _ => panic!("Unexpected event"),
3732 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3733 check_added_monitors!(nodes[1], 1);
3735 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3736 assert_eq!(events_3.len(), 1);
3737 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3738 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3739 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3740 assert!(updates.update_add_htlcs.is_empty());
3741 assert!(updates.update_fail_htlcs.is_empty());
3742 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3743 assert!(updates.update_fail_malformed_htlcs.is_empty());
3744 assert!(updates.update_fee.is_none());
3745 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3747 _ => panic!("Unexpected event"),
3750 if messages_delivered >= 1 {
3751 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3753 let events_4 = nodes[0].node.get_and_clear_pending_events();
3754 assert_eq!(events_4.len(), 1);
3756 Event::PaymentSent { ref payment_preimage } => {
3757 assert_eq!(payment_preimage_1, *payment_preimage);
3759 _ => panic!("Unexpected event"),
3762 if messages_delivered >= 2 {
3763 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3764 check_added_monitors!(nodes[0], 1);
3765 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3767 if messages_delivered >= 3 {
3768 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3769 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3770 check_added_monitors!(nodes[1], 1);
3772 if messages_delivered >= 4 {
3773 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3774 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3775 // No commitment_signed so get_event_msg's assert(len == 1) passes
3776 check_added_monitors!(nodes[1], 1);
3778 if messages_delivered >= 5 {
3779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3780 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3781 check_added_monitors!(nodes[0], 1);
3788 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3789 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3790 if messages_delivered < 2 {
3791 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3792 //TODO: Deduplicate PaymentSent events, then enable this if:
3793 //if messages_delivered < 1 {
3794 let events_4 = nodes[0].node.get_and_clear_pending_events();
3795 assert_eq!(events_4.len(), 1);
3797 Event::PaymentSent { ref payment_preimage } => {
3798 assert_eq!(payment_preimage_1, *payment_preimage);
3800 _ => panic!("Unexpected event"),
3803 } else if messages_delivered == 2 {
3804 // nodes[0] still wants its RAA + commitment_signed
3805 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3806 } else if messages_delivered == 3 {
3807 // nodes[0] still wants its commitment_signed
3808 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3809 } else if messages_delivered == 4 {
3810 // nodes[1] still wants its final RAA
3811 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3812 } else if messages_delivered == 5 {
3813 // Everything was delivered...
3814 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3817 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3818 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3819 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3821 // Channel should still work fine...
3822 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3823 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3824 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3825 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3826 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3827 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3831 fn test_drop_messages_peer_disconnect_a() {
3832 do_test_drop_messages_peer_disconnect(0);
3833 do_test_drop_messages_peer_disconnect(1);
3834 do_test_drop_messages_peer_disconnect(2);
3835 do_test_drop_messages_peer_disconnect(3);
3839 fn test_drop_messages_peer_disconnect_b() {
3840 do_test_drop_messages_peer_disconnect(4);
3841 do_test_drop_messages_peer_disconnect(5);
3842 do_test_drop_messages_peer_disconnect(6);
3846 fn test_funding_peer_disconnect() {
3847 // Test that we can lock in our funding tx while disconnected
3848 let chanmon_cfgs = create_chanmon_cfgs(2);
3849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3851 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3852 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3854 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3855 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3857 confirm_transaction(&nodes[0], &tx);
3858 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3859 assert_eq!(events_1.len(), 1);
3861 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3862 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3864 _ => panic!("Unexpected event"),
3867 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3869 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3870 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3872 confirm_transaction(&nodes[1], &tx);
3873 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3874 assert_eq!(events_2.len(), 2);
3875 let funding_locked = match events_2[0] {
3876 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3877 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3880 _ => panic!("Unexpected event"),
3882 let bs_announcement_sigs = match events_2[1] {
3883 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3884 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3887 _ => panic!("Unexpected event"),
3890 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3892 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3893 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3894 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3895 assert_eq!(events_3.len(), 2);
3896 let as_announcement_sigs = match events_3[0] {
3897 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3898 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3901 _ => panic!("Unexpected event"),
3903 let (as_announcement, as_update) = match events_3[1] {
3904 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3905 (msg.clone(), update_msg.clone())
3907 _ => panic!("Unexpected event"),
3910 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3911 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3912 assert_eq!(events_4.len(), 1);
3913 let (_, bs_update) = match events_4[0] {
3914 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3915 (msg.clone(), update_msg.clone())
3917 _ => panic!("Unexpected event"),
3920 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3921 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3922 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3924 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3925 let logger = test_utils::TestLogger::new();
3926 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();
3927 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3928 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3932 fn test_drop_messages_peer_disconnect_dual_htlc() {
3933 // Test that we can handle reconnecting when both sides of a channel have pending
3934 // commitment_updates when we disconnect.
3935 let chanmon_cfgs = create_chanmon_cfgs(2);
3936 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3937 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3938 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3939 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3940 let logger = test_utils::TestLogger::new();
3942 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3944 // Now try to send a second payment which will fail to send
3945 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3946 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3947 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();
3948 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3949 check_added_monitors!(nodes[0], 1);
3951 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3952 assert_eq!(events_1.len(), 1);
3954 MessageSendEvent::UpdateHTLCs { .. } => {},
3955 _ => panic!("Unexpected event"),
3958 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3959 check_added_monitors!(nodes[1], 1);
3961 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3962 assert_eq!(events_2.len(), 1);
3964 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 } } => {
3965 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3966 assert!(update_add_htlcs.is_empty());
3967 assert_eq!(update_fulfill_htlcs.len(), 1);
3968 assert!(update_fail_htlcs.is_empty());
3969 assert!(update_fail_malformed_htlcs.is_empty());
3970 assert!(update_fee.is_none());
3972 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3973 let events_3 = nodes[0].node.get_and_clear_pending_events();
3974 assert_eq!(events_3.len(), 1);
3976 Event::PaymentSent { ref payment_preimage } => {
3977 assert_eq!(*payment_preimage, payment_preimage_1);
3979 _ => panic!("Unexpected event"),
3982 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3983 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3984 // No commitment_signed so get_event_msg's assert(len == 1) passes
3985 check_added_monitors!(nodes[0], 1);
3987 _ => panic!("Unexpected event"),
3990 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3991 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3993 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3994 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3995 assert_eq!(reestablish_1.len(), 1);
3996 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3997 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3998 assert_eq!(reestablish_2.len(), 1);
4000 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4001 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4002 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4003 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4005 assert!(as_resp.0.is_none());
4006 assert!(bs_resp.0.is_none());
4008 assert!(bs_resp.1.is_none());
4009 assert!(bs_resp.2.is_none());
4011 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4013 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4014 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4015 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4016 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4017 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4018 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4019 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4020 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4021 // No commitment_signed so get_event_msg's assert(len == 1) passes
4022 check_added_monitors!(nodes[1], 1);
4024 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4025 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4026 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4027 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4028 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4029 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4030 assert!(bs_second_commitment_signed.update_fee.is_none());
4031 check_added_monitors!(nodes[1], 1);
4033 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4034 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4035 assert!(as_commitment_signed.update_add_htlcs.is_empty());
4036 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4037 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4038 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4039 assert!(as_commitment_signed.update_fee.is_none());
4040 check_added_monitors!(nodes[0], 1);
4042 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4043 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4044 // No commitment_signed so get_event_msg's assert(len == 1) passes
4045 check_added_monitors!(nodes[0], 1);
4047 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4048 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4049 // No commitment_signed so get_event_msg's assert(len == 1) passes
4050 check_added_monitors!(nodes[1], 1);
4052 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4053 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4054 check_added_monitors!(nodes[1], 1);
4056 expect_pending_htlcs_forwardable!(nodes[1]);
4058 let events_5 = nodes[1].node.get_and_clear_pending_events();
4059 assert_eq!(events_5.len(), 1);
4061 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4062 assert_eq!(payment_hash_2, *payment_hash);
4063 assert_eq!(*payment_secret, None);
4065 _ => panic!("Unexpected event"),
4068 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4069 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4070 check_added_monitors!(nodes[0], 1);
4072 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4075 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4076 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4077 // to avoid our counterparty failing the channel.
4078 let chanmon_cfgs = create_chanmon_cfgs(2);
4079 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4080 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4081 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4083 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4084 let logger = test_utils::TestLogger::new();
4086 let our_payment_hash = if send_partial_mpp {
4087 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4088 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();
4089 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4090 let payment_secret = PaymentSecret([0xdb; 32]);
4091 // Use the utility function send_payment_along_path to send the payment with MPP data which
4092 // indicates there are more HTLCs coming.
4093 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4094 check_added_monitors!(nodes[0], 1);
4095 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4096 assert_eq!(events.len(), 1);
4097 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4098 // hop should *not* yet generate any PaymentReceived event(s).
4099 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4102 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4105 let mut block = Block {
4106 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4109 connect_block(&nodes[0], &block, 101);
4110 connect_block(&nodes[1], &block, 101);
4111 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4112 block.header.prev_blockhash = block.block_hash();
4113 connect_block(&nodes[0], &block, i);
4114 connect_block(&nodes[1], &block, i);
4117 expect_pending_htlcs_forwardable!(nodes[1]);
4119 check_added_monitors!(nodes[1], 1);
4120 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4121 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4122 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4123 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4124 assert!(htlc_timeout_updates.update_fee.is_none());
4126 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4127 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4128 // 100_000 msat as u64, followed by a height of 123 as u32
4129 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4130 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4131 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4135 fn test_htlc_timeout() {
4136 do_test_htlc_timeout(true);
4137 do_test_htlc_timeout(false);
4140 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4141 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4142 let chanmon_cfgs = create_chanmon_cfgs(3);
4143 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4144 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4145 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4146 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4147 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4148 let logger = test_utils::TestLogger::new();
4150 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4151 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4153 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4154 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();
4155 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4157 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4158 check_added_monitors!(nodes[1], 1);
4160 // Now attempt to route a second payment, which should be placed in the holding cell
4161 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4163 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4164 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();
4165 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4166 check_added_monitors!(nodes[0], 1);
4167 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4168 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4169 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4170 expect_pending_htlcs_forwardable!(nodes[1]);
4171 check_added_monitors!(nodes[1], 0);
4173 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4174 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();
4175 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4176 check_added_monitors!(nodes[1], 0);
4179 let mut block = Block {
4180 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4183 connect_block(&nodes[1], &block, 101);
4184 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4185 block.header.prev_blockhash = block.block_hash();
4186 connect_block(&nodes[1], &block, i);
4189 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4190 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4192 block.header.prev_blockhash = block.block_hash();
4193 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4196 expect_pending_htlcs_forwardable!(nodes[1]);
4197 check_added_monitors!(nodes[1], 1);
4198 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4199 assert_eq!(fail_commit.len(), 1);
4200 match fail_commit[0] {
4201 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4202 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4203 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4205 _ => unreachable!(),
4207 expect_payment_failed!(nodes[0], second_payment_hash, false);
4208 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4210 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4211 _ => panic!("Unexpected event"),
4214 panic!("Unexpected event");
4217 expect_payment_failed!(nodes[1], second_payment_hash, true);
4222 fn test_holding_cell_htlc_add_timeouts() {
4223 do_test_holding_cell_htlc_add_timeouts(false);
4224 do_test_holding_cell_htlc_add_timeouts(true);
4228 fn test_invalid_channel_announcement() {
4229 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4230 let secp_ctx = Secp256k1::new();
4231 let chanmon_cfgs = create_chanmon_cfgs(2);
4232 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4233 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4234 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4236 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4238 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4239 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4240 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4241 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4243 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 } );
4245 let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4246 let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4248 let as_network_key = nodes[0].node.get_our_node_id();
4249 let bs_network_key = nodes[1].node.get_our_node_id();
4251 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4253 let mut chan_announcement;
4255 macro_rules! dummy_unsigned_msg {
4257 msgs::UnsignedChannelAnnouncement {
4258 features: ChannelFeatures::known(),
4259 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4260 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4261 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4262 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4263 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4264 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4265 excess_data: Vec::new(),
4270 macro_rules! sign_msg {
4271 ($unsigned_msg: expr) => {
4272 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4273 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4274 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4275 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4276 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4277 chan_announcement = msgs::ChannelAnnouncement {
4278 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4279 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4280 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4281 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4282 contents: $unsigned_msg
4287 let unsigned_msg = dummy_unsigned_msg!();
4288 sign_msg!(unsigned_msg);
4289 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4290 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 } );
4292 // Configured with Network::Testnet
4293 let mut unsigned_msg = dummy_unsigned_msg!();
4294 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4295 sign_msg!(unsigned_msg);
4296 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4298 let mut unsigned_msg = dummy_unsigned_msg!();
4299 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4300 sign_msg!(unsigned_msg);
4301 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4305 fn test_no_txn_manager_serialize_deserialize() {
4306 let chanmon_cfgs = create_chanmon_cfgs(2);
4307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4309 let logger: test_utils::TestLogger;
4310 let fee_estimator: test_utils::TestFeeEstimator;
4311 let persister: test_utils::TestPersister;
4312 let new_chain_monitor: test_utils::TestChainMonitor;
4313 let keys_manager: test_utils::TestKeysInterface;
4314 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4315 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4317 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4319 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4321 let nodes_0_serialized = nodes[0].node.encode();
4322 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4323 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut chan_0_monitor_serialized).unwrap();
4325 logger = test_utils::TestLogger::new();
4326 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4327 persister = test_utils::TestPersister::new();
4328 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4329 nodes[0].chain_monitor = &new_chain_monitor;
4330 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4331 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4332 assert!(chan_0_monitor_read.is_empty());
4334 let mut nodes_0_read = &nodes_0_serialized[..];
4335 let config = UserConfig::default();
4336 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4337 let (_, nodes_0_deserialized_tmp) = {
4338 let mut channel_monitors = HashMap::new();
4339 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4340 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4341 default_config: config,
4342 keys_manager: &keys_manager,
4343 fee_estimator: &fee_estimator,
4344 chain_monitor: nodes[0].chain_monitor,
4345 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4350 nodes_0_deserialized = nodes_0_deserialized_tmp;
4351 assert!(nodes_0_read.is_empty());
4353 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4354 nodes[0].node = &nodes_0_deserialized;
4355 assert_eq!(nodes[0].node.list_channels().len(), 1);
4356 check_added_monitors!(nodes[0], 1);
4358 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4359 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4360 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4361 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4363 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4364 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4365 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4366 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4368 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4369 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4370 for node in nodes.iter() {
4371 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4372 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4373 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4376 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4380 fn test_manager_serialize_deserialize_events() {
4381 // This test makes sure the events field in ChannelManager survives de/serialization
4382 let chanmon_cfgs = create_chanmon_cfgs(2);
4383 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4384 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4385 let fee_estimator: test_utils::TestFeeEstimator;
4386 let persister: test_utils::TestPersister;
4387 let logger: test_utils::TestLogger;
4388 let new_chain_monitor: test_utils::TestChainMonitor;
4389 let keys_manager: test_utils::TestKeysInterface;
4390 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4391 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4393 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4394 let channel_value = 100000;
4395 let push_msat = 10001;
4396 let a_flags = InitFeatures::known();
4397 let b_flags = InitFeatures::known();
4398 let node_a = nodes.pop().unwrap();
4399 let node_b = nodes.pop().unwrap();
4400 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4401 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()));
4402 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()));
4404 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4406 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4407 check_added_monitors!(node_a, 0);
4409 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()));
4411 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4412 assert_eq!(added_monitors.len(), 1);
4413 assert_eq!(added_monitors[0].0, funding_output);
4414 added_monitors.clear();
4417 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()));
4419 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4420 assert_eq!(added_monitors.len(), 1);
4421 assert_eq!(added_monitors[0].0, funding_output);
4422 added_monitors.clear();
4424 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4429 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4430 let nodes_0_serialized = nodes[0].node.encode();
4431 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4432 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut chan_0_monitor_serialized).unwrap();
4434 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4435 logger = test_utils::TestLogger::new();
4436 persister = test_utils::TestPersister::new();
4437 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4438 nodes[0].chain_monitor = &new_chain_monitor;
4439 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4440 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4441 assert!(chan_0_monitor_read.is_empty());
4443 let mut nodes_0_read = &nodes_0_serialized[..];
4444 let config = UserConfig::default();
4445 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4446 let (_, nodes_0_deserialized_tmp) = {
4447 let mut channel_monitors = HashMap::new();
4448 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4449 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4450 default_config: config,
4451 keys_manager: &keys_manager,
4452 fee_estimator: &fee_estimator,
4453 chain_monitor: nodes[0].chain_monitor,
4454 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4459 nodes_0_deserialized = nodes_0_deserialized_tmp;
4460 assert!(nodes_0_read.is_empty());
4462 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4464 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4465 nodes[0].node = &nodes_0_deserialized;
4467 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4468 let events_4 = nodes[0].node.get_and_clear_pending_events();
4469 assert_eq!(events_4.len(), 1);
4471 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4472 assert_eq!(user_channel_id, 42);
4473 assert_eq!(*funding_txo, funding_output);
4475 _ => panic!("Unexpected event"),
4478 // Make sure the channel is functioning as though the de/serialization never happened
4479 assert_eq!(nodes[0].node.list_channels().len(), 1);
4480 check_added_monitors!(nodes[0], 1);
4482 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4483 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4484 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4485 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4487 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4488 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4489 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4490 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4492 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4493 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4494 for node in nodes.iter() {
4495 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4496 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4497 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4500 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4504 fn test_simple_manager_serialize_deserialize() {
4505 let chanmon_cfgs = create_chanmon_cfgs(2);
4506 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4507 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4508 let logger: test_utils::TestLogger;
4509 let fee_estimator: test_utils::TestFeeEstimator;
4510 let persister: test_utils::TestPersister;
4511 let new_chain_monitor: test_utils::TestChainMonitor;
4512 let keys_manager: test_utils::TestKeysInterface;
4513 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4514 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4515 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4517 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4518 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4520 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4522 let nodes_0_serialized = nodes[0].node.encode();
4523 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4524 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut chan_0_monitor_serialized).unwrap();
4526 logger = test_utils::TestLogger::new();
4527 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4528 persister = test_utils::TestPersister::new();
4529 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4530 nodes[0].chain_monitor = &new_chain_monitor;
4531 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4532 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4533 assert!(chan_0_monitor_read.is_empty());
4535 let mut nodes_0_read = &nodes_0_serialized[..];
4536 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4537 let (_, nodes_0_deserialized_tmp) = {
4538 let mut channel_monitors = HashMap::new();
4539 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4540 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4541 default_config: UserConfig::default(),
4542 keys_manager: &keys_manager,
4543 fee_estimator: &fee_estimator,
4544 chain_monitor: nodes[0].chain_monitor,
4545 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4550 nodes_0_deserialized = nodes_0_deserialized_tmp;
4551 assert!(nodes_0_read.is_empty());
4553 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4554 nodes[0].node = &nodes_0_deserialized;
4555 check_added_monitors!(nodes[0], 1);
4557 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4559 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4560 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4564 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4565 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4566 let chanmon_cfgs = create_chanmon_cfgs(4);
4567 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4568 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4569 let logger: test_utils::TestLogger;
4570 let fee_estimator: test_utils::TestFeeEstimator;
4571 let persister: test_utils::TestPersister;
4572 let new_chain_monitor: test_utils::TestChainMonitor;
4573 let keys_manager: test_utils::TestKeysInterface;
4574 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4575 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4576 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4577 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4578 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4580 let mut node_0_stale_monitors_serialized = Vec::new();
4581 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4582 let mut writer = test_utils::TestVecWriter(Vec::new());
4583 monitor.1.serialize_for_disk(&mut writer).unwrap();
4584 node_0_stale_monitors_serialized.push(writer.0);
4587 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4589 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4590 let nodes_0_serialized = nodes[0].node.encode();
4592 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4593 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4594 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4595 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4597 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4599 let mut node_0_monitors_serialized = Vec::new();
4600 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4601 let mut writer = test_utils::TestVecWriter(Vec::new());
4602 monitor.1.serialize_for_disk(&mut writer).unwrap();
4603 node_0_monitors_serialized.push(writer.0);
4606 logger = test_utils::TestLogger::new();
4607 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4608 persister = test_utils::TestPersister::new();
4609 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister);
4610 nodes[0].chain_monitor = &new_chain_monitor;
4612 let mut node_0_stale_monitors = Vec::new();
4613 for serialized in node_0_stale_monitors_serialized.iter() {
4614 let mut read = &serialized[..];
4615 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4616 assert!(read.is_empty());
4617 node_0_stale_monitors.push(monitor);
4620 let mut node_0_monitors = Vec::new();
4621 for serialized in node_0_monitors_serialized.iter() {
4622 let mut read = &serialized[..];
4623 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4624 assert!(read.is_empty());
4625 node_0_monitors.push(monitor);
4628 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4630 let mut nodes_0_read = &nodes_0_serialized[..];
4631 if let Err(msgs::DecodeError::InvalidValue) =
4632 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4633 default_config: UserConfig::default(),
4634 keys_manager: &keys_manager,
4635 fee_estimator: &fee_estimator,
4636 chain_monitor: nodes[0].chain_monitor,
4637 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4639 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4641 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4644 let mut nodes_0_read = &nodes_0_serialized[..];
4645 let (_, nodes_0_deserialized_tmp) =
4646 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4647 default_config: UserConfig::default(),
4648 keys_manager: &keys_manager,
4649 fee_estimator: &fee_estimator,
4650 chain_monitor: nodes[0].chain_monitor,
4651 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4653 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4655 nodes_0_deserialized = nodes_0_deserialized_tmp;
4656 assert!(nodes_0_read.is_empty());
4658 { // Channel close should result in a commitment tx and an HTLC tx
4659 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4660 assert_eq!(txn.len(), 2);
4661 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4662 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4665 for monitor in node_0_monitors.drain(..) {
4666 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4667 check_added_monitors!(nodes[0], 1);
4669 nodes[0].node = &nodes_0_deserialized;
4671 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4672 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4673 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4674 //... and we can even still claim the payment!
4675 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4677 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4678 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4679 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4680 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4681 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4682 assert_eq!(msg_events.len(), 1);
4683 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4685 &ErrorAction::SendErrorMessage { ref msg } => {
4686 assert_eq!(msg.channel_id, channel_id);
4688 _ => panic!("Unexpected event!"),
4693 macro_rules! check_spendable_outputs {
4694 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4696 let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4697 let mut txn = Vec::new();
4698 for event in events {
4700 Event::SpendableOutputs { ref outputs } => {
4701 for outp in outputs {
4703 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4705 previous_output: outpoint.into_bitcoin_outpoint(),
4706 script_sig: Script::new(),
4708 witness: Vec::new(),
4711 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4712 value: output.value,
4714 let mut spend_tx = Transaction {
4720 spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4721 let secp_ctx = Secp256k1::new();
4722 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4723 let remotepubkey = keys.pubkeys().payment_point;
4724 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4725 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4726 let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4727 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4728 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4729 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4732 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4734 previous_output: outpoint.into_bitcoin_outpoint(),
4735 script_sig: Script::new(),
4736 sequence: *to_self_delay as u32,
4737 witness: Vec::new(),
4740 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4741 value: output.value,
4743 let mut spend_tx = Transaction {
4749 let secp_ctx = Secp256k1::new();
4750 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4751 if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4753 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4754 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4755 spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 1 + witness_script.len() + 1 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4756 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4757 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4758 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4759 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4760 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4761 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4765 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4766 let secp_ctx = Secp256k1::new();
4768 previous_output: outpoint.into_bitcoin_outpoint(),
4769 script_sig: Script::new(),
4771 witness: Vec::new(),
4774 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4775 value: output.value,
4777 let mut spend_tx = Transaction {
4781 output: vec![outp.clone()],
4783 spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4785 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4787 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4789 Err(_) => panic!("Your RNG is busted"),
4792 Err(_) => panic!("Your rng is busted"),
4795 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4796 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4797 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4798 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4799 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4800 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4801 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4807 _ => panic!("Unexpected event"),
4816 fn test_claim_sizeable_push_msat() {
4817 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4818 let chanmon_cfgs = create_chanmon_cfgs(2);
4819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4821 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4823 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4824 nodes[1].node.force_close_channel(&chan.2);
4825 check_closed_broadcast!(nodes[1], false);
4826 check_added_monitors!(nodes[1], 1);
4827 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4828 assert_eq!(node_txn.len(), 1);
4829 check_spends!(node_txn[0], chan.3);
4830 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
4832 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4833 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4834 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4836 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4837 assert_eq!(spend_txn.len(), 1);
4838 check_spends!(spend_txn[0], node_txn[0]);
4842 fn test_claim_on_remote_sizeable_push_msat() {
4843 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4844 // to_remote output is encumbered by a P2WPKH
4845 let chanmon_cfgs = create_chanmon_cfgs(2);
4846 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4847 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4848 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4850 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4851 nodes[0].node.force_close_channel(&chan.2);
4852 check_closed_broadcast!(nodes[0], false);
4853 check_added_monitors!(nodes[0], 1);
4855 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4856 assert_eq!(node_txn.len(), 1);
4857 check_spends!(node_txn[0], chan.3);
4858 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
4860 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4861 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4862 check_closed_broadcast!(nodes[1], false);
4863 check_added_monitors!(nodes[1], 1);
4864 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4866 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4867 assert_eq!(spend_txn.len(), 1);
4868 check_spends!(spend_txn[0], node_txn[0]);
4872 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4873 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4874 // to_remote output is encumbered by a P2WPKH
4876 let chanmon_cfgs = create_chanmon_cfgs(2);
4877 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4878 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4879 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4881 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4882 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4883 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4884 assert_eq!(revoked_local_txn[0].input.len(), 1);
4885 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4887 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4888 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4889 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4890 check_closed_broadcast!(nodes[1], false);
4891 check_added_monitors!(nodes[1], 1);
4893 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4894 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4895 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4896 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4898 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4899 assert_eq!(spend_txn.len(), 2);
4900 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4901 check_spends!(spend_txn[1], node_txn[0]);
4905 fn test_static_spendable_outputs_preimage_tx() {
4906 let chanmon_cfgs = create_chanmon_cfgs(2);
4907 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4908 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4909 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4911 // Create some initial channels
4912 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4914 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4916 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4917 assert_eq!(commitment_tx[0].input.len(), 1);
4918 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4920 // Settle A's commitment tx on B's chain
4921 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4922 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4923 check_added_monitors!(nodes[1], 1);
4924 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4925 check_added_monitors!(nodes[1], 1);
4926 let events = nodes[1].node.get_and_clear_pending_msg_events();
4928 MessageSendEvent::UpdateHTLCs { .. } => {},
4929 _ => panic!("Unexpected event"),
4932 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4933 _ => panic!("Unexepected event"),
4936 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4937 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4938 assert_eq!(node_txn.len(), 3);
4939 check_spends!(node_txn[0], commitment_tx[0]);
4940 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4941 check_spends!(node_txn[1], chan_1.3);
4942 check_spends!(node_txn[2], node_txn[1]);
4944 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4945 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4946 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4948 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4949 assert_eq!(spend_txn.len(), 1);
4950 check_spends!(spend_txn[0], node_txn[0]);
4954 fn test_static_spendable_outputs_timeout_tx() {
4955 let chanmon_cfgs = create_chanmon_cfgs(2);
4956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4958 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4960 // Create some initial channels
4961 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4963 // Rebalance the network a bit by relaying one payment through all the channels ...
4964 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4966 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4968 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4969 assert_eq!(commitment_tx[0].input.len(), 1);
4970 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4972 // Settle A's commitment tx on B' chain
4973 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4974 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4975 check_added_monitors!(nodes[1], 1);
4976 let events = nodes[1].node.get_and_clear_pending_msg_events();
4978 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4979 _ => panic!("Unexpected event"),
4982 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4983 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4984 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4985 check_spends!(node_txn[0], commitment_tx[0].clone());
4986 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4987 check_spends!(node_txn[1], chan_1.3.clone());
4988 check_spends!(node_txn[2], node_txn[1]);
4990 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4991 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4992 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4993 expect_payment_failed!(nodes[1], our_payment_hash, true);
4995 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4996 assert_eq!(spend_txn.len(), 2); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4997 check_spends!(spend_txn[1], node_txn[0]);
5001 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
5002 let chanmon_cfgs = create_chanmon_cfgs(2);
5003 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5004 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5005 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5007 // Create some initial channels
5008 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5010 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5011 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5012 assert_eq!(revoked_local_txn[0].input.len(), 1);
5013 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5015 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5017 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5018 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
5019 check_closed_broadcast!(nodes[1], false);
5020 check_added_monitors!(nodes[1], 1);
5022 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5023 assert_eq!(node_txn.len(), 2);
5024 assert_eq!(node_txn[0].input.len(), 2);
5025 check_spends!(node_txn[0], revoked_local_txn[0]);
5027 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5028 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
5029 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5031 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5032 assert_eq!(spend_txn.len(), 1);
5033 check_spends!(spend_txn[0], node_txn[0]);
5037 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
5038 let chanmon_cfgs = create_chanmon_cfgs(2);
5039 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5040 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5041 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5043 // Create some initial channels
5044 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5046 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5047 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5048 assert_eq!(revoked_local_txn[0].input.len(), 1);
5049 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5051 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5053 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5054 // A will generate HTLC-Timeout from revoked commitment tx
5055 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5056 check_closed_broadcast!(nodes[0], false);
5057 check_added_monitors!(nodes[0], 1);
5059 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5060 assert_eq!(revoked_htlc_txn.len(), 2);
5061 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5062 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5063 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5064 check_spends!(revoked_htlc_txn[1], chan_1.3);
5066 // B will generate justice tx from A's revoked commitment/HTLC tx
5067 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5068 check_closed_broadcast!(nodes[1], false);
5069 check_added_monitors!(nodes[1], 1);
5071 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5072 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5073 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5074 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5075 // transactions next...
5076 assert_eq!(node_txn[0].input.len(), 3);
5077 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5079 assert_eq!(node_txn[1].input.len(), 2);
5080 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5081 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5082 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5084 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5085 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5088 assert_eq!(node_txn[2].input.len(), 1);
5089 check_spends!(node_txn[2], chan_1.3);
5091 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5092 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5093 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5095 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5096 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5097 assert_eq!(spend_txn.len(), 1);
5098 assert_eq!(spend_txn[0].input.len(), 1);
5099 check_spends!(spend_txn[0], node_txn[1]);
5103 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5104 let chanmon_cfgs = create_chanmon_cfgs(2);
5105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5107 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5109 // Create some initial channels
5110 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5112 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5113 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5114 assert_eq!(revoked_local_txn[0].input.len(), 1);
5115 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5117 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5118 assert_eq!(revoked_local_txn[0].output.len(), 2);
5120 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5122 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5123 // B will generate HTLC-Success from revoked commitment tx
5124 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5125 check_closed_broadcast!(nodes[1], false);
5126 check_added_monitors!(nodes[1], 1);
5127 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5129 assert_eq!(revoked_htlc_txn.len(), 2);
5130 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5131 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5132 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5134 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5135 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5136 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5138 // A will generate justice tx from B's revoked commitment/HTLC tx
5139 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5140 check_closed_broadcast!(nodes[0], false);
5141 check_added_monitors!(nodes[0], 1);
5143 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5144 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5146 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5147 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5148 // transactions next...
5149 assert_eq!(node_txn[0].input.len(), 2);
5150 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5151 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5152 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5154 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5155 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5158 assert_eq!(node_txn[1].input.len(), 1);
5159 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5161 check_spends!(node_txn[2], chan_1.3);
5163 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5164 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5165 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5167 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5168 // didn't try to generate any new transactions.
5170 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5171 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5172 assert_eq!(spend_txn.len(), 2);
5173 assert_eq!(spend_txn[0].input.len(), 1);
5174 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5175 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5176 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5180 fn test_onchain_to_onchain_claim() {
5181 // Test that in case of channel closure, we detect the state of output and claim HTLC
5182 // on downstream peer's remote commitment tx.
5183 // First, have C claim an HTLC against its own latest commitment transaction.
5184 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5186 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5189 let chanmon_cfgs = create_chanmon_cfgs(3);
5190 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5191 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5192 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5194 // Create some initial channels
5195 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5196 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5198 // Rebalance the network a bit by relaying one payment through all the channels ...
5199 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5200 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5202 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5203 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5204 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5205 check_spends!(commitment_tx[0], chan_2.3);
5206 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5207 check_added_monitors!(nodes[2], 1);
5208 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5209 assert!(updates.update_add_htlcs.is_empty());
5210 assert!(updates.update_fail_htlcs.is_empty());
5211 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5212 assert!(updates.update_fail_malformed_htlcs.is_empty());
5214 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5215 check_closed_broadcast!(nodes[2], false);
5216 check_added_monitors!(nodes[2], 1);
5218 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5219 assert_eq!(c_txn.len(), 3);
5220 assert_eq!(c_txn[0], c_txn[2]);
5221 assert_eq!(commitment_tx[0], c_txn[1]);
5222 check_spends!(c_txn[1], chan_2.3);
5223 check_spends!(c_txn[2], c_txn[1]);
5224 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5225 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5226 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5227 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5229 // 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
5230 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5232 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5233 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5234 assert_eq!(b_txn.len(), 3);
5235 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5236 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5237 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5238 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5239 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5240 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5241 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5242 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5243 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5246 check_added_monitors!(nodes[1], 1);
5247 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5248 check_added_monitors!(nodes[1], 1);
5249 match msg_events[0] {
5250 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5251 _ => panic!("Unexpected event"),
5253 match msg_events[1] {
5254 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, .. } } => {
5255 assert!(update_add_htlcs.is_empty());
5256 assert!(update_fail_htlcs.is_empty());
5257 assert_eq!(update_fulfill_htlcs.len(), 1);
5258 assert!(update_fail_malformed_htlcs.is_empty());
5259 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5261 _ => panic!("Unexpected event"),
5263 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5264 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5265 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5266 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5267 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5268 assert_eq!(b_txn.len(), 3);
5269 check_spends!(b_txn[1], chan_1.3);
5270 check_spends!(b_txn[2], b_txn[1]);
5271 check_spends!(b_txn[0], commitment_tx[0]);
5272 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5273 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5274 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5276 check_closed_broadcast!(nodes[1], false);
5277 check_added_monitors!(nodes[1], 1);
5281 fn test_duplicate_payment_hash_one_failure_one_success() {
5282 // Topology : A --> B --> C
5283 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5284 let chanmon_cfgs = create_chanmon_cfgs(3);
5285 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5286 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5287 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5289 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5290 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5292 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5293 *nodes[0].network_payment_count.borrow_mut() -= 1;
5294 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5296 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5297 assert_eq!(commitment_txn[0].input.len(), 1);
5298 check_spends!(commitment_txn[0], chan_2.3);
5300 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5301 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5302 check_closed_broadcast!(nodes[1], false);
5303 check_added_monitors!(nodes[1], 1);
5305 let htlc_timeout_tx;
5306 { // Extract one of the two HTLC-Timeout transaction
5307 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5308 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5309 assert_eq!(node_txn.len(), 5);
5310 check_spends!(node_txn[0], commitment_txn[0]);
5311 assert_eq!(node_txn[0].input.len(), 1);
5312 check_spends!(node_txn[1], commitment_txn[0]);
5313 assert_eq!(node_txn[1].input.len(), 1);
5314 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5315 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5316 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5317 check_spends!(node_txn[2], chan_2.3);
5318 check_spends!(node_txn[3], node_txn[2]);
5319 check_spends!(node_txn[4], node_txn[2]);
5320 htlc_timeout_tx = node_txn[1].clone();
5323 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5324 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5325 check_added_monitors!(nodes[2], 3);
5326 let events = nodes[2].node.get_and_clear_pending_msg_events();
5328 MessageSendEvent::UpdateHTLCs { .. } => {},
5329 _ => panic!("Unexpected event"),
5332 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5333 _ => panic!("Unexepected event"),
5335 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5336 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)
5337 check_spends!(htlc_success_txn[2], chan_2.3);
5338 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5339 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5340 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5341 assert_eq!(htlc_success_txn[0].input.len(), 1);
5342 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5343 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5344 assert_eq!(htlc_success_txn[1].input.len(), 1);
5345 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5346 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5347 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5348 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5350 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5351 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5352 expect_pending_htlcs_forwardable!(nodes[1]);
5353 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5354 assert!(htlc_updates.update_add_htlcs.is_empty());
5355 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5356 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5357 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5358 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5359 check_added_monitors!(nodes[1], 1);
5361 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5362 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5364 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5365 let events = nodes[0].node.get_and_clear_pending_msg_events();
5366 assert_eq!(events.len(), 1);
5368 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5370 _ => { panic!("Unexpected event"); }
5373 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5375 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5376 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5377 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5378 assert!(updates.update_add_htlcs.is_empty());
5379 assert!(updates.update_fail_htlcs.is_empty());
5380 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5381 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5382 assert!(updates.update_fail_malformed_htlcs.is_empty());
5383 check_added_monitors!(nodes[1], 1);
5385 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5386 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5388 let events = nodes[0].node.get_and_clear_pending_events();
5390 Event::PaymentSent { ref payment_preimage } => {
5391 assert_eq!(*payment_preimage, our_payment_preimage);
5393 _ => panic!("Unexpected event"),
5398 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5399 let chanmon_cfgs = create_chanmon_cfgs(2);
5400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5404 // Create some initial channels
5405 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5407 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5408 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5409 assert_eq!(local_txn[0].input.len(), 1);
5410 check_spends!(local_txn[0], chan_1.3);
5412 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5413 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5414 check_added_monitors!(nodes[1], 1);
5415 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5416 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5417 check_added_monitors!(nodes[1], 1);
5418 let events = nodes[1].node.get_and_clear_pending_msg_events();
5420 MessageSendEvent::UpdateHTLCs { .. } => {},
5421 _ => panic!("Unexpected event"),
5424 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5425 _ => panic!("Unexepected event"),
5428 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5429 assert_eq!(node_txn[0].input.len(), 1);
5430 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5431 check_spends!(node_txn[0], local_txn[0]);
5432 vec![node_txn[0].clone(), node_txn[2].clone()]
5435 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5436 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5437 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5439 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5440 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5441 assert_eq!(spend_txn.len(), 2);
5442 check_spends!(spend_txn[0], node_txn[0]);
5443 check_spends!(spend_txn[1], node_txn[1]);
5446 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5447 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5448 // unrevoked commitment transaction.
5449 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5450 // a remote RAA before they could be failed backwards (and combinations thereof).
5451 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5452 // use the same payment hashes.
5453 // Thus, we use a six-node network:
5458 // And test where C fails back to A/B when D announces its latest commitment transaction
5459 let chanmon_cfgs = create_chanmon_cfgs(6);
5460 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5461 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5462 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5463 let logger = test_utils::TestLogger::new();
5465 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5466 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5467 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5468 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5469 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5471 // Rebalance and check output sanity...
5472 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5473 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5474 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5476 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5478 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
5480 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
5481 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5482 let our_node_id = &nodes[1].node.get_our_node_id();
5483 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();
5485 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
5487 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
5489 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5491 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5492 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();
5494 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5496 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5499 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5501 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5502 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
5505 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
5507 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();
5508 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5510 // Double-check that six of the new HTLC were added
5511 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5512 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5513 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5514 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5516 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5517 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5518 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5519 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5520 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5521 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5522 check_added_monitors!(nodes[4], 0);
5523 expect_pending_htlcs_forwardable!(nodes[4]);
5524 check_added_monitors!(nodes[4], 1);
5526 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5527 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5528 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5529 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5530 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5531 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5533 // Fail 3rd below-dust and 7th above-dust HTLCs
5534 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5535 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5536 check_added_monitors!(nodes[5], 0);
5537 expect_pending_htlcs_forwardable!(nodes[5]);
5538 check_added_monitors!(nodes[5], 1);
5540 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5541 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5542 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5543 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5545 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5547 expect_pending_htlcs_forwardable!(nodes[3]);
5548 check_added_monitors!(nodes[3], 1);
5549 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5550 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5551 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5552 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5553 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5554 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5555 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5556 if deliver_last_raa {
5557 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5559 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5562 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5563 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5564 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5565 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5567 // We now broadcast the latest commitment transaction, which *should* result in failures for
5568 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5569 // the non-broadcast above-dust HTLCs.
5571 // Alternatively, we may broadcast the previous commitment transaction, which should only
5572 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5573 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5575 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5576 if announce_latest {
5577 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5579 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5581 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5582 check_closed_broadcast!(nodes[2], false);
5583 expect_pending_htlcs_forwardable!(nodes[2]);
5584 check_added_monitors!(nodes[2], 3);
5586 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5587 assert_eq!(cs_msgs.len(), 2);
5588 let mut a_done = false;
5589 for msg in cs_msgs {
5591 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5592 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5593 // should be failed-backwards here.
5594 let target = if *node_id == nodes[0].node.get_our_node_id() {
5595 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5596 for htlc in &updates.update_fail_htlcs {
5597 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 });
5599 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5604 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5605 for htlc in &updates.update_fail_htlcs {
5606 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5608 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5609 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5612 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5613 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5614 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5615 if announce_latest {
5616 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5617 if *node_id == nodes[0].node.get_our_node_id() {
5618 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5621 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5623 _ => panic!("Unexpected event"),
5627 let as_events = nodes[0].node.get_and_clear_pending_events();
5628 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5629 let mut as_failds = HashSet::new();
5630 for event in as_events.iter() {
5631 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5632 assert!(as_failds.insert(*payment_hash));
5633 if *payment_hash != payment_hash_2 {
5634 assert_eq!(*rejected_by_dest, deliver_last_raa);
5636 assert!(!rejected_by_dest);
5638 } else { panic!("Unexpected event"); }
5640 assert!(as_failds.contains(&payment_hash_1));
5641 assert!(as_failds.contains(&payment_hash_2));
5642 if announce_latest {
5643 assert!(as_failds.contains(&payment_hash_3));
5644 assert!(as_failds.contains(&payment_hash_5));
5646 assert!(as_failds.contains(&payment_hash_6));
5648 let bs_events = nodes[1].node.get_and_clear_pending_events();
5649 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5650 let mut bs_failds = HashSet::new();
5651 for event in bs_events.iter() {
5652 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5653 assert!(bs_failds.insert(*payment_hash));
5654 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5655 assert_eq!(*rejected_by_dest, deliver_last_raa);
5657 assert!(!rejected_by_dest);
5659 } else { panic!("Unexpected event"); }
5661 assert!(bs_failds.contains(&payment_hash_1));
5662 assert!(bs_failds.contains(&payment_hash_2));
5663 if announce_latest {
5664 assert!(bs_failds.contains(&payment_hash_4));
5666 assert!(bs_failds.contains(&payment_hash_5));
5668 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5669 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5670 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5671 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5672 // PaymentFailureNetworkUpdates.
5673 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5674 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5675 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5676 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5677 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5679 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5680 _ => panic!("Unexpected event"),
5686 fn test_fail_backwards_latest_remote_announce_a() {
5687 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5691 fn test_fail_backwards_latest_remote_announce_b() {
5692 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5696 fn test_fail_backwards_previous_remote_announce() {
5697 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5698 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5699 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5703 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5704 let chanmon_cfgs = create_chanmon_cfgs(2);
5705 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5706 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5707 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5709 // Create some initial channels
5710 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5712 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5713 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5714 assert_eq!(local_txn[0].input.len(), 1);
5715 check_spends!(local_txn[0], chan_1.3);
5717 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5718 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5719 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5720 check_closed_broadcast!(nodes[0], false);
5721 check_added_monitors!(nodes[0], 1);
5723 let htlc_timeout = {
5724 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5725 assert_eq!(node_txn[0].input.len(), 1);
5726 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5727 check_spends!(node_txn[0], local_txn[0]);
5731 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5732 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5733 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5734 expect_payment_failed!(nodes[0], our_payment_hash, true);
5736 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5737 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5738 assert_eq!(spend_txn.len(), 2);
5739 check_spends!(spend_txn[0], local_txn[0]);
5740 check_spends!(spend_txn[1], htlc_timeout);
5744 fn test_key_derivation_params() {
5745 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5746 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5747 // let us re-derive the channel key set to then derive a delayed_payment_key.
5749 let chanmon_cfgs = create_chanmon_cfgs(3);
5751 // We manually create the node configuration to backup the seed.
5752 let seed = [42; 32];
5753 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5754 let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister);
5755 let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, chain_monitor, keys_manager, node_seed: seed };
5756 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5757 node_cfgs.remove(0);
5758 node_cfgs.insert(0, node);
5760 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5761 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5763 // Create some initial channels
5764 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5766 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5767 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5768 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5770 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5771 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5772 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5773 assert_eq!(local_txn_1[0].input.len(), 1);
5774 check_spends!(local_txn_1[0], chan_1.3);
5776 // We check funding pubkey are unique
5777 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]));
5778 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]));
5779 if from_0_funding_key_0 == from_1_funding_key_0
5780 || from_0_funding_key_0 == from_1_funding_key_1
5781 || from_0_funding_key_1 == from_1_funding_key_0
5782 || from_0_funding_key_1 == from_1_funding_key_1 {
5783 panic!("Funding pubkeys aren't unique");
5786 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5787 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5788 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5789 check_closed_broadcast!(nodes[0], false);
5790 check_added_monitors!(nodes[0], 1);
5792 let htlc_timeout = {
5793 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5794 assert_eq!(node_txn[0].input.len(), 1);
5795 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5796 check_spends!(node_txn[0], local_txn_1[0]);
5800 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5801 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5802 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5803 expect_payment_failed!(nodes[0], our_payment_hash, true);
5805 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5806 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5807 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5808 assert_eq!(spend_txn.len(), 2);
5809 check_spends!(spend_txn[0], local_txn_1[0]);
5810 check_spends!(spend_txn[1], htlc_timeout);
5814 fn test_static_output_closing_tx() {
5815 let chanmon_cfgs = create_chanmon_cfgs(2);
5816 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5817 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5818 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5820 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5822 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5823 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5825 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5826 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5827 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5829 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5830 assert_eq!(spend_txn.len(), 1);
5831 check_spends!(spend_txn[0], closing_tx);
5833 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5834 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5836 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5837 assert_eq!(spend_txn.len(), 1);
5838 check_spends!(spend_txn[0], closing_tx);
5841 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5842 let chanmon_cfgs = create_chanmon_cfgs(2);
5843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5845 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5846 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5848 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5850 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5851 // present in B's local commitment transaction, but none of A's commitment transactions.
5852 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5853 check_added_monitors!(nodes[1], 1);
5855 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5856 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5857 let events = nodes[0].node.get_and_clear_pending_events();
5858 assert_eq!(events.len(), 1);
5860 Event::PaymentSent { payment_preimage } => {
5861 assert_eq!(payment_preimage, our_payment_preimage);
5863 _ => panic!("Unexpected event"),
5866 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5867 check_added_monitors!(nodes[0], 1);
5868 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5869 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5870 check_added_monitors!(nodes[1], 1);
5872 let mut block = Block {
5873 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5876 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5877 connect_block(&nodes[1], &block, i);
5878 block.header.prev_blockhash = block.block_hash();
5880 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5881 check_closed_broadcast!(nodes[1], false);
5882 check_added_monitors!(nodes[1], 1);
5885 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5886 let chanmon_cfgs = create_chanmon_cfgs(2);
5887 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5888 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5889 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5890 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5891 let logger = test_utils::TestLogger::new();
5893 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5894 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5895 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();
5896 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5897 check_added_monitors!(nodes[0], 1);
5899 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5901 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5902 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5903 // to "time out" the HTLC.
5905 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5907 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5908 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5909 header.prev_blockhash = header.block_hash();
5911 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5912 check_closed_broadcast!(nodes[0], false);
5913 check_added_monitors!(nodes[0], 1);
5916 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5917 let chanmon_cfgs = create_chanmon_cfgs(3);
5918 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5919 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5920 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5921 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5923 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5924 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5925 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5926 // actually revoked.
5927 let htlc_value = if use_dust { 50000 } else { 3000000 };
5928 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5929 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5930 expect_pending_htlcs_forwardable!(nodes[1]);
5931 check_added_monitors!(nodes[1], 1);
5933 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5934 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5935 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5936 check_added_monitors!(nodes[0], 1);
5937 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5938 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5939 check_added_monitors!(nodes[1], 1);
5940 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5941 check_added_monitors!(nodes[1], 1);
5942 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5944 if check_revoke_no_close {
5945 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5946 check_added_monitors!(nodes[0], 1);
5949 let mut block = Block {
5950 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5953 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5954 connect_block(&nodes[0], &block, i);
5955 block.header.prev_blockhash = block.block_hash();
5957 if !check_revoke_no_close {
5958 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5959 check_closed_broadcast!(nodes[0], false);
5960 check_added_monitors!(nodes[0], 1);
5962 expect_payment_failed!(nodes[0], our_payment_hash, true);
5966 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5967 // There are only a few cases to test here:
5968 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5969 // broadcastable commitment transactions result in channel closure,
5970 // * its included in an unrevoked-but-previous remote commitment transaction,
5971 // * its included in the latest remote or local commitment transactions.
5972 // We test each of the three possible commitment transactions individually and use both dust and
5974 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5975 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5976 // tested for at least one of the cases in other tests.
5978 fn htlc_claim_single_commitment_only_a() {
5979 do_htlc_claim_local_commitment_only(true);
5980 do_htlc_claim_local_commitment_only(false);
5982 do_htlc_claim_current_remote_commitment_only(true);
5983 do_htlc_claim_current_remote_commitment_only(false);
5987 fn htlc_claim_single_commitment_only_b() {
5988 do_htlc_claim_previous_remote_commitment_only(true, false);
5989 do_htlc_claim_previous_remote_commitment_only(false, false);
5990 do_htlc_claim_previous_remote_commitment_only(true, true);
5991 do_htlc_claim_previous_remote_commitment_only(false, true);
5996 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5997 let chanmon_cfgs = create_chanmon_cfgs(2);
5998 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5999 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6000 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6001 //Force duplicate channel ids
6002 for node in nodes.iter() {
6003 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
6006 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
6007 let channel_value_satoshis=10000;
6008 let push_msat=10001;
6009 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
6010 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6011 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
6013 //Create a second channel with a channel_id collision
6014 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6018 fn bolt2_open_channel_sending_node_checks_part2() {
6019 let chanmon_cfgs = create_chanmon_cfgs(2);
6020 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6021 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6022 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6024 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
6025 let channel_value_satoshis=2^24;
6026 let push_msat=10001;
6027 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6029 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
6030 let channel_value_satoshis=10000;
6031 // Test when push_msat is equal to 1000 * funding_satoshis.
6032 let push_msat=1000*channel_value_satoshis+1;
6033 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
6035 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
6036 let channel_value_satoshis=10000;
6037 let push_msat=10001;
6038 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
6039 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
6040 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6042 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6043 // 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
6044 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6046 // 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.
6047 assert!(BREAKDOWN_TIMEOUT>0);
6048 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6050 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6051 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6052 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6054 // 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.
6055 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6056 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6057 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6058 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6059 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6062 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6063 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6064 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6065 // is no longer affordable once it's freed.
6067 fn test_fail_holding_cell_htlc_upon_free() {
6068 let chanmon_cfgs = create_chanmon_cfgs(2);
6069 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6070 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6071 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6072 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6073 let logger = test_utils::TestLogger::new();
6075 // First nodes[0] generates an update_fee, setting the channel's
6076 // pending_update_fee.
6077 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6078 check_added_monitors!(nodes[0], 1);
6080 let events = nodes[0].node.get_and_clear_pending_msg_events();
6081 assert_eq!(events.len(), 1);
6082 let (update_msg, commitment_signed) = match events[0] {
6083 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6084 (update_fee.as_ref(), commitment_signed)
6086 _ => panic!("Unexpected event"),
6089 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6091 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6092 let channel_reserve = chan_stat.channel_reserve_msat;
6093 let feerate = get_feerate!(nodes[0], chan.2);
6095 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6096 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6097 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6098 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6099 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();
6101 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6102 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6103 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6104 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6106 // Flush the pending fee update.
6107 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6108 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6109 check_added_monitors!(nodes[1], 1);
6110 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6111 check_added_monitors!(nodes[0], 1);
6113 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6114 // HTLC, but now that the fee has been raised the payment will now fail, causing
6115 // us to surface its failure to the user.
6116 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6117 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6118 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6119 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);
6120 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6122 // Check that the payment failed to be sent out.
6123 let events = nodes[0].node.get_and_clear_pending_events();
6124 assert_eq!(events.len(), 1);
6126 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6127 assert_eq!(our_payment_hash.clone(), *payment_hash);
6128 assert_eq!(*rejected_by_dest, false);
6129 assert_eq!(*error_code, None);
6130 assert_eq!(*error_data, None);
6132 _ => panic!("Unexpected event"),
6136 // Test that if multiple HTLCs are released from the holding cell and one is
6137 // valid but the other is no longer valid upon release, the valid HTLC can be
6138 // successfully completed while the other one fails as expected.
6140 fn test_free_and_fail_holding_cell_htlcs() {
6141 let chanmon_cfgs = create_chanmon_cfgs(2);
6142 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6143 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6144 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6145 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6146 let logger = test_utils::TestLogger::new();
6148 // First nodes[0] generates an update_fee, setting the channel's
6149 // pending_update_fee.
6150 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6151 check_added_monitors!(nodes[0], 1);
6153 let events = nodes[0].node.get_and_clear_pending_msg_events();
6154 assert_eq!(events.len(), 1);
6155 let (update_msg, commitment_signed) = match events[0] {
6156 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6157 (update_fee.as_ref(), commitment_signed)
6159 _ => panic!("Unexpected event"),
6162 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6164 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6165 let channel_reserve = chan_stat.channel_reserve_msat;
6166 let feerate = get_feerate!(nodes[0], chan.2);
6168 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6169 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6171 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6172 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6173 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6174 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();
6175 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();
6177 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6178 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6179 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6180 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6181 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6182 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6183 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6185 // Flush the pending fee update.
6186 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6187 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6188 check_added_monitors!(nodes[1], 1);
6189 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6190 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6191 check_added_monitors!(nodes[0], 2);
6193 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6194 // but now that the fee has been raised the second payment will now fail, causing us
6195 // to surface its failure to the user. The first payment should succeed.
6196 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6197 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6198 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6199 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);
6200 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6202 // Check that the second payment failed to be sent out.
6203 let events = nodes[0].node.get_and_clear_pending_events();
6204 assert_eq!(events.len(), 1);
6206 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6207 assert_eq!(payment_hash_2.clone(), *payment_hash);
6208 assert_eq!(*rejected_by_dest, false);
6209 assert_eq!(*error_code, None);
6210 assert_eq!(*error_data, None);
6212 _ => panic!("Unexpected event"),
6215 // Complete the first payment and the RAA from the fee update.
6216 let (payment_event, send_raa_event) = {
6217 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6218 assert_eq!(msgs.len(), 2);
6219 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6221 let raa = match send_raa_event {
6222 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6223 _ => panic!("Unexpected event"),
6225 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6226 check_added_monitors!(nodes[1], 1);
6227 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6228 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6229 let events = nodes[1].node.get_and_clear_pending_events();
6230 assert_eq!(events.len(), 1);
6232 Event::PendingHTLCsForwardable { .. } => {},
6233 _ => panic!("Unexpected event"),
6235 nodes[1].node.process_pending_htlc_forwards();
6236 let events = nodes[1].node.get_and_clear_pending_events();
6237 assert_eq!(events.len(), 1);
6239 Event::PaymentReceived { .. } => {},
6240 _ => panic!("Unexpected event"),
6242 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6243 check_added_monitors!(nodes[1], 1);
6244 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6245 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6246 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6247 let events = nodes[0].node.get_and_clear_pending_events();
6248 assert_eq!(events.len(), 1);
6250 Event::PaymentSent { ref payment_preimage } => {
6251 assert_eq!(*payment_preimage, payment_preimage_1);
6253 _ => panic!("Unexpected event"),
6257 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6258 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6259 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6262 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6263 let chanmon_cfgs = create_chanmon_cfgs(3);
6264 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6265 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6266 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6267 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6268 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6269 let logger = test_utils::TestLogger::new();
6271 // First nodes[1] generates an update_fee, setting the channel's
6272 // pending_update_fee.
6273 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6274 check_added_monitors!(nodes[1], 1);
6276 let events = nodes[1].node.get_and_clear_pending_msg_events();
6277 assert_eq!(events.len(), 1);
6278 let (update_msg, commitment_signed) = match events[0] {
6279 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6280 (update_fee.as_ref(), commitment_signed)
6282 _ => panic!("Unexpected event"),
6285 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6287 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6288 let channel_reserve = chan_stat.channel_reserve_msat;
6289 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6291 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6293 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6294 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6295 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6296 let payment_event = {
6297 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6298 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();
6299 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6300 check_added_monitors!(nodes[0], 1);
6302 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6303 assert_eq!(events.len(), 1);
6305 SendEvent::from_event(events.remove(0))
6307 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6308 check_added_monitors!(nodes[1], 0);
6309 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6310 expect_pending_htlcs_forwardable!(nodes[1]);
6312 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6313 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6315 // Flush the pending fee update.
6316 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6317 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6318 check_added_monitors!(nodes[2], 1);
6319 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6320 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6321 check_added_monitors!(nodes[1], 2);
6323 // A final RAA message is generated to finalize the fee update.
6324 let events = nodes[1].node.get_and_clear_pending_msg_events();
6325 assert_eq!(events.len(), 1);
6327 let raa_msg = match &events[0] {
6328 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6331 _ => panic!("Unexpected event"),
6334 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6335 check_added_monitors!(nodes[2], 1);
6336 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6338 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6339 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6340 assert_eq!(process_htlc_forwards_event.len(), 1);
6341 match &process_htlc_forwards_event[0] {
6342 &Event::PendingHTLCsForwardable { .. } => {},
6343 _ => panic!("Unexpected event"),
6346 // In response, we call ChannelManager's process_pending_htlc_forwards
6347 nodes[1].node.process_pending_htlc_forwards();
6348 check_added_monitors!(nodes[1], 1);
6350 // This causes the HTLC to be failed backwards.
6351 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6352 assert_eq!(fail_event.len(), 1);
6353 let (fail_msg, commitment_signed) = match &fail_event[0] {
6354 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6355 assert_eq!(updates.update_add_htlcs.len(), 0);
6356 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6357 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6358 assert_eq!(updates.update_fail_htlcs.len(), 1);
6359 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6361 _ => panic!("Unexpected event"),
6364 // Pass the failure messages back to nodes[0].
6365 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6366 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6368 // Complete the HTLC failure+removal process.
6369 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6370 check_added_monitors!(nodes[0], 1);
6371 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6372 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6373 check_added_monitors!(nodes[1], 2);
6374 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6375 assert_eq!(final_raa_event.len(), 1);
6376 let raa = match &final_raa_event[0] {
6377 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6378 _ => panic!("Unexpected event"),
6380 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6381 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6382 assert_eq!(fail_msg_event.len(), 1);
6383 match &fail_msg_event[0] {
6384 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6385 _ => panic!("Unexpected event"),
6387 let failure_event = nodes[0].node.get_and_clear_pending_events();
6388 assert_eq!(failure_event.len(), 1);
6389 match &failure_event[0] {
6390 &Event::PaymentFailed { rejected_by_dest, .. } => {
6391 assert!(!rejected_by_dest);
6393 _ => panic!("Unexpected event"),
6395 check_added_monitors!(nodes[0], 1);
6398 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6399 // 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.
6400 //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.
6403 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6404 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6405 let chanmon_cfgs = create_chanmon_cfgs(2);
6406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6408 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6409 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6411 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6412 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6413 let logger = test_utils::TestLogger::new();
6414 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();
6415 route.paths[0][0].fee_msat = 100;
6417 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6418 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6419 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6420 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6424 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6425 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6426 let chanmon_cfgs = create_chanmon_cfgs(2);
6427 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6428 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6429 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6430 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6431 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6433 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6434 let logger = test_utils::TestLogger::new();
6435 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();
6436 route.paths[0][0].fee_msat = 0;
6437 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6438 assert_eq!(err, "Cannot send 0-msat HTLC"));
6440 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6441 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6445 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6446 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6447 let chanmon_cfgs = create_chanmon_cfgs(2);
6448 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6449 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6450 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6451 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6453 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6454 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6455 let logger = test_utils::TestLogger::new();
6456 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();
6457 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6458 check_added_monitors!(nodes[0], 1);
6459 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6460 updates.update_add_htlcs[0].amount_msat = 0;
6462 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6463 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6464 check_closed_broadcast!(nodes[1], true).unwrap();
6465 check_added_monitors!(nodes[1], 1);
6469 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6470 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6471 //It is enforced when constructing a route.
6472 let chanmon_cfgs = create_chanmon_cfgs(2);
6473 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6474 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6475 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6476 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6477 let logger = test_utils::TestLogger::new();
6479 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6481 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6482 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();
6483 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6484 assert_eq!(err, &"Channel CLTV overflowed?"));
6488 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6489 //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.
6490 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6491 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6492 let chanmon_cfgs = create_chanmon_cfgs(2);
6493 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6494 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6495 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6496 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6497 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6499 let logger = test_utils::TestLogger::new();
6500 for i in 0..max_accepted_htlcs {
6501 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6502 let payment_event = {
6503 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6504 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();
6505 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6506 check_added_monitors!(nodes[0], 1);
6508 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6509 assert_eq!(events.len(), 1);
6510 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6511 assert_eq!(htlcs[0].htlc_id, i);
6515 SendEvent::from_event(events.remove(0))
6517 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6518 check_added_monitors!(nodes[1], 0);
6519 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6521 expect_pending_htlcs_forwardable!(nodes[1]);
6522 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6524 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6525 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6526 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();
6527 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6528 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6530 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6531 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6535 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6536 //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.
6537 let chanmon_cfgs = create_chanmon_cfgs(2);
6538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6540 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6541 let channel_value = 100000;
6542 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6543 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6545 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6547 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6548 // Manually create a route over our max in flight (which our router normally automatically
6550 let route = Route { paths: vec![vec![RouteHop {
6551 pubkey: nodes[1].node.get_our_node_id(), node_features: NodeFeatures::known(), channel_features: ChannelFeatures::known(),
6552 short_channel_id: nodes[1].node.list_usable_channels()[0].short_channel_id.unwrap(),
6553 fee_msat: max_in_flight + 1, cltv_expiry_delta: TEST_FINAL_CLTV
6555 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6556 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)));
6558 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6559 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);
6561 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6564 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6566 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6567 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6568 let chanmon_cfgs = create_chanmon_cfgs(2);
6569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6571 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6572 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6573 let htlc_minimum_msat: u64;
6575 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6576 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6577 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6580 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6581 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6582 let logger = test_utils::TestLogger::new();
6583 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();
6584 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6585 check_added_monitors!(nodes[0], 1);
6586 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6587 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6588 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6589 assert!(nodes[1].node.list_channels().is_empty());
6590 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6591 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()));
6592 check_added_monitors!(nodes[1], 1);
6596 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6597 //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
6598 let chanmon_cfgs = create_chanmon_cfgs(2);
6599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6602 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6603 let logger = test_utils::TestLogger::new();
6605 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6606 let channel_reserve = chan_stat.channel_reserve_msat;
6607 let feerate = get_feerate!(nodes[0], chan.2);
6608 // The 2* and +1 are for the fee spike reserve.
6609 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6611 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6612 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6613 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6614 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();
6615 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6616 check_added_monitors!(nodes[0], 1);
6617 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6619 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6620 // at this time channel-initiatee receivers are not required to enforce that senders
6621 // respect the fee_spike_reserve.
6622 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6623 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6625 assert!(nodes[1].node.list_channels().is_empty());
6626 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6627 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6628 check_added_monitors!(nodes[1], 1);
6632 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6633 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6634 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6635 let chanmon_cfgs = create_chanmon_cfgs(2);
6636 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6637 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6638 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6639 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6640 let logger = test_utils::TestLogger::new();
6642 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6643 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6645 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6646 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();
6648 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6649 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6650 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6651 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6653 let mut msg = msgs::UpdateAddHTLC {
6657 payment_hash: our_payment_hash,
6658 cltv_expiry: htlc_cltv,
6659 onion_routing_packet: onion_packet.clone(),
6662 for i in 0..super::channel::OUR_MAX_HTLCS {
6663 msg.htlc_id = i as u64;
6664 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6666 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6667 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6669 assert!(nodes[1].node.list_channels().is_empty());
6670 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6671 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6672 check_added_monitors!(nodes[1], 1);
6676 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6677 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6678 let chanmon_cfgs = create_chanmon_cfgs(2);
6679 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6680 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6681 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6682 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6683 let logger = test_utils::TestLogger::new();
6685 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6686 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6687 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();
6688 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6689 check_added_monitors!(nodes[0], 1);
6690 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6691 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6692 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6694 assert!(nodes[1].node.list_channels().is_empty());
6695 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6696 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6697 check_added_monitors!(nodes[1], 1);
6701 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6702 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6703 let chanmon_cfgs = create_chanmon_cfgs(2);
6704 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6705 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6706 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6707 let logger = test_utils::TestLogger::new();
6709 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6710 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6711 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6712 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();
6713 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6714 check_added_monitors!(nodes[0], 1);
6715 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6716 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6717 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6719 assert!(nodes[1].node.list_channels().is_empty());
6720 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6721 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6722 check_added_monitors!(nodes[1], 1);
6726 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6727 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6728 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6729 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6730 let chanmon_cfgs = create_chanmon_cfgs(2);
6731 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6732 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6733 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6734 let logger = test_utils::TestLogger::new();
6736 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6737 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6738 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6739 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();
6740 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6741 check_added_monitors!(nodes[0], 1);
6742 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6743 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6745 //Disconnect and Reconnect
6746 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6747 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6748 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6749 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6750 assert_eq!(reestablish_1.len(), 1);
6751 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6752 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6753 assert_eq!(reestablish_2.len(), 1);
6754 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6755 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6756 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6757 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6760 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6761 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6762 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6763 check_added_monitors!(nodes[1], 1);
6764 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6766 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6768 assert!(nodes[1].node.list_channels().is_empty());
6769 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6770 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6771 check_added_monitors!(nodes[1], 1);
6775 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6776 //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.
6778 let chanmon_cfgs = create_chanmon_cfgs(2);
6779 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6780 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6781 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6782 let logger = test_utils::TestLogger::new();
6783 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6784 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6785 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6786 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6787 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6789 check_added_monitors!(nodes[0], 1);
6790 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6791 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6793 let update_msg = msgs::UpdateFulfillHTLC{
6796 payment_preimage: our_payment_preimage,
6799 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6801 assert!(nodes[0].node.list_channels().is_empty());
6802 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6803 assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6804 check_added_monitors!(nodes[0], 1);
6808 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6809 //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.
6811 let chanmon_cfgs = create_chanmon_cfgs(2);
6812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6814 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6815 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6816 let logger = test_utils::TestLogger::new();
6818 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6819 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6820 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();
6821 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6822 check_added_monitors!(nodes[0], 1);
6823 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6824 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6826 let update_msg = msgs::UpdateFailHTLC{
6829 reason: msgs::OnionErrorPacket { data: Vec::new()},
6832 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6834 assert!(nodes[0].node.list_channels().is_empty());
6835 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6836 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()));
6837 check_added_monitors!(nodes[0], 1);
6841 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6842 //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.
6844 let chanmon_cfgs = create_chanmon_cfgs(2);
6845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6847 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6848 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6849 let logger = test_utils::TestLogger::new();
6851 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6852 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6853 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();
6854 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6855 check_added_monitors!(nodes[0], 1);
6856 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6857 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6859 let update_msg = msgs::UpdateFailMalformedHTLC{
6862 sha256_of_onion: [1; 32],
6863 failure_code: 0x8000,
6866 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6868 assert!(nodes[0].node.list_channels().is_empty());
6869 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6870 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()));
6871 check_added_monitors!(nodes[0], 1);
6875 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6876 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6878 let chanmon_cfgs = create_chanmon_cfgs(2);
6879 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6880 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6881 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6882 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6884 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6886 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6887 check_added_monitors!(nodes[1], 1);
6889 let events = nodes[1].node.get_and_clear_pending_msg_events();
6890 assert_eq!(events.len(), 1);
6891 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6893 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, .. } } => {
6894 assert!(update_add_htlcs.is_empty());
6895 assert_eq!(update_fulfill_htlcs.len(), 1);
6896 assert!(update_fail_htlcs.is_empty());
6897 assert!(update_fail_malformed_htlcs.is_empty());
6898 assert!(update_fee.is_none());
6899 update_fulfill_htlcs[0].clone()
6901 _ => panic!("Unexpected event"),
6905 update_fulfill_msg.htlc_id = 1;
6907 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6909 assert!(nodes[0].node.list_channels().is_empty());
6910 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6911 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6912 check_added_monitors!(nodes[0], 1);
6916 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6917 //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.
6919 let chanmon_cfgs = create_chanmon_cfgs(2);
6920 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6921 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6922 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6923 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6925 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6927 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6928 check_added_monitors!(nodes[1], 1);
6930 let events = nodes[1].node.get_and_clear_pending_msg_events();
6931 assert_eq!(events.len(), 1);
6932 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6934 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, .. } } => {
6935 assert!(update_add_htlcs.is_empty());
6936 assert_eq!(update_fulfill_htlcs.len(), 1);
6937 assert!(update_fail_htlcs.is_empty());
6938 assert!(update_fail_malformed_htlcs.is_empty());
6939 assert!(update_fee.is_none());
6940 update_fulfill_htlcs[0].clone()
6942 _ => panic!("Unexpected event"),
6946 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6948 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6950 assert!(nodes[0].node.list_channels().is_empty());
6951 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6952 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6953 check_added_monitors!(nodes[0], 1);
6957 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6958 //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.
6960 let chanmon_cfgs = create_chanmon_cfgs(2);
6961 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6962 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6963 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6964 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6965 let logger = test_utils::TestLogger::new();
6967 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6968 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6969 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();
6970 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6971 check_added_monitors!(nodes[0], 1);
6973 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6974 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6976 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6977 check_added_monitors!(nodes[1], 0);
6978 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6980 let events = nodes[1].node.get_and_clear_pending_msg_events();
6982 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
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, .. } } => {
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()
6992 _ => panic!("Unexpected event"),
6995 update_msg.failure_code &= !0x8000;
6996 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6998 assert!(nodes[0].node.list_channels().is_empty());
6999 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
7000 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
7001 check_added_monitors!(nodes[0], 1);
7005 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
7006 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
7007 // * 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.
7009 let chanmon_cfgs = create_chanmon_cfgs(3);
7010 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7011 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7012 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7013 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7014 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7015 let logger = test_utils::TestLogger::new();
7017 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
7020 let mut payment_event = {
7021 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7022 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();
7023 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
7024 check_added_monitors!(nodes[0], 1);
7025 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7026 assert_eq!(events.len(), 1);
7027 SendEvent::from_event(events.remove(0))
7029 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7030 check_added_monitors!(nodes[1], 0);
7031 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7032 expect_pending_htlcs_forwardable!(nodes[1]);
7033 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
7034 assert_eq!(events_2.len(), 1);
7035 check_added_monitors!(nodes[1], 1);
7036 payment_event = SendEvent::from_event(events_2.remove(0));
7037 assert_eq!(payment_event.msgs.len(), 1);
7040 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
7041 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
7042 check_added_monitors!(nodes[2], 0);
7043 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
7045 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7046 assert_eq!(events_3.len(), 1);
7047 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7049 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 } } => {
7050 assert!(update_add_htlcs.is_empty());
7051 assert!(update_fulfill_htlcs.is_empty());
7052 assert!(update_fail_htlcs.is_empty());
7053 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7054 assert!(update_fee.is_none());
7055 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7057 _ => panic!("Unexpected event"),
7061 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7063 check_added_monitors!(nodes[1], 0);
7064 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7065 expect_pending_htlcs_forwardable!(nodes[1]);
7066 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7067 assert_eq!(events_4.len(), 1);
7069 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7071 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, .. } } => {
7072 assert!(update_add_htlcs.is_empty());
7073 assert!(update_fulfill_htlcs.is_empty());
7074 assert_eq!(update_fail_htlcs.len(), 1);
7075 assert!(update_fail_malformed_htlcs.is_empty());
7076 assert!(update_fee.is_none());
7078 _ => panic!("Unexpected event"),
7081 check_added_monitors!(nodes[1], 1);
7084 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7085 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7086 // 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
7087 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7089 let chanmon_cfgs = create_chanmon_cfgs(2);
7090 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7091 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7092 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7093 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7095 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7097 // We route 2 dust-HTLCs between A and B
7098 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7099 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7100 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7102 // Cache one local commitment tx as previous
7103 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7105 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7106 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7107 check_added_monitors!(nodes[1], 0);
7108 expect_pending_htlcs_forwardable!(nodes[1]);
7109 check_added_monitors!(nodes[1], 1);
7111 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7112 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7113 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7114 check_added_monitors!(nodes[0], 1);
7116 // Cache one local commitment tx as lastest
7117 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7119 let events = nodes[0].node.get_and_clear_pending_msg_events();
7121 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7122 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7124 _ => panic!("Unexpected event"),
7127 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7128 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7130 _ => panic!("Unexpected event"),
7133 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7134 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7135 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7137 if announce_latest {
7138 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7140 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7143 check_closed_broadcast!(nodes[0], false);
7144 check_added_monitors!(nodes[0], 1);
7146 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7147 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7148 let events = nodes[0].node.get_and_clear_pending_events();
7149 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7150 assert_eq!(events.len(), 2);
7151 let mut first_failed = false;
7152 for event in events {
7154 Event::PaymentFailed { payment_hash, .. } => {
7155 if payment_hash == payment_hash_1 {
7156 assert!(!first_failed);
7157 first_failed = true;
7159 assert_eq!(payment_hash, payment_hash_2);
7162 _ => panic!("Unexpected event"),
7168 fn test_failure_delay_dust_htlc_local_commitment() {
7169 do_test_failure_delay_dust_htlc_local_commitment(true);
7170 do_test_failure_delay_dust_htlc_local_commitment(false);
7173 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7174 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7175 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7176 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7177 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7178 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7179 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7181 let chanmon_cfgs = create_chanmon_cfgs(3);
7182 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7183 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7184 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7185 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7187 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7189 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7190 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7192 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7193 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7195 // We revoked bs_commitment_tx
7197 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7198 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7201 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7202 let mut timeout_tx = Vec::new();
7204 // We fail dust-HTLC 1 by broadcast of local commitment tx
7205 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7206 check_closed_broadcast!(nodes[0], false);
7207 check_added_monitors!(nodes[0], 1);
7208 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7209 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7210 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7211 expect_payment_failed!(nodes[0], dust_hash, true);
7212 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7213 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7214 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7215 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7216 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7217 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7218 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7219 expect_payment_failed!(nodes[0], non_dust_hash, true);
7221 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7222 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7223 check_closed_broadcast!(nodes[0], false);
7224 check_added_monitors!(nodes[0], 1);
7225 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7226 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7227 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7228 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7230 expect_payment_failed!(nodes[0], dust_hash, true);
7231 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7232 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7233 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7234 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7235 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7236 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7237 expect_payment_failed!(nodes[0], non_dust_hash, true);
7239 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7241 let events = nodes[0].node.get_and_clear_pending_events();
7242 assert_eq!(events.len(), 2);
7245 Event::PaymentFailed { payment_hash, .. } => {
7246 if payment_hash == dust_hash { first = true; }
7247 else { first = false; }
7249 _ => panic!("Unexpected event"),
7252 Event::PaymentFailed { payment_hash, .. } => {
7253 if first { assert_eq!(payment_hash, non_dust_hash); }
7254 else { assert_eq!(payment_hash, dust_hash); }
7256 _ => panic!("Unexpected event"),
7263 fn test_sweep_outbound_htlc_failure_update() {
7264 do_test_sweep_outbound_htlc_failure_update(false, true);
7265 do_test_sweep_outbound_htlc_failure_update(false, false);
7266 do_test_sweep_outbound_htlc_failure_update(true, false);
7270 fn test_upfront_shutdown_script() {
7271 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7272 // enforce it at shutdown message
7274 let mut config = UserConfig::default();
7275 config.channel_options.announced_channel = true;
7276 config.peer_channel_config_limits.force_announced_channel_preference = false;
7277 config.channel_options.commit_upfront_shutdown_pubkey = false;
7278 let user_cfgs = [None, Some(config), None];
7279 let chanmon_cfgs = create_chanmon_cfgs(3);
7280 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7281 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7282 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7284 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7285 let flags = InitFeatures::known();
7286 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7287 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7288 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7289 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7290 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7291 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7292 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()));
7293 check_added_monitors!(nodes[2], 1);
7295 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7296 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7297 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7298 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7299 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7300 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7301 let events = nodes[2].node.get_and_clear_pending_msg_events();
7302 assert_eq!(events.len(), 1);
7304 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7305 _ => panic!("Unexpected event"),
7308 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7309 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7310 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7311 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7312 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7313 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7314 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7315 let events = nodes[1].node.get_and_clear_pending_msg_events();
7316 assert_eq!(events.len(), 1);
7318 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7319 _ => panic!("Unexpected event"),
7322 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7323 // channel smoothly, opt-out is from channel initiator here
7324 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7325 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7326 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7327 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7328 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7329 let events = nodes[0].node.get_and_clear_pending_msg_events();
7330 assert_eq!(events.len(), 1);
7332 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7333 _ => panic!("Unexpected event"),
7336 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7337 //// channel smoothly
7338 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7339 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7340 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7341 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7342 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7343 let events = nodes[0].node.get_and_clear_pending_msg_events();
7344 assert_eq!(events.len(), 2);
7346 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7347 _ => panic!("Unexpected event"),
7350 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7351 _ => panic!("Unexpected event"),
7356 fn test_user_configurable_csv_delay() {
7357 // We test our channel constructors yield errors when we pass them absurd csv delay
7359 let mut low_our_to_self_config = UserConfig::default();
7360 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7361 let mut high_their_to_self_config = UserConfig::default();
7362 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7363 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7364 let chanmon_cfgs = create_chanmon_cfgs(2);
7365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7367 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7369 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7370 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
7371 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) {
7373 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())); },
7374 _ => panic!("Unexpected event"),
7376 } else { assert!(false) }
7378 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7379 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7380 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7381 open_channel.to_self_delay = 200;
7382 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) {
7384 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())); },
7385 _ => panic!("Unexpected event"),
7387 } else { assert!(false); }
7389 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7390 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7391 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()));
7392 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7393 accept_channel.to_self_delay = 200;
7394 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7395 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7397 &ErrorAction::SendErrorMessage { ref msg } => {
7398 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()));
7400 _ => { assert!(false); }
7402 } else { assert!(false); }
7404 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7405 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7406 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7407 open_channel.to_self_delay = 200;
7408 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) {
7410 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())); },
7411 _ => panic!("Unexpected event"),
7413 } else { assert!(false); }
7417 fn test_data_loss_protect() {
7418 // We want to be sure that :
7419 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7420 // * we close channel in case of detecting other being fallen behind
7421 // * we are able to claim our own outputs thanks to to_remote being static
7430 let chanmon_cfgs = create_chanmon_cfgs(2);
7431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7433 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7435 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7437 // Cache node A state before any channel update
7438 let previous_node_state = nodes[0].node.encode();
7439 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7440 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.serialize_for_disk(&mut previous_chain_monitor_state).unwrap();
7442 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7443 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7445 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7446 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7448 // Restore node A from previous state
7449 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7450 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0)).unwrap().1;
7451 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7452 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7453 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7454 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7455 persister = test_utils::TestPersister::new();
7456 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister);
7458 let mut channel_monitors = HashMap::new();
7459 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7460 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7461 keys_manager: &keys_manager,
7462 fee_estimator: &fee_estimator,
7463 chain_monitor: &monitor,
7465 tx_broadcaster: &tx_broadcaster,
7466 default_config: UserConfig::default(),
7470 nodes[0].node = &node_state_0;
7471 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7472 nodes[0].chain_monitor = &monitor;
7473 nodes[0].chain_source = &chain_source;
7475 check_added_monitors!(nodes[0], 1);
7477 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7478 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7480 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7482 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7483 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7484 check_added_monitors!(nodes[0], 1);
7487 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7488 assert_eq!(node_txn.len(), 0);
7491 let mut reestablish_1 = Vec::with_capacity(1);
7492 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7493 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7494 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7495 reestablish_1.push(msg.clone());
7496 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7497 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7499 &ErrorAction::SendErrorMessage { ref msg } => {
7500 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");
7502 _ => panic!("Unexpected event!"),
7505 panic!("Unexpected event")
7509 // Check we close channel detecting A is fallen-behind
7510 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7511 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7512 check_added_monitors!(nodes[1], 1);
7515 // Check A is able to claim to_remote output
7516 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7517 assert_eq!(node_txn.len(), 1);
7518 check_spends!(node_txn[0], chan.3);
7519 assert_eq!(node_txn[0].output.len(), 2);
7520 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7521 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7522 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7523 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7524 assert_eq!(spend_txn.len(), 1);
7525 check_spends!(spend_txn[0], node_txn[0]);
7529 fn test_check_htlc_underpaying() {
7530 // Send payment through A -> B but A is maliciously
7531 // sending a probe payment (i.e less than expected value0
7532 // to B, B should refuse payment.
7534 let chanmon_cfgs = create_chanmon_cfgs(2);
7535 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7536 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7537 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7539 // Create some initial channels
7540 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7542 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7544 // Node 3 is expecting payment of 100_000 but receive 10_000,
7545 // fail htlc like we didn't know the preimage.
7546 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7547 nodes[1].node.process_pending_htlc_forwards();
7549 let events = nodes[1].node.get_and_clear_pending_msg_events();
7550 assert_eq!(events.len(), 1);
7551 let (update_fail_htlc, commitment_signed) = match events[0] {
7552 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 } } => {
7553 assert!(update_add_htlcs.is_empty());
7554 assert!(update_fulfill_htlcs.is_empty());
7555 assert_eq!(update_fail_htlcs.len(), 1);
7556 assert!(update_fail_malformed_htlcs.is_empty());
7557 assert!(update_fee.is_none());
7558 (update_fail_htlcs[0].clone(), commitment_signed)
7560 _ => panic!("Unexpected event"),
7562 check_added_monitors!(nodes[1], 1);
7564 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7565 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7567 // 10_000 msat as u64, followed by a height of 99 as u32
7568 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7569 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7570 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7571 nodes[1].node.get_and_clear_pending_events();
7575 fn test_announce_disable_channels() {
7576 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7577 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7579 let chanmon_cfgs = create_chanmon_cfgs(2);
7580 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7581 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7582 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7584 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7585 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7586 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7589 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7590 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7592 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7593 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7594 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7595 assert_eq!(msg_events.len(), 3);
7596 for e in msg_events {
7598 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7599 let short_id = msg.contents.short_channel_id;
7600 // Check generated channel_update match list in PendingChannelUpdate
7601 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7602 panic!("Generated ChannelUpdate for wrong chan!");
7605 _ => panic!("Unexpected event"),
7609 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7610 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7611 assert_eq!(reestablish_1.len(), 3);
7612 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7613 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7614 assert_eq!(reestablish_2.len(), 3);
7616 // Reestablish chan_1
7617 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7618 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7619 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7620 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7621 // Reestablish chan_2
7622 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7623 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7624 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7625 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7626 // Reestablish chan_3
7627 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7628 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7629 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7630 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7632 nodes[0].node.timer_chan_freshness_every_min();
7633 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7637 fn test_bump_penalty_txn_on_revoked_commitment() {
7638 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7639 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7641 let chanmon_cfgs = create_chanmon_cfgs(2);
7642 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7643 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7644 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7646 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7647 let logger = test_utils::TestLogger::new();
7650 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7651 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7652 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();
7653 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7655 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7656 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7657 assert_eq!(revoked_txn[0].output.len(), 4);
7658 assert_eq!(revoked_txn[0].input.len(), 1);
7659 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7660 let revoked_txid = revoked_txn[0].txid();
7662 let mut penalty_sum = 0;
7663 for outp in revoked_txn[0].output.iter() {
7664 if outp.script_pubkey.is_v0_p2wsh() {
7665 penalty_sum += outp.value;
7669 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7670 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7672 // Actually revoke tx by claiming a HTLC
7673 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7674 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7675 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7676 check_added_monitors!(nodes[1], 1);
7678 // One or more justice tx should have been broadcast, check it
7682 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7683 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7684 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7685 assert_eq!(node_txn[0].output.len(), 1);
7686 check_spends!(node_txn[0], revoked_txn[0]);
7687 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7688 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7689 penalty_1 = node_txn[0].txid();
7693 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7694 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7695 let mut penalty_2 = penalty_1;
7696 let mut feerate_2 = 0;
7698 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7699 assert_eq!(node_txn.len(), 1);
7700 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7701 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7702 assert_eq!(node_txn[0].output.len(), 1);
7703 check_spends!(node_txn[0], revoked_txn[0]);
7704 penalty_2 = node_txn[0].txid();
7705 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7706 assert_ne!(penalty_2, penalty_1);
7707 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7708 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7709 // Verify 25% bump heuristic
7710 assert!(feerate_2 * 100 >= feerate_1 * 125);
7714 assert_ne!(feerate_2, 0);
7716 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7717 connect_blocks(&nodes[1], 3, 118, true, header);
7719 let mut feerate_3 = 0;
7721 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7722 assert_eq!(node_txn.len(), 1);
7723 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7724 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7725 assert_eq!(node_txn[0].output.len(), 1);
7726 check_spends!(node_txn[0], revoked_txn[0]);
7727 penalty_3 = node_txn[0].txid();
7728 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7729 assert_ne!(penalty_3, penalty_2);
7730 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7731 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7732 // Verify 25% bump heuristic
7733 assert!(feerate_3 * 100 >= feerate_2 * 125);
7737 assert_ne!(feerate_3, 0);
7739 nodes[1].node.get_and_clear_pending_events();
7740 nodes[1].node.get_and_clear_pending_msg_events();
7744 fn test_bump_penalty_txn_on_revoked_htlcs() {
7745 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7746 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7748 let chanmon_cfgs = create_chanmon_cfgs(2);
7749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7751 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7753 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7754 // Lock HTLC in both directions
7755 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7756 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7758 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7759 assert_eq!(revoked_local_txn[0].input.len(), 1);
7760 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7762 // Revoke local commitment tx
7763 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7765 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7766 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7767 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7768 check_closed_broadcast!(nodes[1], false);
7769 check_added_monitors!(nodes[1], 1);
7771 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7772 assert_eq!(revoked_htlc_txn.len(), 4);
7773 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7774 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7775 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7776 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7777 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7778 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7779 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7780 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7781 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7782 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7783 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7784 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7785 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7786 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7789 // Broadcast set of revoked txn on A
7790 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7791 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7792 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7793 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7794 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7799 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7800 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7801 // Verify claim tx are spending revoked HTLC txn
7803 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7804 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7805 // which are included in the same block (they are broadcasted because we scan the
7806 // transactions linearly and generate claims as we go, they likely should be removed in the
7808 assert_eq!(node_txn[0].input.len(), 1);
7809 check_spends!(node_txn[0], revoked_local_txn[0]);
7810 assert_eq!(node_txn[1].input.len(), 1);
7811 check_spends!(node_txn[1], revoked_local_txn[0]);
7812 assert_eq!(node_txn[2].input.len(), 1);
7813 check_spends!(node_txn[2], revoked_local_txn[0]);
7815 // Each of the three justice transactions claim a separate (single) output of the three
7816 // available, which we check here:
7817 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7818 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7819 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7821 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7822 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7824 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7825 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7826 // a remote commitment tx has already been confirmed).
7827 check_spends!(node_txn[3], chan.3);
7829 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7830 // output, checked above).
7831 assert_eq!(node_txn[4].input.len(), 2);
7832 assert_eq!(node_txn[4].output.len(), 1);
7833 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7835 first = node_txn[4].txid();
7836 // Store both feerates for later comparison
7837 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7838 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7839 penalty_txn = vec![node_txn[2].clone()];
7843 // Connect one more block to see if bumped penalty are issued for HTLC txn
7844 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7845 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7846 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7847 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7849 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7850 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7852 check_spends!(node_txn[0], revoked_local_txn[0]);
7853 check_spends!(node_txn[1], revoked_local_txn[0]);
7854 // Note that these are both bogus - they spend outputs already claimed in block 129:
7855 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7856 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7858 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7859 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7865 // Few more blocks to confirm penalty txn
7866 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7867 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7868 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7870 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7871 assert_eq!(node_txn.len(), 1);
7873 assert_eq!(node_txn[0].input.len(), 2);
7874 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7875 // Verify bumped tx is different and 25% bump heuristic
7876 assert_ne!(first, node_txn[0].txid());
7877 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7878 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7879 assert!(feerate_2 * 100 > feerate_1 * 125);
7880 let txn = vec![node_txn[0].clone()];
7884 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7885 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7886 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7887 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7889 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7890 // We verify than no new transaction has been broadcast because previously
7891 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7892 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7893 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7894 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7895 // up bumped justice generation.
7896 assert_eq!(node_txn.len(), 0);
7899 check_closed_broadcast!(nodes[0], false);
7900 check_added_monitors!(nodes[0], 1);
7904 fn test_bump_penalty_txn_on_remote_commitment() {
7905 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7906 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7909 // Provide preimage for one
7910 // Check aggregation
7912 let chanmon_cfgs = create_chanmon_cfgs(2);
7913 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7914 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7915 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7917 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7918 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7919 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7921 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7922 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7923 assert_eq!(remote_txn[0].output.len(), 4);
7924 assert_eq!(remote_txn[0].input.len(), 1);
7925 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7927 // Claim a HTLC without revocation (provide B monitor with preimage)
7928 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7929 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7930 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7931 check_added_monitors!(nodes[1], 2);
7933 // One or more claim tx should have been broadcast, check it
7936 let feerate_timeout;
7937 let feerate_preimage;
7939 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7940 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7941 assert_eq!(node_txn[0].input.len(), 1);
7942 assert_eq!(node_txn[1].input.len(), 1);
7943 check_spends!(node_txn[0], remote_txn[0]);
7944 check_spends!(node_txn[1], remote_txn[0]);
7945 check_spends!(node_txn[2], chan.3);
7946 check_spends!(node_txn[3], node_txn[2]);
7947 check_spends!(node_txn[4], node_txn[2]);
7948 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7949 timeout = node_txn[0].txid();
7950 let index = node_txn[0].input[0].previous_output.vout;
7951 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7952 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7954 preimage = node_txn[1].txid();
7955 let index = node_txn[1].input[0].previous_output.vout;
7956 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7957 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7959 timeout = node_txn[1].txid();
7960 let index = node_txn[1].input[0].previous_output.vout;
7961 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7962 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7964 preimage = node_txn[0].txid();
7965 let index = node_txn[0].input[0].previous_output.vout;
7966 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7967 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7971 assert_ne!(feerate_timeout, 0);
7972 assert_ne!(feerate_preimage, 0);
7974 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7975 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
7977 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7978 assert_eq!(node_txn.len(), 2);
7979 assert_eq!(node_txn[0].input.len(), 1);
7980 assert_eq!(node_txn[1].input.len(), 1);
7981 check_spends!(node_txn[0], remote_txn[0]);
7982 check_spends!(node_txn[1], remote_txn[0]);
7983 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7984 let index = node_txn[0].input[0].previous_output.vout;
7985 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7986 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7987 assert!(new_feerate * 100 > feerate_timeout * 125);
7988 assert_ne!(timeout, node_txn[0].txid());
7990 let index = node_txn[1].input[0].previous_output.vout;
7991 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7992 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7993 assert!(new_feerate * 100 > feerate_preimage * 125);
7994 assert_ne!(preimage, node_txn[1].txid());
7996 let index = node_txn[1].input[0].previous_output.vout;
7997 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7998 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7999 assert!(new_feerate * 100 > feerate_timeout * 125);
8000 assert_ne!(timeout, node_txn[1].txid());
8002 let index = node_txn[0].input[0].previous_output.vout;
8003 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
8004 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
8005 assert!(new_feerate * 100 > feerate_preimage * 125);
8006 assert_ne!(preimage, node_txn[0].txid());
8011 nodes[1].node.get_and_clear_pending_events();
8012 nodes[1].node.get_and_clear_pending_msg_events();
8016 fn test_set_outpoints_partial_claiming() {
8017 // - remote party claim tx, new bump tx
8018 // - disconnect remote claiming tx, new bump
8019 // - disconnect tx, see no tx anymore
8020 let chanmon_cfgs = create_chanmon_cfgs(2);
8021 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8022 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8023 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8025 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8026 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8027 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
8029 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
8030 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
8031 assert_eq!(remote_txn.len(), 3);
8032 assert_eq!(remote_txn[0].output.len(), 4);
8033 assert_eq!(remote_txn[0].input.len(), 1);
8034 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
8035 check_spends!(remote_txn[1], remote_txn[0]);
8036 check_spends!(remote_txn[2], remote_txn[0]);
8038 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
8039 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
8040 // Provide node A with both preimage
8041 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
8042 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
8043 check_added_monitors!(nodes[0], 2);
8044 nodes[0].node.get_and_clear_pending_events();
8045 nodes[0].node.get_and_clear_pending_msg_events();
8047 // Connect blocks on node A commitment transaction
8048 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8049 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8050 check_closed_broadcast!(nodes[0], false);
8051 check_added_monitors!(nodes[0], 1);
8052 // Verify node A broadcast tx claiming both HTLCs
8054 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8055 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8056 assert_eq!(node_txn.len(), 4);
8057 check_spends!(node_txn[0], remote_txn[0]);
8058 check_spends!(node_txn[1], chan.3);
8059 check_spends!(node_txn[2], node_txn[1]);
8060 check_spends!(node_txn[3], node_txn[1]);
8061 assert_eq!(node_txn[0].input.len(), 2);
8065 // Connect blocks on node B
8066 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8067 check_closed_broadcast!(nodes[1], false);
8068 check_added_monitors!(nodes[1], 1);
8069 // Verify node B broadcast 2 HTLC-timeout txn
8070 let partial_claim_tx = {
8071 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8072 assert_eq!(node_txn.len(), 3);
8073 check_spends!(node_txn[1], node_txn[0]);
8074 check_spends!(node_txn[2], node_txn[0]);
8075 assert_eq!(node_txn[1].input.len(), 1);
8076 assert_eq!(node_txn[2].input.len(), 1);
8080 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8081 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8082 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8084 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8085 assert_eq!(node_txn.len(), 1);
8086 check_spends!(node_txn[0], remote_txn[0]);
8087 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8090 nodes[0].node.get_and_clear_pending_msg_events();
8092 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8093 disconnect_block(&nodes[0], &header, 102);
8095 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8096 assert_eq!(node_txn.len(), 1);
8097 check_spends!(node_txn[0], remote_txn[0]);
8098 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8102 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8103 disconnect_block(&nodes[0], &header, 101);
8104 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8106 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8107 assert_eq!(node_txn.len(), 0);
8113 fn test_counterparty_raa_skip_no_crash() {
8114 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8115 // commitment transaction, we would have happily carried on and provided them the next
8116 // commitment transaction based on one RAA forward. This would probably eventually have led to
8117 // channel closure, but it would not have resulted in funds loss. Still, our
8118 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8119 // check simply that the channel is closed in response to such an RAA, but don't check whether
8120 // we decide to punish our counterparty for revoking their funds (as we don't currently
8122 let chanmon_cfgs = create_chanmon_cfgs(2);
8123 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8124 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8125 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8126 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8128 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8129 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8130 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8131 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8132 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8133 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8135 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8136 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8137 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8138 check_added_monitors!(nodes[1], 1);
8142 fn test_bump_txn_sanitize_tracking_maps() {
8143 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8144 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8146 let chanmon_cfgs = create_chanmon_cfgs(2);
8147 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8148 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8149 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8151 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8152 // Lock HTLC in both directions
8153 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8154 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8156 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8157 assert_eq!(revoked_local_txn[0].input.len(), 1);
8158 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8160 // Revoke local commitment tx
8161 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8163 // Broadcast set of revoked txn on A
8164 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8165 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8167 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8168 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8169 check_closed_broadcast!(nodes[0], false);
8170 check_added_monitors!(nodes[0], 1);
8172 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8173 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8174 check_spends!(node_txn[0], revoked_local_txn[0]);
8175 check_spends!(node_txn[1], revoked_local_txn[0]);
8176 check_spends!(node_txn[2], revoked_local_txn[0]);
8177 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8181 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8182 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8183 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8185 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8186 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8187 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8188 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8194 fn test_override_channel_config() {
8195 let chanmon_cfgs = create_chanmon_cfgs(2);
8196 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8197 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8198 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8200 // Node0 initiates a channel to node1 using the override config.
8201 let mut override_config = UserConfig::default();
8202 override_config.own_channel_config.our_to_self_delay = 200;
8204 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8206 // Assert the channel created by node0 is using the override config.
8207 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8208 assert_eq!(res.channel_flags, 0);
8209 assert_eq!(res.to_self_delay, 200);
8213 fn test_override_0msat_htlc_minimum() {
8214 let mut zero_config = UserConfig::default();
8215 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8216 let chanmon_cfgs = create_chanmon_cfgs(2);
8217 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8218 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8219 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8221 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8222 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8223 assert_eq!(res.htlc_minimum_msat, 1);
8225 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8226 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8227 assert_eq!(res.htlc_minimum_msat, 1);
8231 fn test_simple_payment_secret() {
8232 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8233 // features, however.
8234 let chanmon_cfgs = create_chanmon_cfgs(3);
8235 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8236 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8237 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8239 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8240 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8241 let logger = test_utils::TestLogger::new();
8243 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8244 let payment_secret = PaymentSecret([0xdb; 32]);
8245 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8246 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();
8247 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8248 // Claiming with all the correct values but the wrong secret should result in nothing...
8249 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8250 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8251 // ...but with the right secret we should be able to claim all the way back
8252 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8256 fn test_simple_mpp() {
8257 // Simple test of sending a multi-path payment.
8258 let chanmon_cfgs = create_chanmon_cfgs(4);
8259 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8260 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8261 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8263 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8264 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8265 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8266 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8267 let logger = test_utils::TestLogger::new();
8269 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8270 let payment_secret = PaymentSecret([0xdb; 32]);
8271 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8272 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();
8273 let path = route.paths[0].clone();
8274 route.paths.push(path);
8275 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8276 route.paths[0][0].short_channel_id = chan_1_id;
8277 route.paths[0][1].short_channel_id = chan_3_id;
8278 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8279 route.paths[1][0].short_channel_id = chan_2_id;
8280 route.paths[1][1].short_channel_id = chan_4_id;
8281 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8282 // Claiming with all the correct values but the wrong secret should result in nothing...
8283 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8284 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8285 // ...but with the right secret we should be able to claim all the way back
8286 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8290 fn test_update_err_monitor_lockdown() {
8291 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8292 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8293 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8295 // This scenario may happen in a watchtower setup, where watchtower process a block height
8296 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8297 // commitment at same time.
8299 let chanmon_cfgs = create_chanmon_cfgs(2);
8300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8302 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8304 // Create some initial channel
8305 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8306 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8308 // Rebalance the network to generate htlc in the two directions
8309 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8311 // Route a HTLC from node 0 to node 1 (but don't settle)
8312 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8314 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8315 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8316 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8317 let persister = test_utils::TestPersister::new();
8319 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8320 let monitor = monitors.get(&outpoint).unwrap();
8321 let mut w = test_utils::TestVecWriter(Vec::new());
8322 monitor.serialize_for_disk(&mut w).unwrap();
8323 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8324 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8325 assert!(new_monitor == *monitor);
8326 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
8327 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8330 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8331 watchtower.chain_monitor.block_connected(&header, &[], 200);
8333 // Try to update ChannelMonitor
8334 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8335 check_added_monitors!(nodes[1], 1);
8336 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8337 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8338 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8339 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8340 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8341 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8342 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8343 } else { assert!(false); }
8344 } else { assert!(false); };
8345 // Our local monitor is in-sync and hasn't processed yet timeout
8346 check_added_monitors!(nodes[0], 1);
8347 let events = nodes[0].node.get_and_clear_pending_events();
8348 assert_eq!(events.len(), 1);
8352 fn test_concurrent_monitor_claim() {
8353 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8354 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8355 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8356 // state N+1 confirms. Alice claims output from state N+1.
8358 let chanmon_cfgs = create_chanmon_cfgs(2);
8359 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8360 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8361 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8363 // Create some initial channel
8364 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8365 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8367 // Rebalance the network to generate htlc in the two directions
8368 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8370 // Route a HTLC from node 0 to node 1 (but don't settle)
8371 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8373 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8374 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8375 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8376 let persister = test_utils::TestPersister::new();
8377 let watchtower_alice = {
8378 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8379 let monitor = monitors.get(&outpoint).unwrap();
8380 let mut w = test_utils::TestVecWriter(Vec::new());
8381 monitor.serialize_for_disk(&mut w).unwrap();
8382 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8383 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8384 assert!(new_monitor == *monitor);
8385 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
8386 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8389 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8390 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8392 // Watchtower Alice 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);
8399 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8400 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8401 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8402 let persister = test_utils::TestPersister::new();
8403 let watchtower_bob = {
8404 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8405 let monitor = monitors.get(&outpoint).unwrap();
8406 let mut w = test_utils::TestVecWriter(Vec::new());
8407 monitor.serialize_for_disk(&mut w).unwrap();
8408 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8409 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
8410 assert!(new_monitor == *monitor);
8411 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister);
8412 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8415 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8416 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8418 // Route another payment to generate another update with still previous HTLC pending
8419 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8421 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8422 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();
8423 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8425 check_added_monitors!(nodes[1], 1);
8427 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8428 assert_eq!(updates.update_add_htlcs.len(), 1);
8429 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8430 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8431 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8432 // Watchtower Alice should already have seen the block and reject the update
8433 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8434 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8435 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8436 } else { assert!(false); }
8437 } else { assert!(false); };
8438 // Our local monitor is in-sync and hasn't processed yet timeout
8439 check_added_monitors!(nodes[0], 1);
8441 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8442 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8444 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8447 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8448 assert_eq!(txn.len(), 2);
8449 bob_state_y = txn[0].clone();
8453 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8454 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8456 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8457 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8458 // the onchain detection of the HTLC output
8459 assert_eq!(htlc_txn.len(), 2);
8460 check_spends!(htlc_txn[0], bob_state_y);
8461 check_spends!(htlc_txn[1], bob_state_y);
8466 fn test_pre_lockin_no_chan_closed_update() {
8467 // Test that if a peer closes a channel in response to a funding_created message we don't
8468 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8471 // Doing so would imply a channel monitor update before the initial channel monitor
8472 // registration, violating our API guarantees.
8474 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8475 // then opening a second channel with the same funding output as the first (which is not
8476 // rejected because the first channel does not exist in the ChannelManager) and closing it
8477 // before receiving funding_signed.
8478 let chanmon_cfgs = create_chanmon_cfgs(2);
8479 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8480 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8481 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8483 // Create an initial channel
8484 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8485 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8486 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8487 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8488 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8490 // Move the first channel through the funding flow...
8491 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8493 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8494 check_added_monitors!(nodes[0], 0);
8496 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8497 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8498 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8499 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8503 fn test_htlc_no_detection() {
8504 // This test is a mutation to underscore the detection logic bug we had
8505 // before #653. HTLC value routed is above the remaining balance, thus
8506 // inverting HTLC and `to_remote` output. HTLC will come second and
8507 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8508 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8509 // outputs order detection for correct spending children filtring.
8511 let chanmon_cfgs = create_chanmon_cfgs(2);
8512 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8513 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8514 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8516 // Create some initial channels
8517 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8519 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8520 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8521 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8522 assert_eq!(local_txn[0].input.len(), 1);
8523 assert_eq!(local_txn[0].output.len(), 3);
8524 check_spends!(local_txn[0], chan_1.3);
8526 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8527 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8528 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8529 // We deliberately connect the local tx twice as this should provoke a failure calling
8530 // this test before #653 fix.
8531 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8532 check_closed_broadcast!(nodes[0], false);
8533 check_added_monitors!(nodes[0], 1);
8535 let htlc_timeout = {
8536 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8537 assert_eq!(node_txn[0].input.len(), 1);
8538 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8539 check_spends!(node_txn[0], local_txn[0]);
8543 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8544 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8545 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8546 expect_payment_failed!(nodes[0], our_payment_hash, true);
8549 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8550 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8551 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8552 // Carol, Alice would be the upstream node, and Carol the downstream.)
8554 // Steps of the test:
8555 // 1) Alice sends a HTLC to Carol through Bob.
8556 // 2) Carol doesn't settle the HTLC.
8557 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8558 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8559 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8560 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8561 // 5) Carol release the preimage to Bob off-chain.
8562 // 6) Bob claims the offered output on the broadcasted commitment.
8563 let chanmon_cfgs = create_chanmon_cfgs(3);
8564 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8565 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8566 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8568 // Create some initial channels
8569 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8570 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8572 // Steps (1) and (2):
8573 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8574 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8576 // Check that Alice's commitment transaction now contains an output for this HTLC.
8577 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8578 check_spends!(alice_txn[0], chan_ab.3);
8579 assert_eq!(alice_txn[0].output.len(), 2);
8580 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8581 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8582 assert_eq!(alice_txn.len(), 2);
8584 // Steps (3) and (4):
8585 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8586 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8587 let mut force_closing_node = 0; // Alice force-closes
8588 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8589 nodes[force_closing_node].node.force_close_channel(&chan_ab.2);
8590 check_closed_broadcast!(nodes[force_closing_node], false);
8591 check_added_monitors!(nodes[force_closing_node], 1);
8592 if go_onchain_before_fulfill {
8593 let txn_to_broadcast = match broadcast_alice {
8594 true => alice_txn.clone(),
8595 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8597 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8598 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8599 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8600 if broadcast_alice {
8601 check_closed_broadcast!(nodes[1], false);
8602 check_added_monitors!(nodes[1], 1);
8604 assert_eq!(bob_txn.len(), 1);
8605 check_spends!(bob_txn[0], chan_ab.3);
8609 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8610 // process of removing the HTLC from their commitment transactions.
8611 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8612 check_added_monitors!(nodes[2], 1);
8613 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8614 assert!(carol_updates.update_add_htlcs.is_empty());
8615 assert!(carol_updates.update_fail_htlcs.is_empty());
8616 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8617 assert!(carol_updates.update_fee.is_none());
8618 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8620 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8621 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8622 if !go_onchain_before_fulfill && broadcast_alice {
8623 let events = nodes[1].node.get_and_clear_pending_msg_events();
8624 assert_eq!(events.len(), 1);
8626 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8627 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8629 _ => panic!("Unexpected event"),
8632 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8633 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8634 // Carol<->Bob's updated commitment transaction info.
8635 check_added_monitors!(nodes[1], 2);
8637 let events = nodes[1].node.get_and_clear_pending_msg_events();
8638 assert_eq!(events.len(), 2);
8639 let bob_revocation = match events[0] {
8640 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8641 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8644 _ => panic!("Unexpected event"),
8646 let bob_updates = match events[1] {
8647 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8648 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8651 _ => panic!("Unexpected event"),
8654 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8655 check_added_monitors!(nodes[2], 1);
8656 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8657 check_added_monitors!(nodes[2], 1);
8659 let events = nodes[2].node.get_and_clear_pending_msg_events();
8660 assert_eq!(events.len(), 1);
8661 let carol_revocation = match events[0] {
8662 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8663 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8666 _ => panic!("Unexpected event"),
8668 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8669 check_added_monitors!(nodes[1], 1);
8671 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8672 // here's where we put said channel's commitment tx on-chain.
8673 let mut txn_to_broadcast = alice_txn.clone();
8674 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8675 if !go_onchain_before_fulfill {
8676 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8677 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8678 // If Bob was the one to force-close, he will have already passed these checks earlier.
8679 if broadcast_alice {
8680 check_closed_broadcast!(nodes[1], false);
8681 check_added_monitors!(nodes[1], 1);
8683 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8684 if broadcast_alice {
8685 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8686 // new block being connected. The ChannelManager being notified triggers a monitor update,
8687 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8688 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8690 assert_eq!(bob_txn.len(), 3);
8691 check_spends!(bob_txn[1], chan_ab.3);
8693 assert_eq!(bob_txn.len(), 2);
8694 check_spends!(bob_txn[0], chan_ab.3);
8699 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8700 // broadcasted commitment transaction.
8702 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8703 if go_onchain_before_fulfill {
8704 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8705 assert_eq!(bob_txn.len(), 2);
8707 let script_weight = match broadcast_alice {
8708 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8709 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8711 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8712 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8713 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8714 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8715 if broadcast_alice && !go_onchain_before_fulfill {
8716 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8717 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8719 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8720 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8726 fn test_onchain_htlc_settlement_after_close() {
8727 do_test_onchain_htlc_settlement_after_close(true, true);
8728 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8729 do_test_onchain_htlc_settlement_after_close(true, false);
8730 do_test_onchain_htlc_settlement_after_close(false, false);
8734 fn test_duplicate_chan_id() {
8735 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8736 // already open we reject it and keep the old channel.
8738 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8739 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8740 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8741 // updating logic for the existing channel.
8742 let chanmon_cfgs = create_chanmon_cfgs(2);
8743 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8744 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8745 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8747 // Create an initial channel
8748 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8749 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8750 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8751 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8753 // Try to create a second channel with the same temporary_channel_id as the first and check
8754 // that it is rejected.
8755 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8757 let events = nodes[1].node.get_and_clear_pending_msg_events();
8758 assert_eq!(events.len(), 1);
8760 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8761 // Technically, at this point, nodes[1] would be justified in thinking both the
8762 // first (valid) and second (invalid) channels are closed, given they both have
8763 // the same non-temporary channel_id. However, currently we do not, so we just
8764 // move forward with it.
8765 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8766 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8768 _ => panic!("Unexpected event"),
8772 // Move the first channel through the funding flow...
8773 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8775 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8776 check_added_monitors!(nodes[0], 0);
8778 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8779 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8781 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8782 assert_eq!(added_monitors.len(), 1);
8783 assert_eq!(added_monitors[0].0, funding_output);
8784 added_monitors.clear();
8786 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8788 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8789 let channel_id = funding_outpoint.to_channel_id();
8791 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8794 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8795 // Technically this is allowed by the spec, but we don't support it and there's little reason
8796 // to. Still, it shouldn't cause any other issues.
8797 open_chan_msg.temporary_channel_id = channel_id;
8798 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8800 let events = nodes[1].node.get_and_clear_pending_msg_events();
8801 assert_eq!(events.len(), 1);
8803 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8804 // Technically, at this point, nodes[1] would be justified in thinking both
8805 // channels are closed, but currently we do not, so we just move forward with it.
8806 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8807 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8809 _ => panic!("Unexpected event"),
8813 // Now try to create a second channel which has a duplicate funding output.
8814 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8815 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8816 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8817 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
8818 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8820 let funding_created = {
8821 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8822 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8823 let logger = test_utils::TestLogger::new();
8824 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8826 check_added_monitors!(nodes[0], 0);
8827 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8828 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8829 // still needs to be cleared here.
8830 check_added_monitors!(nodes[1], 1);
8832 // ...still, nodes[1] will reject the duplicate channel.
8834 let events = nodes[1].node.get_and_clear_pending_msg_events();
8835 assert_eq!(events.len(), 1);
8837 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8838 // Technically, at this point, nodes[1] would be justified in thinking both
8839 // channels are closed, but currently we do not, so we just move forward with it.
8840 assert_eq!(msg.channel_id, channel_id);
8841 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8843 _ => panic!("Unexpected event"),
8847 // finally, finish creating the original channel and send a payment over it to make sure
8848 // everything is functional.
8849 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8851 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8852 assert_eq!(added_monitors.len(), 1);
8853 assert_eq!(added_monitors[0].0, funding_output);
8854 added_monitors.clear();
8857 let events_4 = nodes[0].node.get_and_clear_pending_events();
8858 assert_eq!(events_4.len(), 1);
8860 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8861 assert_eq!(user_channel_id, 42);
8862 assert_eq!(*funding_txo, funding_output);
8864 _ => panic!("Unexpected event"),
8867 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8868 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8869 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8870 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);