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};
32 use util::config::UserConfig;
34 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
35 use bitcoin::hash_types::{Txid, BlockHash};
36 use bitcoin::util::bip143;
37 use bitcoin::util::address::Address;
38 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
39 use bitcoin::blockdata::block::{Block, BlockHeader};
40 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
41 use bitcoin::blockdata::script::{Builder, Script};
42 use bitcoin::blockdata::opcodes;
43 use bitcoin::blockdata::constants::genesis_block;
44 use bitcoin::network::constants::Network;
46 use bitcoin::hashes::sha256::Hash as Sha256;
47 use bitcoin::hashes::Hash;
49 use bitcoin::secp256k1::{Secp256k1, Message};
50 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
54 use std::collections::{BTreeSet, HashMap, HashSet};
55 use std::default::Default;
57 use std::sync::atomic::Ordering;
60 use ln::functional_test_utils::*;
61 use ln::chan_utils::CommitmentTransaction;
64 fn test_insane_channel_opens() {
65 // Stand up a network of 2 nodes
66 let chanmon_cfgs = create_chanmon_cfgs(2);
67 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
68 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
69 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
71 // Instantiate channel parameters where we push the maximum msats given our
73 let channel_value_sat = 31337; // same as funding satoshis
74 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_holder_selected_channel_reserve_satoshis(channel_value_sat);
75 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
77 // Have node0 initiate a channel to node1 with aforementioned parameters
78 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
80 // Extract the channel open message from node0 to node1
81 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
83 // Test helper that asserts we get the correct error string given a mutator
84 // that supposedly makes the channel open message insane
85 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
86 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
87 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
88 assert_eq!(msg_events.len(), 1);
89 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
90 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
92 &ErrorAction::SendErrorMessage { .. } => {
93 nodes[1].logger.assert_log_regex("lightning::ln::channelmanager".to_string(), expected_regex, 1);
95 _ => panic!("unexpected event!"),
97 } else { assert!(false); }
100 use ln::channel::MAX_FUNDING_SATOSHIS;
101 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
103 // Test all mutations that would make the channel open message insane
104 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 });
106 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
108 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 });
110 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
112 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 });
114 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 });
116 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 });
118 insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
120 insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
124 fn test_async_inbound_update_fee() {
125 let chanmon_cfgs = create_chanmon_cfgs(2);
126 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
128 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
129 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
130 let logger = test_utils::TestLogger::new();
131 let channel_id = chan.2;
134 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
138 // send (1) commitment_signed -.
139 // <- update_add_htlc/commitment_signed
140 // send (2) RAA (awaiting remote revoke) -.
141 // (1) commitment_signed is delivered ->
142 // .- send (3) RAA (awaiting remote revoke)
143 // (2) RAA is delivered ->
144 // .- send (4) commitment_signed
145 // <- (3) RAA is delivered
146 // send (5) commitment_signed -.
147 // <- (4) commitment_signed is delivered
149 // (5) commitment_signed is delivered ->
151 // (6) RAA is delivered ->
153 // First nodes[0] generates an update_fee
154 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
155 check_added_monitors!(nodes[0], 1);
157 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
158 assert_eq!(events_0.len(), 1);
159 let (update_msg, commitment_signed) = match events_0[0] { // (1)
160 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
161 (update_fee.as_ref(), commitment_signed)
163 _ => panic!("Unexpected event"),
166 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
168 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
169 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
170 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
171 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();
172 check_added_monitors!(nodes[1], 1);
174 let payment_event = {
175 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
176 assert_eq!(events_1.len(), 1);
177 SendEvent::from_event(events_1.remove(0))
179 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
180 assert_eq!(payment_event.msgs.len(), 1);
182 // ...now when the messages get delivered everyone should be happy
183 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
184 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
185 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
186 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
187 check_added_monitors!(nodes[0], 1);
189 // deliver(1), generate (3):
190 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
191 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
192 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
193 check_added_monitors!(nodes[1], 1);
195 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
196 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
197 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
198 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
199 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
200 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
201 assert!(bs_update.update_fee.is_none()); // (4)
202 check_added_monitors!(nodes[1], 1);
204 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
205 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
206 assert!(as_update.update_add_htlcs.is_empty()); // (5)
207 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
208 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
209 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
210 assert!(as_update.update_fee.is_none()); // (5)
211 check_added_monitors!(nodes[0], 1);
213 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
214 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
215 // only (6) so get_event_msg's assert(len == 1) passes
216 check_added_monitors!(nodes[0], 1);
218 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
219 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
220 check_added_monitors!(nodes[1], 1);
222 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
223 check_added_monitors!(nodes[0], 1);
225 let events_2 = nodes[0].node.get_and_clear_pending_events();
226 assert_eq!(events_2.len(), 1);
228 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
229 _ => panic!("Unexpected event"),
232 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
233 check_added_monitors!(nodes[1], 1);
237 fn test_update_fee_unordered_raa() {
238 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
239 // crash in an earlier version of the update_fee patch)
240 let chanmon_cfgs = create_chanmon_cfgs(2);
241 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
242 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
243 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
244 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
245 let channel_id = chan.2;
246 let logger = test_utils::TestLogger::new();
249 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
251 // First nodes[0] generates an update_fee
252 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
253 check_added_monitors!(nodes[0], 1);
255 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
256 assert_eq!(events_0.len(), 1);
257 let update_msg = match events_0[0] { // (1)
258 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
261 _ => panic!("Unexpected event"),
264 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
266 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
267 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
268 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
269 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();
270 check_added_monitors!(nodes[1], 1);
272 let payment_event = {
273 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
274 assert_eq!(events_1.len(), 1);
275 SendEvent::from_event(events_1.remove(0))
277 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
278 assert_eq!(payment_event.msgs.len(), 1);
280 // ...now when the messages get delivered everyone should be happy
281 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
282 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
283 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
284 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
285 check_added_monitors!(nodes[0], 1);
287 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
288 check_added_monitors!(nodes[1], 1);
290 // We can't continue, sadly, because our (1) now has a bogus signature
294 fn test_multi_flight_update_fee() {
295 let chanmon_cfgs = create_chanmon_cfgs(2);
296 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
297 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
298 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
299 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
300 let channel_id = chan.2;
303 // update_fee/commitment_signed ->
304 // .- send (1) RAA and (2) commitment_signed
305 // update_fee (never committed) ->
307 // We have to manually generate the above update_fee, it is allowed by the protocol but we
308 // don't track which updates correspond to which revoke_and_ack responses so we're in
309 // AwaitingRAA mode and will not generate the update_fee yet.
310 // <- (1) RAA delivered
311 // (3) is generated and send (4) CS -.
312 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
313 // know the per_commitment_point to use for it.
314 // <- (2) commitment_signed delivered
316 // B should send no response here
317 // (4) commitment_signed delivered ->
318 // <- RAA/commitment_signed delivered
321 // First nodes[0] generates an update_fee
322 let initial_feerate = get_feerate!(nodes[0], channel_id);
323 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
324 check_added_monitors!(nodes[0], 1);
326 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
327 assert_eq!(events_0.len(), 1);
328 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
329 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
330 (update_fee.as_ref().unwrap(), commitment_signed)
332 _ => panic!("Unexpected event"),
335 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
336 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
337 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
338 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
339 check_added_monitors!(nodes[1], 1);
341 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
343 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
344 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
345 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
347 // Create the (3) update_fee message that nodes[0] will generate before it does...
348 let mut update_msg_2 = msgs::UpdateFee {
349 channel_id: update_msg_1.channel_id.clone(),
350 feerate_per_kw: (initial_feerate + 30) as u32,
353 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
355 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
357 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
359 // Deliver (1), generating (3) and (4)
360 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
361 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
362 check_added_monitors!(nodes[0], 1);
363 assert!(as_second_update.update_add_htlcs.is_empty());
364 assert!(as_second_update.update_fulfill_htlcs.is_empty());
365 assert!(as_second_update.update_fail_htlcs.is_empty());
366 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
367 // Check that the update_fee newly generated matches what we delivered:
368 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
369 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
371 // Deliver (2) commitment_signed
372 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
373 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
374 check_added_monitors!(nodes[0], 1);
375 // No commitment_signed so get_event_msg's assert(len == 1) passes
377 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
378 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
379 check_added_monitors!(nodes[1], 1);
382 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
383 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
384 check_added_monitors!(nodes[1], 1);
386 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
387 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
388 check_added_monitors!(nodes[0], 1);
390 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
391 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
392 // No commitment_signed so get_event_msg's assert(len == 1) passes
393 check_added_monitors!(nodes[0], 1);
395 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
396 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
397 check_added_monitors!(nodes[1], 1);
401 fn test_1_conf_open() {
402 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
403 // tests that we properly send one in that case.
404 let mut alice_config = UserConfig::default();
405 alice_config.own_channel_config.minimum_depth = 1;
406 alice_config.channel_options.announced_channel = true;
407 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
408 let mut bob_config = UserConfig::default();
409 bob_config.own_channel_config.minimum_depth = 1;
410 bob_config.channel_options.announced_channel = true;
411 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
412 let chanmon_cfgs = create_chanmon_cfgs(2);
413 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
414 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
415 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
417 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
419 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
422 connect_block(&nodes[1], &block, 1);
423 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()));
425 connect_block(&nodes[0], &block, 1);
426 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
427 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
430 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
431 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
432 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
436 fn do_test_sanity_on_in_flight_opens(steps: u8) {
437 // Previously, we had issues deserializing channels when we hadn't connected the first block
438 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
439 // serialization round-trips and simply do steps towards opening a channel and then drop the
442 let chanmon_cfgs = create_chanmon_cfgs(2);
443 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
444 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
445 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
447 if steps & 0b1000_0000 != 0{
449 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
452 connect_block(&nodes[0], &block, 1);
453 connect_block(&nodes[1], &block, 1);
456 if steps & 0x0f == 0 { return; }
457 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
458 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
460 if steps & 0x0f == 1 { return; }
461 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
462 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
464 if steps & 0x0f == 2 { return; }
465 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
467 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
469 if steps & 0x0f == 3 { return; }
470 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
471 check_added_monitors!(nodes[0], 0);
472 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
474 if steps & 0x0f == 4 { return; }
475 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
477 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
478 assert_eq!(added_monitors.len(), 1);
479 assert_eq!(added_monitors[0].0, funding_output);
480 added_monitors.clear();
482 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
484 if steps & 0x0f == 5 { return; }
485 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
487 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
488 assert_eq!(added_monitors.len(), 1);
489 assert_eq!(added_monitors[0].0, funding_output);
490 added_monitors.clear();
493 let events_4 = nodes[0].node.get_and_clear_pending_events();
494 assert_eq!(events_4.len(), 1);
496 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
497 assert_eq!(user_channel_id, 42);
498 assert_eq!(*funding_txo, funding_output);
500 _ => panic!("Unexpected event"),
503 if steps & 0x0f == 6 { return; }
504 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
506 if steps & 0x0f == 7 { return; }
507 confirm_transaction(&nodes[0], &tx);
508 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
512 fn test_sanity_on_in_flight_opens() {
513 do_test_sanity_on_in_flight_opens(0);
514 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
515 do_test_sanity_on_in_flight_opens(1);
516 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
517 do_test_sanity_on_in_flight_opens(2);
518 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
519 do_test_sanity_on_in_flight_opens(3);
520 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
521 do_test_sanity_on_in_flight_opens(4);
522 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
523 do_test_sanity_on_in_flight_opens(5);
524 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
525 do_test_sanity_on_in_flight_opens(6);
526 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
527 do_test_sanity_on_in_flight_opens(7);
528 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
529 do_test_sanity_on_in_flight_opens(8);
530 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
534 fn test_update_fee_vanilla() {
535 let chanmon_cfgs = create_chanmon_cfgs(2);
536 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
537 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
538 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
539 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
540 let channel_id = chan.2;
542 let feerate = get_feerate!(nodes[0], channel_id);
543 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
544 check_added_monitors!(nodes[0], 1);
546 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
547 assert_eq!(events_0.len(), 1);
548 let (update_msg, commitment_signed) = match events_0[0] {
549 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 } } => {
550 (update_fee.as_ref(), commitment_signed)
552 _ => panic!("Unexpected event"),
554 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
556 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
557 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
558 check_added_monitors!(nodes[1], 1);
560 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
561 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
562 check_added_monitors!(nodes[0], 1);
564 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
565 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
566 // No commitment_signed so get_event_msg's assert(len == 1) passes
567 check_added_monitors!(nodes[0], 1);
569 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
570 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
571 check_added_monitors!(nodes[1], 1);
575 fn test_update_fee_that_funder_cannot_afford() {
576 let chanmon_cfgs = create_chanmon_cfgs(2);
577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
579 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
580 let channel_value = 1888;
581 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
582 let channel_id = chan.2;
585 nodes[0].node.update_fee(channel_id, feerate).unwrap();
586 check_added_monitors!(nodes[0], 1);
587 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
589 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
591 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
593 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
594 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
596 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
598 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
599 let num_htlcs = commitment_tx.output.len() - 2;
600 let total_fee: u64 = feerate as u64 * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
601 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
602 actual_fee = channel_value - actual_fee;
603 assert_eq!(total_fee, actual_fee);
606 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
607 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
608 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
609 check_added_monitors!(nodes[0], 1);
611 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
613 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
615 //While producing the commitment_signed response after handling a received update_fee request the
616 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
617 //Should produce and error.
618 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
619 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
620 check_added_monitors!(nodes[1], 1);
621 check_closed_broadcast!(nodes[1], true);
625 fn test_update_fee_with_fundee_update_add_htlc() {
626 let chanmon_cfgs = create_chanmon_cfgs(2);
627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
629 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
630 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
631 let channel_id = chan.2;
632 let logger = test_utils::TestLogger::new();
635 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
637 let feerate = get_feerate!(nodes[0], channel_id);
638 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
639 check_added_monitors!(nodes[0], 1);
641 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
642 assert_eq!(events_0.len(), 1);
643 let (update_msg, commitment_signed) = match events_0[0] {
644 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 } } => {
645 (update_fee.as_ref(), commitment_signed)
647 _ => panic!("Unexpected event"),
649 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
650 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
651 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
652 check_added_monitors!(nodes[1], 1);
654 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
655 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
656 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();
658 // nothing happens since node[1] is in AwaitingRemoteRevoke
659 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
661 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
662 assert_eq!(added_monitors.len(), 0);
663 added_monitors.clear();
665 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
666 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
667 // node[1] has nothing to do
669 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
670 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
671 check_added_monitors!(nodes[0], 1);
673 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
674 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
675 // No commitment_signed so get_event_msg's assert(len == 1) passes
676 check_added_monitors!(nodes[0], 1);
677 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
678 check_added_monitors!(nodes[1], 1);
679 // AwaitingRemoteRevoke ends here
681 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
682 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
683 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
684 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
685 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
686 assert_eq!(commitment_update.update_fee.is_none(), true);
688 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
689 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
690 check_added_monitors!(nodes[0], 1);
691 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
693 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
694 check_added_monitors!(nodes[1], 1);
695 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
697 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
698 check_added_monitors!(nodes[1], 1);
699 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
700 // No commitment_signed so get_event_msg's assert(len == 1) passes
702 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
703 check_added_monitors!(nodes[0], 1);
704 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
706 expect_pending_htlcs_forwardable!(nodes[0]);
708 let events = nodes[0].node.get_and_clear_pending_events();
709 assert_eq!(events.len(), 1);
711 Event::PaymentReceived { .. } => { },
712 _ => panic!("Unexpected event"),
715 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
717 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
718 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
719 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
723 fn test_update_fee() {
724 let chanmon_cfgs = create_chanmon_cfgs(2);
725 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
726 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
727 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
728 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
729 let channel_id = chan.2;
732 // (1) update_fee/commitment_signed ->
733 // <- (2) revoke_and_ack
734 // .- send (3) commitment_signed
735 // (4) update_fee/commitment_signed ->
736 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
737 // <- (3) commitment_signed delivered
738 // send (6) revoke_and_ack -.
739 // <- (5) deliver revoke_and_ack
740 // (6) deliver revoke_and_ack ->
741 // .- send (7) commitment_signed in response to (4)
742 // <- (7) deliver commitment_signed
745 // Create and deliver (1)...
746 let feerate = get_feerate!(nodes[0], channel_id);
747 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
748 check_added_monitors!(nodes[0], 1);
750 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
751 assert_eq!(events_0.len(), 1);
752 let (update_msg, commitment_signed) = match events_0[0] {
753 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 } } => {
754 (update_fee.as_ref(), commitment_signed)
756 _ => panic!("Unexpected event"),
758 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
760 // Generate (2) and (3):
761 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
762 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
763 check_added_monitors!(nodes[1], 1);
766 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
767 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
768 check_added_monitors!(nodes[0], 1);
770 // Create and deliver (4)...
771 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
772 check_added_monitors!(nodes[0], 1);
773 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
774 assert_eq!(events_0.len(), 1);
775 let (update_msg, commitment_signed) = match events_0[0] {
776 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 } } => {
777 (update_fee.as_ref(), commitment_signed)
779 _ => panic!("Unexpected event"),
782 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
783 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
784 check_added_monitors!(nodes[1], 1);
786 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
787 // No commitment_signed so get_event_msg's assert(len == 1) passes
789 // Handle (3), creating (6):
790 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
791 check_added_monitors!(nodes[0], 1);
792 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
793 // No commitment_signed so get_event_msg's assert(len == 1) passes
796 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
797 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
798 check_added_monitors!(nodes[0], 1);
800 // Deliver (6), creating (7):
801 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
802 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
803 assert!(commitment_update.update_add_htlcs.is_empty());
804 assert!(commitment_update.update_fulfill_htlcs.is_empty());
805 assert!(commitment_update.update_fail_htlcs.is_empty());
806 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
807 assert!(commitment_update.update_fee.is_none());
808 check_added_monitors!(nodes[1], 1);
811 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
812 check_added_monitors!(nodes[0], 1);
813 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
814 // No commitment_signed so get_event_msg's assert(len == 1) passes
816 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
817 check_added_monitors!(nodes[1], 1);
818 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
820 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
821 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
822 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
826 fn pre_funding_lock_shutdown_test() {
827 // Test sending a shutdown prior to funding_locked after funding generation
828 let chanmon_cfgs = create_chanmon_cfgs(2);
829 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
830 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
831 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
832 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
833 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
834 connect_block(&nodes[0], &Block { header, txdata: vec![tx.clone()]}, 1);
835 connect_block(&nodes[1], &Block { header, txdata: vec![tx.clone()]}, 1);
837 nodes[0].node.close_channel(&OutPoint { txid: tx.txid(), index: 0 }.to_channel_id()).unwrap();
838 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
839 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
840 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
841 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
843 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
844 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
845 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
846 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
847 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
848 assert!(node_0_none.is_none());
850 assert!(nodes[0].node.list_channels().is_empty());
851 assert!(nodes[1].node.list_channels().is_empty());
855 fn updates_shutdown_wait() {
856 // Test sending a shutdown with outstanding updates pending
857 let chanmon_cfgs = create_chanmon_cfgs(3);
858 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
859 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
860 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
861 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
862 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
863 let logger = test_utils::TestLogger::new();
865 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
867 nodes[0].node.close_channel(&chan_1.2).unwrap();
868 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
869 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
870 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
871 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
873 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
874 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
876 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
878 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
879 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
880 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();
881 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();
882 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
883 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
885 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
886 check_added_monitors!(nodes[2], 1);
887 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
888 assert!(updates.update_add_htlcs.is_empty());
889 assert!(updates.update_fail_htlcs.is_empty());
890 assert!(updates.update_fail_malformed_htlcs.is_empty());
891 assert!(updates.update_fee.is_none());
892 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
893 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
894 check_added_monitors!(nodes[1], 1);
895 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
896 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
898 assert!(updates_2.update_add_htlcs.is_empty());
899 assert!(updates_2.update_fail_htlcs.is_empty());
900 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
901 assert!(updates_2.update_fee.is_none());
902 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
903 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
904 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
906 let events = nodes[0].node.get_and_clear_pending_events();
907 assert_eq!(events.len(), 1);
909 Event::PaymentSent { ref payment_preimage } => {
910 assert_eq!(our_payment_preimage, *payment_preimage);
912 _ => panic!("Unexpected event"),
915 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
916 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
917 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
918 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
919 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
920 assert!(node_0_none.is_none());
922 assert!(nodes[0].node.list_channels().is_empty());
924 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
925 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
926 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
927 assert!(nodes[1].node.list_channels().is_empty());
928 assert!(nodes[2].node.list_channels().is_empty());
932 fn htlc_fail_async_shutdown() {
933 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
934 let chanmon_cfgs = create_chanmon_cfgs(3);
935 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
936 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
937 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
938 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
939 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
940 let logger = test_utils::TestLogger::new();
942 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
943 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
944 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();
945 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
946 check_added_monitors!(nodes[0], 1);
947 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
948 assert_eq!(updates.update_add_htlcs.len(), 1);
949 assert!(updates.update_fulfill_htlcs.is_empty());
950 assert!(updates.update_fail_htlcs.is_empty());
951 assert!(updates.update_fail_malformed_htlcs.is_empty());
952 assert!(updates.update_fee.is_none());
954 nodes[1].node.close_channel(&chan_1.2).unwrap();
955 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
956 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
957 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
959 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
960 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
961 check_added_monitors!(nodes[1], 1);
962 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
963 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
965 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
966 assert!(updates_2.update_add_htlcs.is_empty());
967 assert!(updates_2.update_fulfill_htlcs.is_empty());
968 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
969 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
970 assert!(updates_2.update_fee.is_none());
972 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
973 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
975 expect_payment_failed!(nodes[0], our_payment_hash, false);
977 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
978 assert_eq!(msg_events.len(), 2);
979 let node_0_closing_signed = match msg_events[0] {
980 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
981 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
984 _ => panic!("Unexpected event"),
986 match msg_events[1] {
987 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
988 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
990 _ => panic!("Unexpected event"),
993 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
994 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
995 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
996 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
997 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
998 assert!(node_0_none.is_none());
1000 assert!(nodes[0].node.list_channels().is_empty());
1002 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1003 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1004 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1005 assert!(nodes[1].node.list_channels().is_empty());
1006 assert!(nodes[2].node.list_channels().is_empty());
1009 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1010 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1011 // messages delivered prior to disconnect
1012 let chanmon_cfgs = create_chanmon_cfgs(3);
1013 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1014 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1015 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1016 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1017 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1019 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1021 nodes[1].node.close_channel(&chan_1.2).unwrap();
1022 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1024 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1025 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1027 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1031 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1032 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1034 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1035 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1036 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1037 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1039 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1040 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1041 assert!(node_1_shutdown == node_1_2nd_shutdown);
1043 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1044 let node_0_2nd_shutdown = if recv_count > 0 {
1045 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1046 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1049 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1050 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1051 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1053 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1055 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1056 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1058 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1059 check_added_monitors!(nodes[2], 1);
1060 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1061 assert!(updates.update_add_htlcs.is_empty());
1062 assert!(updates.update_fail_htlcs.is_empty());
1063 assert!(updates.update_fail_malformed_htlcs.is_empty());
1064 assert!(updates.update_fee.is_none());
1065 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1066 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1067 check_added_monitors!(nodes[1], 1);
1068 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1069 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1071 assert!(updates_2.update_add_htlcs.is_empty());
1072 assert!(updates_2.update_fail_htlcs.is_empty());
1073 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1074 assert!(updates_2.update_fee.is_none());
1075 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1076 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1077 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1079 let events = nodes[0].node.get_and_clear_pending_events();
1080 assert_eq!(events.len(), 1);
1082 Event::PaymentSent { ref payment_preimage } => {
1083 assert_eq!(our_payment_preimage, *payment_preimage);
1085 _ => panic!("Unexpected event"),
1088 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1090 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1091 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1092 assert!(node_1_closing_signed.is_some());
1095 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1096 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1098 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1099 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1100 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1101 if recv_count == 0 {
1102 // If all closing_signeds weren't delivered we can just resume where we left off...
1103 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1105 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1106 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1107 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1109 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1110 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1111 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1113 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1114 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1116 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1117 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1118 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1120 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1121 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1122 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1123 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1124 assert!(node_0_none.is_none());
1126 // If one node, however, received + responded with an identical closing_signed we end
1127 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1128 // There isn't really anything better we can do simply, but in the future we might
1129 // explore storing a set of recently-closed channels that got disconnected during
1130 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1131 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1133 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1135 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1136 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1137 assert_eq!(msg_events.len(), 1);
1138 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1140 &ErrorAction::SendErrorMessage { ref msg } => {
1141 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1142 assert_eq!(msg.channel_id, chan_1.2);
1144 _ => panic!("Unexpected event!"),
1146 } else { panic!("Needed SendErrorMessage close"); }
1148 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1149 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1150 // closing_signed so we do it ourselves
1151 check_closed_broadcast!(nodes[0], false);
1152 check_added_monitors!(nodes[0], 1);
1155 assert!(nodes[0].node.list_channels().is_empty());
1157 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1158 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1159 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1160 assert!(nodes[1].node.list_channels().is_empty());
1161 assert!(nodes[2].node.list_channels().is_empty());
1165 fn test_shutdown_rebroadcast() {
1166 do_test_shutdown_rebroadcast(0);
1167 do_test_shutdown_rebroadcast(1);
1168 do_test_shutdown_rebroadcast(2);
1172 fn fake_network_test() {
1173 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1174 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1175 let chanmon_cfgs = create_chanmon_cfgs(4);
1176 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1177 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1178 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1180 // Create some initial channels
1181 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1182 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1183 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1185 // Rebalance the network a bit by relaying one payment through all the channels...
1186 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1187 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1188 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1189 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1191 // Send some more payments
1192 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1193 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1194 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1196 // Test failure packets
1197 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1198 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1200 // Add a new channel that skips 3
1201 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1203 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1204 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1205 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1206 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1207 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1208 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1209 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1211 // Do some rebalance loop payments, simultaneously
1212 let mut hops = Vec::with_capacity(3);
1213 hops.push(RouteHop {
1214 pubkey: nodes[2].node.get_our_node_id(),
1215 node_features: NodeFeatures::empty(),
1216 short_channel_id: chan_2.0.contents.short_channel_id,
1217 channel_features: ChannelFeatures::empty(),
1219 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1221 hops.push(RouteHop {
1222 pubkey: nodes[3].node.get_our_node_id(),
1223 node_features: NodeFeatures::empty(),
1224 short_channel_id: chan_3.0.contents.short_channel_id,
1225 channel_features: ChannelFeatures::empty(),
1227 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1229 hops.push(RouteHop {
1230 pubkey: nodes[1].node.get_our_node_id(),
1231 node_features: NodeFeatures::empty(),
1232 short_channel_id: chan_4.0.contents.short_channel_id,
1233 channel_features: ChannelFeatures::empty(),
1235 cltv_expiry_delta: TEST_FINAL_CLTV,
1237 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;
1238 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;
1239 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1241 let mut hops = Vec::with_capacity(3);
1242 hops.push(RouteHop {
1243 pubkey: nodes[3].node.get_our_node_id(),
1244 node_features: NodeFeatures::empty(),
1245 short_channel_id: chan_4.0.contents.short_channel_id,
1246 channel_features: ChannelFeatures::empty(),
1248 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1250 hops.push(RouteHop {
1251 pubkey: nodes[2].node.get_our_node_id(),
1252 node_features: NodeFeatures::empty(),
1253 short_channel_id: chan_3.0.contents.short_channel_id,
1254 channel_features: ChannelFeatures::empty(),
1256 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1258 hops.push(RouteHop {
1259 pubkey: nodes[1].node.get_our_node_id(),
1260 node_features: NodeFeatures::empty(),
1261 short_channel_id: chan_2.0.contents.short_channel_id,
1262 channel_features: ChannelFeatures::empty(),
1264 cltv_expiry_delta: TEST_FINAL_CLTV,
1266 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;
1267 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;
1268 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1270 // Claim the rebalances...
1271 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1272 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1274 // Add a duplicate new channel from 2 to 4
1275 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1277 // Send some payments across both channels
1278 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1279 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1280 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1283 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1284 let events = nodes[0].node.get_and_clear_pending_msg_events();
1285 assert_eq!(events.len(), 0);
1286 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);
1288 //TODO: Test that routes work again here as we've been notified that the channel is full
1290 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1291 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1292 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1294 // Close down the channels...
1295 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1296 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1297 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1298 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1299 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1303 fn holding_cell_htlc_counting() {
1304 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1305 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1306 // commitment dance rounds.
1307 let chanmon_cfgs = create_chanmon_cfgs(3);
1308 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1309 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1310 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1311 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1312 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1313 let logger = test_utils::TestLogger::new();
1315 let mut payments = Vec::new();
1316 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1317 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1318 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1319 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();
1320 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1321 payments.push((payment_preimage, payment_hash));
1323 check_added_monitors!(nodes[1], 1);
1325 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1326 assert_eq!(events.len(), 1);
1327 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1328 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1330 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1331 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1333 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1335 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1336 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();
1337 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { ref err },
1338 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
1339 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1340 nodes[1].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1343 // This should also be true if we try to forward a payment.
1344 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1346 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1347 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();
1348 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1349 check_added_monitors!(nodes[0], 1);
1352 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1353 assert_eq!(events.len(), 1);
1354 let payment_event = SendEvent::from_event(events.pop().unwrap());
1355 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1357 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1358 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1359 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1360 // fails), the second will process the resulting failure and fail the HTLC backward.
1361 expect_pending_htlcs_forwardable!(nodes[1]);
1362 expect_pending_htlcs_forwardable!(nodes[1]);
1363 check_added_monitors!(nodes[1], 1);
1365 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1366 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1367 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1369 let events = nodes[0].node.get_and_clear_pending_msg_events();
1370 assert_eq!(events.len(), 1);
1372 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1373 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1375 _ => panic!("Unexpected event"),
1378 expect_payment_failed!(nodes[0], payment_hash_2, false);
1380 // Now forward all the pending HTLCs and claim them back
1381 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1382 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1383 check_added_monitors!(nodes[2], 1);
1385 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1386 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1387 check_added_monitors!(nodes[1], 1);
1388 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1390 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1391 check_added_monitors!(nodes[1], 1);
1392 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1394 for ref update in as_updates.update_add_htlcs.iter() {
1395 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1397 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1398 check_added_monitors!(nodes[2], 1);
1399 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1400 check_added_monitors!(nodes[2], 1);
1401 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1403 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1404 check_added_monitors!(nodes[1], 1);
1405 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1406 check_added_monitors!(nodes[1], 1);
1407 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1409 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1410 check_added_monitors!(nodes[2], 1);
1412 expect_pending_htlcs_forwardable!(nodes[2]);
1414 let events = nodes[2].node.get_and_clear_pending_events();
1415 assert_eq!(events.len(), payments.len());
1416 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1418 &Event::PaymentReceived { ref payment_hash, .. } => {
1419 assert_eq!(*payment_hash, *hash);
1421 _ => panic!("Unexpected event"),
1425 for (preimage, _) in payments.drain(..) {
1426 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1429 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1433 fn duplicate_htlc_test() {
1434 // Test that we accept duplicate payment_hash HTLCs across the network and that
1435 // claiming/failing them are all separate and don't affect each other
1436 let chanmon_cfgs = create_chanmon_cfgs(6);
1437 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1438 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1439 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1441 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1442 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1443 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1444 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1445 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1446 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1448 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1450 *nodes[0].network_payment_count.borrow_mut() -= 1;
1451 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1453 *nodes[0].network_payment_count.borrow_mut() -= 1;
1454 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1456 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1457 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1458 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1462 fn test_duplicate_htlc_different_direction_onchain() {
1463 // Test that ChannelMonitor doesn't generate 2 preimage txn
1464 // when we have 2 HTLCs with same preimage that go across a node
1465 // in opposite directions.
1466 let chanmon_cfgs = create_chanmon_cfgs(2);
1467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1471 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1472 let logger = test_utils::TestLogger::new();
1475 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1477 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1479 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1480 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();
1481 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1483 // Provide preimage to node 0 by claiming payment
1484 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1485 check_added_monitors!(nodes[0], 1);
1487 // Broadcast node 1 commitment txn
1488 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1490 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1491 let mut has_both_htlcs = 0; // check htlcs match ones committed
1492 for outp in remote_txn[0].output.iter() {
1493 if outp.value == 800_000 / 1000 {
1494 has_both_htlcs += 1;
1495 } else if outp.value == 900_000 / 1000 {
1496 has_both_htlcs += 1;
1499 assert_eq!(has_both_htlcs, 2);
1501 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1502 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1503 check_added_monitors!(nodes[0], 1);
1505 // Check we only broadcast 1 timeout tx
1506 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1507 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()) };
1508 assert_eq!(claim_txn.len(), 5);
1509 check_spends!(claim_txn[2], chan_1.3);
1510 check_spends!(claim_txn[3], claim_txn[2]);
1511 assert_eq!(htlc_pair.0.input.len(), 1);
1512 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1513 check_spends!(htlc_pair.0, remote_txn[0]);
1514 assert_eq!(htlc_pair.1.input.len(), 1);
1515 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1516 check_spends!(htlc_pair.1, remote_txn[0]);
1518 let events = nodes[0].node.get_and_clear_pending_msg_events();
1519 assert_eq!(events.len(), 2);
1522 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1523 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, .. } } => {
1524 assert!(update_add_htlcs.is_empty());
1525 assert!(update_fail_htlcs.is_empty());
1526 assert_eq!(update_fulfill_htlcs.len(), 1);
1527 assert!(update_fail_malformed_htlcs.is_empty());
1528 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1530 _ => panic!("Unexpected event"),
1536 fn test_basic_channel_reserve() {
1537 let chanmon_cfgs = create_chanmon_cfgs(2);
1538 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1539 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1540 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1541 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1542 let logger = test_utils::TestLogger::new();
1544 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1545 let channel_reserve = chan_stat.channel_reserve_msat;
1547 // The 2* and +1 are for the fee spike reserve.
1548 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
1549 let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], chan.2), 1 + 1);
1550 let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1551 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1552 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();
1553 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
1555 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
1557 &APIError::ChannelUnavailable{ref err} =>
1558 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
1559 _ => panic!("Unexpected error variant"),
1562 _ => panic!("Unexpected error variant"),
1564 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1565 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);
1567 send_payment(&nodes[0], &vec![&nodes[1]], max_can_send, max_can_send);
1571 fn test_fee_spike_violation_fails_htlc() {
1572 let chanmon_cfgs = create_chanmon_cfgs(2);
1573 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1574 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1575 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1576 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1577 let logger = test_utils::TestLogger::new();
1579 macro_rules! get_route_and_payment_hash {
1580 ($recv_value: expr) => {{
1581 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1582 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
1583 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();
1584 (route, payment_hash, payment_preimage)
1588 let (route, payment_hash, _) = get_route_and_payment_hash!(3460001);
1589 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1590 let secp_ctx = Secp256k1::new();
1591 let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1593 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1595 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1596 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3460001, &None, cur_height).unwrap();
1597 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1598 let msg = msgs::UpdateAddHTLC {
1601 amount_msat: htlc_msat,
1602 payment_hash: payment_hash,
1603 cltv_expiry: htlc_cltv,
1604 onion_routing_packet: onion_packet,
1607 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1609 // Now manually create the commitment_signed message corresponding to the update_add
1610 // nodes[0] just sent. In the code for construction of this message, "local" refers
1611 // to the sender of the message, and "remote" refers to the receiver.
1613 let feerate_per_kw = get_feerate!(nodes[0], chan.2);
1615 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1617 // Get the EnforcingChannelKeys for each channel, which will be used to (1) get the keys
1618 // needed to sign the new commitment tx and (2) sign the new commitment tx.
1619 let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point) = {
1620 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
1621 let local_chan = chan_lock.by_id.get(&chan.2).unwrap();
1622 let chan_keys = local_chan.get_keys();
1623 let pubkeys = chan_keys.pubkeys();
1624 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1625 chan_keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1626 chan_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx))
1628 let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point) = {
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,
1634 chan_keys.get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx))
1637 // Assemble the set of keys we can use for signatures for our commitment_signed message.
1638 let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1639 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint).unwrap();
1641 // Build the remote commitment transaction so we can sign it, and then later use the
1642 // signature for the commitment_signed message.
1643 let local_chan_balance = 1313;
1645 let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1647 amount_msat: 3460001,
1648 cltv_expiry: htlc_cltv,
1650 transaction_output_index: Some(1),
1653 let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1656 let local_chan_lock = nodes[0].node.channel_state.lock().unwrap();
1657 let local_chan = local_chan_lock.by_id.get(&chan.2).unwrap();
1658 let local_chan_keys = local_chan.get_keys();
1659 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1663 commit_tx_keys.clone(),
1665 &mut vec![(accepted_htlc_info, ())],
1666 &local_chan.channel_transaction_parameters.as_counterparty_broadcastable()
1668 local_chan_keys.sign_counterparty_commitment(&commitment_tx, &secp_ctx).unwrap()
1671 let commit_signed_msg = msgs::CommitmentSigned {
1674 htlc_signatures: res.1
1677 // Send the commitment_signed message to the nodes[1].
1678 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1679 let _ = nodes[1].node.get_and_clear_pending_msg_events();
1681 // Send the RAA to nodes[1].
1682 let raa_msg = msgs::RevokeAndACK {
1684 per_commitment_secret: local_secret,
1685 next_per_commitment_point: next_local_point
1687 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1689 let events = nodes[1].node.get_and_clear_pending_msg_events();
1690 assert_eq!(events.len(), 1);
1691 // Make sure the HTLC failed in the way we expect.
1693 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1694 assert_eq!(update_fail_htlcs.len(), 1);
1695 update_fail_htlcs[0].clone()
1697 _ => panic!("Unexpected event"),
1699 nodes[1].logger.assert_log("lightning::ln::channel".to_string(), "Attempting to fail HTLC due to fee spike buffer violation".to_string(), 1);
1701 check_added_monitors!(nodes[1], 2);
1705 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1706 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1707 // Set the fee rate for the channel very high, to the point where the fundee
1708 // sending any amount would result in a channel reserve violation. In this test
1709 // we check that we would be prevented from sending an HTLC in this situation.
1710 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1711 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1715 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1716 let logger = test_utils::TestLogger::new();
1718 macro_rules! get_route_and_payment_hash {
1719 ($recv_value: expr) => {{
1720 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1721 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1722 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();
1723 (route, payment_hash, payment_preimage)
1727 let (route, our_payment_hash, _) = get_route_and_payment_hash!(1000);
1728 unwrap_send_err!(nodes[1].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1729 assert_eq!(err, "Cannot send value that would put counterparty balance under holder-announced channel reserve value"));
1730 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1731 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);
1735 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1736 let mut chanmon_cfgs = create_chanmon_cfgs(2);
1737 // Set the fee rate for the channel very high, to the point where the funder
1738 // receiving 1 update_add_htlc would result in them closing the channel due
1739 // to channel reserve violation. This close could also happen if the fee went
1740 // up a more realistic amount, but many HTLCs were outstanding at the time of
1741 // the update_add_htlc.
1742 chanmon_cfgs[0].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1743 chanmon_cfgs[1].fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 6000 };
1744 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1745 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1746 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1747 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1748 let logger = test_utils::TestLogger::new();
1750 macro_rules! get_route_and_payment_hash {
1751 ($recv_value: expr) => {{
1752 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[1]);
1753 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1754 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();
1755 (route, payment_hash, payment_preimage)
1759 let (route, payment_hash, _) = get_route_and_payment_hash!(1000);
1760 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1761 let secp_ctx = Secp256k1::new();
1762 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1763 let cur_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1764 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1765 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 1000, &None, cur_height).unwrap();
1766 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
1767 let msg = msgs::UpdateAddHTLC {
1770 amount_msat: htlc_msat + 1,
1771 payment_hash: payment_hash,
1772 cltv_expiry: htlc_cltv,
1773 onion_routing_packet: onion_packet,
1776 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1777 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1778 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);
1779 assert_eq!(nodes[0].node.list_channels().len(), 0);
1780 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1781 assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1782 check_added_monitors!(nodes[0], 1);
1786 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1787 let chanmon_cfgs = create_chanmon_cfgs(3);
1788 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1789 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1790 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1791 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1792 let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1793 let logger = test_utils::TestLogger::new();
1795 macro_rules! get_route_and_payment_hash {
1796 ($recv_value: expr) => {{
1797 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1798 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1799 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();
1800 (route, payment_hash, payment_preimage)
1805 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1806 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
1807 let feerate = get_feerate!(nodes[0], chan.2);
1809 // Add a 2* and +1 for the fee spike reserve.
1810 let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1);
1811 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;
1812 let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1814 // Add a pending HTLC.
1815 let (route_1, our_payment_hash_1, _) = get_route_and_payment_hash!(amt_msat_1);
1816 let payment_event_1 = {
1817 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1818 check_added_monitors!(nodes[0], 1);
1820 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1821 assert_eq!(events.len(), 1);
1822 SendEvent::from_event(events.remove(0))
1824 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1826 // Attempt to trigger a channel reserve violation --> payment failure.
1827 let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2);
1828 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;
1829 let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1830 let (route_2, _, _) = get_route_and_payment_hash!(amt_msat_2);
1832 // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1833 let secp_ctx = Secp256k1::new();
1834 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1835 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1836 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1837 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route_2.paths[0], recv_value_2, &None, cur_height).unwrap();
1838 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1);
1839 let msg = msgs::UpdateAddHTLC {
1842 amount_msat: htlc_msat + 1,
1843 payment_hash: our_payment_hash_1,
1844 cltv_expiry: htlc_cltv,
1845 onion_routing_packet: onion_packet,
1848 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1849 // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1850 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote HTLC add would put them under remote reserve value".to_string(), 1);
1851 assert_eq!(nodes[1].node.list_channels().len(), 1);
1852 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1853 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1854 check_added_monitors!(nodes[1], 1);
1858 fn test_inbound_outbound_capacity_is_not_zero() {
1859 let chanmon_cfgs = create_chanmon_cfgs(2);
1860 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1861 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1862 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1863 let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
1864 let channels0 = node_chanmgrs[0].list_channels();
1865 let channels1 = node_chanmgrs[1].list_channels();
1866 assert_eq!(channels0.len(), 1);
1867 assert_eq!(channels1.len(), 1);
1869 assert_eq!(channels0[0].inbound_capacity_msat, 95000000);
1870 assert_eq!(channels1[0].outbound_capacity_msat, 95000000);
1872 assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000);
1873 assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000);
1876 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64) -> u64 {
1877 (COMMITMENT_TX_BASE_WEIGHT + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1881 fn test_channel_reserve_holding_cell_htlcs() {
1882 let chanmon_cfgs = create_chanmon_cfgs(3);
1883 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1884 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1885 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1886 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1887 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001, InitFeatures::known(), InitFeatures::known());
1888 let logger = test_utils::TestLogger::new();
1890 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1891 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1893 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1894 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1896 macro_rules! get_route_and_payment_hash {
1897 ($recv_value: expr) => {{
1898 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1899 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1900 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();
1901 (route, payment_hash, payment_preimage)
1905 macro_rules! expect_forward {
1907 let mut events = $node.node.get_and_clear_pending_msg_events();
1908 assert_eq!(events.len(), 1);
1909 check_added_monitors!($node, 1);
1910 let payment_event = SendEvent::from_event(events.remove(0));
1915 let feemsat = 239; // somehow we know?
1916 let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1917 let feerate = get_feerate!(nodes[0], chan_1.2);
1919 let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1921 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1923 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1924 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1925 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1926 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)));
1927 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1928 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);
1931 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1932 // nodes[0]'s wealth
1934 let amt_msat = recv_value_0 + total_fee_msat;
1935 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1936 // Also, ensure that each payment has enough to be over the dust limit to
1937 // ensure it'll be included in each commit tx fee calculation.
1938 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1939 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1940 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1943 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1945 let (stat01_, stat11_, stat12_, stat22_) = (
1946 get_channel_value_stat!(nodes[0], chan_1.2),
1947 get_channel_value_stat!(nodes[1], chan_1.2),
1948 get_channel_value_stat!(nodes[1], chan_2.2),
1949 get_channel_value_stat!(nodes[2], chan_2.2),
1952 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1953 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1954 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1955 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1956 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1959 // adding pending output.
1960 // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1961 // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1962 // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1963 // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1964 // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1965 // cases where 1 msat over X amount will cause a payment failure, but anything less than
1966 // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1967 // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1968 // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1970 let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1);
1971 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1972 let amt_msat_1 = recv_value_1 + total_fee_msat;
1974 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1975 let payment_event_1 = {
1976 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1977 check_added_monitors!(nodes[0], 1);
1979 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1980 assert_eq!(events.len(), 1);
1981 SendEvent::from_event(events.remove(0))
1983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1985 // channel reserve test with htlc pending output > 0
1986 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1988 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1989 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
1990 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
1991 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1994 // split the rest to test holding cell
1995 let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1);
1996 let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1997 let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1998 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
2000 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
2001 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);
2004 // now see if they go through on both sides
2005 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
2006 // but this will stuck in the holding cell
2007 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
2008 check_added_monitors!(nodes[0], 0);
2009 let events = nodes[0].node.get_and_clear_pending_events();
2010 assert_eq!(events.len(), 0);
2012 // test with outbound holding cell amount > 0
2014 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
2015 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
2016 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)));
2017 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2018 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);
2021 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
2022 // this will also stuck in the holding cell
2023 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
2024 check_added_monitors!(nodes[0], 0);
2025 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
2026 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2028 // flush the pending htlc
2029 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
2030 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2031 check_added_monitors!(nodes[1], 1);
2033 // the pending htlc should be promoted to committed
2034 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2035 check_added_monitors!(nodes[0], 1);
2036 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2038 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2039 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2040 // No commitment_signed so get_event_msg's assert(len == 1) passes
2041 check_added_monitors!(nodes[0], 1);
2043 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2044 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2045 check_added_monitors!(nodes[1], 1);
2047 expect_pending_htlcs_forwardable!(nodes[1]);
2049 let ref payment_event_11 = expect_forward!(nodes[1]);
2050 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2051 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2053 expect_pending_htlcs_forwardable!(nodes[2]);
2054 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
2056 // flush the htlcs in the holding cell
2057 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2058 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2059 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2060 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2061 expect_pending_htlcs_forwardable!(nodes[1]);
2063 let ref payment_event_3 = expect_forward!(nodes[1]);
2064 assert_eq!(payment_event_3.msgs.len(), 2);
2065 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2066 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2068 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2069 expect_pending_htlcs_forwardable!(nodes[2]);
2071 let events = nodes[2].node.get_and_clear_pending_events();
2072 assert_eq!(events.len(), 2);
2074 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2075 assert_eq!(our_payment_hash_21, *payment_hash);
2076 assert_eq!(*payment_secret, None);
2077 assert_eq!(recv_value_21, amt);
2079 _ => panic!("Unexpected event"),
2082 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
2083 assert_eq!(our_payment_hash_22, *payment_hash);
2084 assert_eq!(None, *payment_secret);
2085 assert_eq!(recv_value_22, amt);
2087 _ => panic!("Unexpected event"),
2090 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
2091 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
2092 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
2094 let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1);
2095 let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2097 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_3 + 1);
2098 let err = nodes[0].node.send_payment(&route, our_payment_hash, &None).err().unwrap();
2100 PaymentSendFailure::AllFailedRetrySafe(ref fails) => {
2102 &APIError::ChannelUnavailable{ref err} =>
2103 assert!(regex::Regex::new(r"Cannot send value that would put our balance under counterparty-announced channel reserve value \(\d+\)").unwrap().is_match(err)),
2104 _ => panic!("Unexpected error variant"),
2107 _ => panic!("Unexpected error variant"),
2109 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2110 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);
2113 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3, recv_value_3);
2115 let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1);
2116 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);
2117 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
2118 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2119 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2121 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
2122 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2126 fn channel_reserve_in_flight_removes() {
2127 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2128 // can send to its counterparty, but due to update ordering, the other side may not yet have
2129 // considered those HTLCs fully removed.
2130 // This tests that we don't count HTLCs which will not be included in the next remote
2131 // commitment transaction towards the reserve value (as it implies no commitment transaction
2132 // will be generated which violates the remote reserve value).
2133 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2135 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2136 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2137 // you only consider the value of the first HTLC, it may not),
2138 // * start routing a third HTLC from A to B,
2139 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2140 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2141 // * deliver the first fulfill from B
2142 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2144 // * deliver A's response CS and RAA.
2145 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2146 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
2147 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2148 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2149 let chanmon_cfgs = create_chanmon_cfgs(2);
2150 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2151 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2152 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2153 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2154 let logger = test_utils::TestLogger::new();
2156 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
2157 // Route the first two HTLCs.
2158 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
2159 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
2161 // Start routing the third HTLC (this is just used to get everyone in the right state).
2162 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
2164 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2165 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();
2166 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
2167 check_added_monitors!(nodes[0], 1);
2168 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2169 assert_eq!(events.len(), 1);
2170 SendEvent::from_event(events.remove(0))
2173 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2174 // initial fulfill/CS.
2175 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
2176 check_added_monitors!(nodes[1], 1);
2177 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2179 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2180 // remove the second HTLC when we send the HTLC back from B to A.
2181 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
2182 check_added_monitors!(nodes[1], 1);
2183 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2185 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2186 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2187 check_added_monitors!(nodes[0], 1);
2188 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2189 expect_payment_sent!(nodes[0], payment_preimage_1);
2191 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2192 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2193 check_added_monitors!(nodes[1], 1);
2194 // B is already AwaitingRAA, so cant generate a CS here
2195 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2197 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2198 check_added_monitors!(nodes[1], 1);
2199 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2201 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2202 check_added_monitors!(nodes[0], 1);
2203 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2205 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2206 check_added_monitors!(nodes[1], 1);
2207 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2209 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2210 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2211 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2212 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2213 // on-chain as necessary).
2214 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2215 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2216 check_added_monitors!(nodes[0], 1);
2217 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2218 expect_payment_sent!(nodes[0], payment_preimage_2);
2220 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2221 check_added_monitors!(nodes[1], 1);
2222 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2224 expect_pending_htlcs_forwardable!(nodes[1]);
2225 expect_payment_received!(nodes[1], payment_hash_3, 100000);
2227 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2228 // resolve the second HTLC from A's point of view.
2229 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2230 check_added_monitors!(nodes[0], 1);
2231 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2233 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2234 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2235 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
2237 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2238 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();
2239 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
2240 check_added_monitors!(nodes[1], 1);
2241 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2242 assert_eq!(events.len(), 1);
2243 SendEvent::from_event(events.remove(0))
2246 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2247 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2248 check_added_monitors!(nodes[0], 1);
2249 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2251 // Now just resolve all the outstanding messages/HTLCs for completeness...
2253 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2254 check_added_monitors!(nodes[1], 1);
2255 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2257 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2258 check_added_monitors!(nodes[1], 1);
2260 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2261 check_added_monitors!(nodes[0], 1);
2262 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2264 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2265 check_added_monitors!(nodes[1], 1);
2266 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2268 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2269 check_added_monitors!(nodes[0], 1);
2271 expect_pending_htlcs_forwardable!(nodes[0]);
2272 expect_payment_received!(nodes[0], payment_hash_4, 10000);
2274 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
2275 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
2279 fn channel_monitor_network_test() {
2280 // Simple test which builds a network of ChannelManagers, connects them to each other, and
2281 // tests that ChannelMonitor is able to recover from various states.
2282 let chanmon_cfgs = create_chanmon_cfgs(5);
2283 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2284 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2285 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2287 // Create some initial channels
2288 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2289 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2290 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
2291 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
2293 // Rebalance the network a bit by relaying one payment through all the channels...
2294 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2295 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2296 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2297 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
2299 // Simple case with no pending HTLCs:
2300 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
2301 check_added_monitors!(nodes[1], 1);
2303 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2304 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2305 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2306 check_added_monitors!(nodes[0], 1);
2307 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
2309 get_announce_close_broadcast_events(&nodes, 0, 1);
2310 assert_eq!(nodes[0].node.list_channels().len(), 0);
2311 assert_eq!(nodes[1].node.list_channels().len(), 1);
2313 // One pending HTLC is discarded by the force-close:
2314 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
2316 // Simple case of one pending HTLC to HTLC-Timeout
2317 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
2318 check_added_monitors!(nodes[1], 1);
2320 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2321 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2322 connect_block(&nodes[2], &Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
2323 check_added_monitors!(nodes[2], 1);
2324 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
2326 get_announce_close_broadcast_events(&nodes, 1, 2);
2327 assert_eq!(nodes[1].node.list_channels().len(), 0);
2328 assert_eq!(nodes[2].node.list_channels().len(), 1);
2330 macro_rules! claim_funds {
2331 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
2333 assert!($node.node.claim_funds($preimage, &None, $amount));
2334 check_added_monitors!($node, 1);
2336 let events = $node.node.get_and_clear_pending_msg_events();
2337 assert_eq!(events.len(), 1);
2339 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2340 assert!(update_add_htlcs.is_empty());
2341 assert!(update_fail_htlcs.is_empty());
2342 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2344 _ => panic!("Unexpected event"),
2350 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2351 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2352 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2353 check_added_monitors!(nodes[2], 1);
2354 let node2_commitment_txid;
2356 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2357 node2_commitment_txid = node_txn[0].txid();
2359 // Claim the payment on nodes[3], giving it knowledge of the preimage
2360 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2362 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2363 connect_block(&nodes[3], &Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2364 check_added_monitors!(nodes[3], 1);
2366 check_preimage_claim(&nodes[3], &node_txn);
2368 get_announce_close_broadcast_events(&nodes, 2, 3);
2369 assert_eq!(nodes[2].node.list_channels().len(), 0);
2370 assert_eq!(nodes[3].node.list_channels().len(), 1);
2372 { // Cheat and reset nodes[4]'s height to 1
2373 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2374 connect_block(&nodes[4], &Block { header, txdata: vec![] }, 1);
2377 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2378 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2379 // One pending HTLC to time out:
2380 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2381 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2384 let (close_chan_update_1, close_chan_update_2) = {
2385 let mut block = Block {
2386 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2389 connect_block(&nodes[3], &block, 2);
2390 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2392 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2395 connect_block(&nodes[3], &block, i);
2397 let events = nodes[3].node.get_and_clear_pending_msg_events();
2398 assert_eq!(events.len(), 1);
2399 let close_chan_update_1 = match events[0] {
2400 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2403 _ => panic!("Unexpected event"),
2405 check_added_monitors!(nodes[3], 1);
2407 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2409 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2410 node_txn.retain(|tx| {
2411 if tx.input[0].previous_output.txid == node2_commitment_txid {
2417 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2419 // Claim the payment on nodes[4], giving it knowledge of the preimage
2420 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2423 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2427 connect_block(&nodes[4], &block, 2);
2428 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2430 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2433 connect_block(&nodes[4], &block, i);
2435 let events = nodes[4].node.get_and_clear_pending_msg_events();
2436 assert_eq!(events.len(), 1);
2437 let close_chan_update_2 = match events[0] {
2438 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2441 _ => panic!("Unexpected event"),
2443 check_added_monitors!(nodes[4], 1);
2444 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2447 header: BlockHeader { version: 0x20000000, prev_blockhash: block.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
2448 txdata: vec![node_txn[0].clone()],
2450 connect_block(&nodes[4], &block, TEST_FINAL_CLTV - 5);
2452 check_preimage_claim(&nodes[4], &node_txn);
2453 (close_chan_update_1, close_chan_update_2)
2455 nodes[3].net_graph_msg_handler.handle_channel_update(&close_chan_update_2).unwrap();
2456 nodes[4].net_graph_msg_handler.handle_channel_update(&close_chan_update_1).unwrap();
2457 assert_eq!(nodes[3].node.list_channels().len(), 0);
2458 assert_eq!(nodes[4].node.list_channels().len(), 0);
2462 fn test_justice_tx() {
2463 // Test justice txn built on revoked HTLC-Success tx, against both sides
2464 let mut alice_config = UserConfig::default();
2465 alice_config.channel_options.announced_channel = true;
2466 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2467 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2468 let mut bob_config = UserConfig::default();
2469 bob_config.channel_options.announced_channel = true;
2470 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2471 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2472 let user_cfgs = [Some(alice_config), Some(bob_config)];
2473 let chanmon_cfgs = create_chanmon_cfgs(2);
2474 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2475 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2476 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2477 // Create some new channels:
2478 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2480 // A pending HTLC which will be revoked:
2481 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2482 // Get the will-be-revoked local txn from nodes[0]
2483 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2484 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2485 assert_eq!(revoked_local_txn[0].input.len(), 1);
2486 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2487 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2488 assert_eq!(revoked_local_txn[1].input.len(), 1);
2489 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2490 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2491 // Revoke the old state
2492 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2495 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2496 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2498 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2499 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2500 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2502 check_spends!(node_txn[0], revoked_local_txn[0]);
2503 node_txn.swap_remove(0);
2504 node_txn.truncate(1);
2506 check_added_monitors!(nodes[1], 1);
2507 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2509 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2510 // Verify broadcast of revoked HTLC-timeout
2511 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2512 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2513 check_added_monitors!(nodes[0], 1);
2514 // Broadcast revoked HTLC-timeout on node 1
2515 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2516 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2518 get_announce_close_broadcast_events(&nodes, 0, 1);
2520 assert_eq!(nodes[0].node.list_channels().len(), 0);
2521 assert_eq!(nodes[1].node.list_channels().len(), 0);
2523 // We test justice_tx build by A on B's revoked HTLC-Success tx
2524 // Create some new channels:
2525 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2527 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2531 // A pending HTLC which will be revoked:
2532 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2533 // Get the will-be-revoked local txn from B
2534 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2535 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2536 assert_eq!(revoked_local_txn[0].input.len(), 1);
2537 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2538 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2539 // Revoke the old state
2540 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2542 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2543 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2545 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2546 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2547 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2549 check_spends!(node_txn[0], revoked_local_txn[0]);
2550 node_txn.swap_remove(0);
2552 check_added_monitors!(nodes[0], 1);
2553 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2555 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2556 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2557 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2558 check_added_monitors!(nodes[1], 1);
2559 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2560 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2562 get_announce_close_broadcast_events(&nodes, 0, 1);
2563 assert_eq!(nodes[0].node.list_channels().len(), 0);
2564 assert_eq!(nodes[1].node.list_channels().len(), 0);
2568 fn revoked_output_claim() {
2569 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2570 // transaction is broadcast by its counterparty
2571 let chanmon_cfgs = create_chanmon_cfgs(2);
2572 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2573 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2574 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2575 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2576 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2577 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2578 assert_eq!(revoked_local_txn.len(), 1);
2579 // Only output is the full channel value back to nodes[0]:
2580 assert_eq!(revoked_local_txn[0].output.len(), 1);
2581 // Send a payment through, updating everyone's latest commitment txn
2582 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2584 // Inform nodes[1] that nodes[0] broadcast a stale tx
2585 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2586 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2587 check_added_monitors!(nodes[1], 1);
2588 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2589 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2591 check_spends!(node_txn[0], revoked_local_txn[0]);
2592 check_spends!(node_txn[1], chan_1.3);
2594 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2595 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2596 get_announce_close_broadcast_events(&nodes, 0, 1);
2597 check_added_monitors!(nodes[0], 1)
2601 fn claim_htlc_outputs_shared_tx() {
2602 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2603 let chanmon_cfgs = create_chanmon_cfgs(2);
2604 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2605 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2606 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608 // Create some new channel:
2609 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2611 // Rebalance the network to generate htlc in the two directions
2612 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2613 // 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
2614 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2615 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2617 // Get the will-be-revoked local txn from node[0]
2618 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2619 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2620 assert_eq!(revoked_local_txn[0].input.len(), 1);
2621 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2622 assert_eq!(revoked_local_txn[1].input.len(), 1);
2623 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2624 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2625 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2627 //Revoke the old state
2628 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2631 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2632 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2633 check_added_monitors!(nodes[0], 1);
2634 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2635 check_added_monitors!(nodes[1], 1);
2636 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2637 expect_payment_failed!(nodes[1], payment_hash_2, true);
2639 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2640 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2642 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2643 check_spends!(node_txn[0], revoked_local_txn[0]);
2645 let mut witness_lens = BTreeSet::new();
2646 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2647 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2648 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2649 assert_eq!(witness_lens.len(), 3);
2650 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2651 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2652 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2654 // Next nodes[1] broadcasts its current local tx state:
2655 assert_eq!(node_txn[1].input.len(), 1);
2656 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2658 assert_eq!(node_txn[2].input.len(), 1);
2659 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2660 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2661 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2662 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2663 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2665 get_announce_close_broadcast_events(&nodes, 0, 1);
2666 assert_eq!(nodes[0].node.list_channels().len(), 0);
2667 assert_eq!(nodes[1].node.list_channels().len(), 0);
2671 fn claim_htlc_outputs_single_tx() {
2672 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2673 let chanmon_cfgs = create_chanmon_cfgs(2);
2674 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2675 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2676 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2678 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2680 // Rebalance the network to generate htlc in the two directions
2681 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2682 // 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
2683 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2684 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2685 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2687 // Get the will-be-revoked local txn from node[0]
2688 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2690 //Revoke the old state
2691 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2694 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2695 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2696 check_added_monitors!(nodes[0], 1);
2697 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2698 check_added_monitors!(nodes[1], 1);
2699 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2701 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
2702 expect_payment_failed!(nodes[1], payment_hash_2, true);
2704 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2705 assert_eq!(node_txn.len(), 9);
2706 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2707 // ChannelManager: local commmitment + local HTLC-timeout (2)
2708 // 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)
2709 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2711 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2712 assert_eq!(node_txn[2].input.len(), 1);
2713 check_spends!(node_txn[2], chan_1.3);
2714 assert_eq!(node_txn[3].input.len(), 1);
2715 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2716 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2717 check_spends!(node_txn[3], node_txn[2]);
2719 // Justice transactions are indices 1-2-4
2720 assert_eq!(node_txn[0].input.len(), 1);
2721 assert_eq!(node_txn[1].input.len(), 1);
2722 assert_eq!(node_txn[4].input.len(), 1);
2724 check_spends!(node_txn[0], revoked_local_txn[0]);
2725 check_spends!(node_txn[1], revoked_local_txn[0]);
2726 check_spends!(node_txn[4], revoked_local_txn[0]);
2728 let mut witness_lens = BTreeSet::new();
2729 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2730 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2731 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2732 assert_eq!(witness_lens.len(), 3);
2733 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2734 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2735 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2737 get_announce_close_broadcast_events(&nodes, 0, 1);
2738 assert_eq!(nodes[0].node.list_channels().len(), 0);
2739 assert_eq!(nodes[1].node.list_channels().len(), 0);
2743 fn test_htlc_on_chain_success() {
2744 // Test that in case of a unilateral close onchain, we detect the state of output and pass
2745 // the preimage backward accordingly. So here we test that ChannelManager is
2746 // broadcasting the right event to other nodes in payment path.
2747 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2748 // A --------------------> B ----------------------> C (preimage)
2749 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2750 // commitment transaction was broadcast.
2751 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2753 // B should be able to claim via preimage if A then broadcasts its local tx.
2754 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2755 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2756 // PaymentSent event).
2758 let chanmon_cfgs = create_chanmon_cfgs(3);
2759 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2760 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2761 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2763 // Create some initial channels
2764 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2765 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2767 // Rebalance the network a bit by relaying one payment through all the channels...
2768 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2769 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2771 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2772 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2773 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2775 // Broadcast legit commitment tx from C on B's chain
2776 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2777 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2778 assert_eq!(commitment_tx.len(), 1);
2779 check_spends!(commitment_tx[0], chan_2.3);
2780 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2781 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2782 check_added_monitors!(nodes[2], 2);
2783 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2784 assert!(updates.update_add_htlcs.is_empty());
2785 assert!(updates.update_fail_htlcs.is_empty());
2786 assert!(updates.update_fail_malformed_htlcs.is_empty());
2787 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2789 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2790 check_closed_broadcast!(nodes[2], false);
2791 check_added_monitors!(nodes[2], 1);
2792 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)
2793 assert_eq!(node_txn.len(), 5);
2794 assert_eq!(node_txn[0], node_txn[3]);
2795 assert_eq!(node_txn[1], node_txn[4]);
2796 assert_eq!(node_txn[2], commitment_tx[0]);
2797 check_spends!(node_txn[0], commitment_tx[0]);
2798 check_spends!(node_txn[1], commitment_tx[0]);
2799 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2800 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2801 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2802 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2803 assert_eq!(node_txn[0].lock_time, 0);
2804 assert_eq!(node_txn[1].lock_time, 0);
2806 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2807 connect_block(&nodes[1], &Block { header, txdata: node_txn}, 1);
2809 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2810 assert_eq!(added_monitors.len(), 1);
2811 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2812 added_monitors.clear();
2814 let events = nodes[1].node.get_and_clear_pending_msg_events();
2816 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2817 assert_eq!(added_monitors.len(), 2);
2818 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2819 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2820 added_monitors.clear();
2822 assert_eq!(events.len(), 2);
2824 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2825 _ => panic!("Unexpected event"),
2828 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, .. } } => {
2829 assert!(update_add_htlcs.is_empty());
2830 assert!(update_fail_htlcs.is_empty());
2831 assert_eq!(update_fulfill_htlcs.len(), 1);
2832 assert!(update_fail_malformed_htlcs.is_empty());
2833 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2835 _ => panic!("Unexpected event"),
2837 macro_rules! check_tx_local_broadcast {
2838 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2839 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2840 assert_eq!(node_txn.len(), 5);
2841 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2842 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2843 check_spends!(node_txn[0], $commitment_tx);
2844 check_spends!(node_txn[1], $commitment_tx);
2845 assert_ne!(node_txn[0].lock_time, 0);
2846 assert_ne!(node_txn[1].lock_time, 0);
2848 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2849 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2850 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2851 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2853 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2854 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2855 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2856 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2858 check_spends!(node_txn[2], $chan_tx);
2859 check_spends!(node_txn[3], node_txn[2]);
2860 check_spends!(node_txn[4], node_txn[2]);
2861 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2862 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2863 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2864 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2865 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2866 assert_ne!(node_txn[3].lock_time, 0);
2867 assert_ne!(node_txn[4].lock_time, 0);
2871 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2872 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2873 // timeout-claim of the output that nodes[2] just claimed via success.
2874 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2876 // Broadcast legit commitment tx from A on B's chain
2877 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2878 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2879 check_spends!(commitment_tx[0], chan_1.3);
2880 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2881 check_closed_broadcast!(nodes[1], false);
2882 check_added_monitors!(nodes[1], 1);
2883 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2884 assert_eq!(node_txn.len(), 4);
2885 check_spends!(node_txn[0], commitment_tx[0]);
2886 assert_eq!(node_txn[0].input.len(), 2);
2887 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2888 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2889 assert_eq!(node_txn[0].lock_time, 0);
2890 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2891 check_spends!(node_txn[1], chan_1.3);
2892 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2893 check_spends!(node_txn[2], node_txn[1]);
2894 check_spends!(node_txn[3], node_txn[1]);
2895 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2896 // we already checked the same situation with A.
2898 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2899 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2900 check_closed_broadcast!(nodes[0], false);
2901 check_added_monitors!(nodes[0], 1);
2902 let events = nodes[0].node.get_and_clear_pending_events();
2903 assert_eq!(events.len(), 2);
2904 let mut first_claimed = false;
2905 for event in events {
2907 Event::PaymentSent { payment_preimage } => {
2908 if payment_preimage == our_payment_preimage {
2909 assert!(!first_claimed);
2910 first_claimed = true;
2912 assert_eq!(payment_preimage, our_payment_preimage_2);
2915 _ => panic!("Unexpected event"),
2918 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2922 fn test_htlc_on_chain_timeout() {
2923 // Test that in case of a unilateral close onchain, we detect the state of output and
2924 // timeout the HTLC backward accordingly. So here we test that ChannelManager is
2925 // broadcasting the right event to other nodes in payment path.
2926 // A ------------------> B ----------------------> C (timeout)
2927 // B's commitment tx C's commitment tx
2929 // B's HTLC timeout tx B's timeout tx
2931 let chanmon_cfgs = create_chanmon_cfgs(3);
2932 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2933 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2934 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2936 // Create some intial channels
2937 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2938 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2940 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2941 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2942 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2944 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2945 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2947 // Broadcast legit commitment tx from C on B's chain
2948 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2949 check_spends!(commitment_tx[0], chan_2.3);
2950 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2951 check_added_monitors!(nodes[2], 0);
2952 expect_pending_htlcs_forwardable!(nodes[2]);
2953 check_added_monitors!(nodes[2], 1);
2955 let events = nodes[2].node.get_and_clear_pending_msg_events();
2956 assert_eq!(events.len(), 1);
2958 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, .. } } => {
2959 assert!(update_add_htlcs.is_empty());
2960 assert!(!update_fail_htlcs.is_empty());
2961 assert!(update_fulfill_htlcs.is_empty());
2962 assert!(update_fail_malformed_htlcs.is_empty());
2963 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2965 _ => panic!("Unexpected event"),
2967 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2968 check_closed_broadcast!(nodes[2], false);
2969 check_added_monitors!(nodes[2], 1);
2970 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2971 assert_eq!(node_txn.len(), 1);
2972 check_spends!(node_txn[0], chan_2.3);
2973 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2975 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2976 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2977 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2980 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2981 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2982 assert_eq!(node_txn[1], node_txn[3]);
2983 assert_eq!(node_txn[2], node_txn[4]);
2985 check_spends!(node_txn[0], commitment_tx[0]);
2986 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2988 check_spends!(node_txn[1], chan_2.3);
2989 check_spends!(node_txn[2], node_txn[1]);
2990 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2991 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2993 timeout_tx = node_txn[0].clone();
2997 connect_block(&nodes[1], &Block { header, txdata: vec![timeout_tx]}, 1);
2998 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
2999 check_added_monitors!(nodes[1], 1);
3000 check_closed_broadcast!(nodes[1], false);
3002 expect_pending_htlcs_forwardable!(nodes[1]);
3003 check_added_monitors!(nodes[1], 1);
3004 let events = nodes[1].node.get_and_clear_pending_msg_events();
3005 assert_eq!(events.len(), 1);
3007 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, .. } } => {
3008 assert!(update_add_htlcs.is_empty());
3009 assert!(!update_fail_htlcs.is_empty());
3010 assert!(update_fulfill_htlcs.is_empty());
3011 assert!(update_fail_malformed_htlcs.is_empty());
3012 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3014 _ => panic!("Unexpected event"),
3016 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
3017 assert_eq!(node_txn.len(), 0);
3019 // Broadcast legit commitment tx from B on A's chain
3020 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3021 check_spends!(commitment_tx[0], chan_1.3);
3023 connect_block(&nodes[0], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
3024 check_closed_broadcast!(nodes[0], false);
3025 check_added_monitors!(nodes[0], 1);
3026 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
3027 assert_eq!(node_txn.len(), 3);
3028 check_spends!(node_txn[0], commitment_tx[0]);
3029 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3030 check_spends!(node_txn[1], chan_1.3);
3031 check_spends!(node_txn[2], node_txn[1]);
3032 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
3033 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3037 fn test_simple_commitment_revoked_fail_backward() {
3038 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3039 // and fail backward accordingly.
3041 let chanmon_cfgs = create_chanmon_cfgs(3);
3042 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3043 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3044 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3046 // Create some initial channels
3047 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3048 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3050 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3051 // Get the will-be-revoked local txn from nodes[2]
3052 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3053 // Revoke the old state
3054 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
3056 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3058 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3059 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3060 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3061 check_added_monitors!(nodes[1], 1);
3062 check_closed_broadcast!(nodes[1], false);
3064 expect_pending_htlcs_forwardable!(nodes[1]);
3065 check_added_monitors!(nodes[1], 1);
3066 let events = nodes[1].node.get_and_clear_pending_msg_events();
3067 assert_eq!(events.len(), 1);
3069 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, .. } } => {
3070 assert!(update_add_htlcs.is_empty());
3071 assert_eq!(update_fail_htlcs.len(), 1);
3072 assert!(update_fulfill_htlcs.is_empty());
3073 assert!(update_fail_malformed_htlcs.is_empty());
3074 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3076 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3077 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3079 let events = nodes[0].node.get_and_clear_pending_msg_events();
3080 assert_eq!(events.len(), 1);
3082 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3083 _ => panic!("Unexpected event"),
3085 expect_payment_failed!(nodes[0], payment_hash, false);
3087 _ => panic!("Unexpected event"),
3091 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3092 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3093 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3094 // commitment transaction anymore.
3095 // To do this, we have the peer which will broadcast a revoked commitment transaction send
3096 // a number of update_fail/commitment_signed updates without ever sending the RAA in
3097 // response to our commitment_signed. This is somewhat misbehavior-y, though not
3098 // technically disallowed and we should probably handle it reasonably.
3099 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3100 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3102 // * Once we move it out of our holding cell/add it, we will immediately include it in a
3103 // commitment_signed (implying it will be in the latest remote commitment transaction).
3104 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3105 // and once they revoke the previous commitment transaction (allowing us to send a new
3106 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3107 let chanmon_cfgs = create_chanmon_cfgs(3);
3108 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3109 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3110 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3112 // Create some initial channels
3113 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3114 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3116 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3117 // Get the will-be-revoked local txn from nodes[2]
3118 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3119 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3120 // Revoke the old state
3121 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
3123 let value = if use_dust {
3124 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3125 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3126 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().holder_dust_limit_satoshis * 1000
3129 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3130 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3131 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3133 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
3134 expect_pending_htlcs_forwardable!(nodes[2]);
3135 check_added_monitors!(nodes[2], 1);
3136 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3137 assert!(updates.update_add_htlcs.is_empty());
3138 assert!(updates.update_fulfill_htlcs.is_empty());
3139 assert!(updates.update_fail_malformed_htlcs.is_empty());
3140 assert_eq!(updates.update_fail_htlcs.len(), 1);
3141 assert!(updates.update_fee.is_none());
3142 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3143 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3144 // Drop the last RAA from 3 -> 2
3146 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
3147 expect_pending_htlcs_forwardable!(nodes[2]);
3148 check_added_monitors!(nodes[2], 1);
3149 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3150 assert!(updates.update_add_htlcs.is_empty());
3151 assert!(updates.update_fulfill_htlcs.is_empty());
3152 assert!(updates.update_fail_malformed_htlcs.is_empty());
3153 assert_eq!(updates.update_fail_htlcs.len(), 1);
3154 assert!(updates.update_fee.is_none());
3155 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3156 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3157 check_added_monitors!(nodes[1], 1);
3158 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3159 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3160 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3161 check_added_monitors!(nodes[2], 1);
3163 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
3164 expect_pending_htlcs_forwardable!(nodes[2]);
3165 check_added_monitors!(nodes[2], 1);
3166 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3167 assert!(updates.update_add_htlcs.is_empty());
3168 assert!(updates.update_fulfill_htlcs.is_empty());
3169 assert!(updates.update_fail_malformed_htlcs.is_empty());
3170 assert_eq!(updates.update_fail_htlcs.len(), 1);
3171 assert!(updates.update_fee.is_none());
3172 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3173 // At this point first_payment_hash has dropped out of the latest two commitment
3174 // transactions that nodes[1] is tracking...
3175 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3176 check_added_monitors!(nodes[1], 1);
3177 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3178 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3179 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3180 check_added_monitors!(nodes[2], 1);
3182 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3183 // on nodes[2]'s RAA.
3184 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3185 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3186 let logger = test_utils::TestLogger::new();
3187 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();
3188 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
3189 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3190 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3191 check_added_monitors!(nodes[1], 0);
3194 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3195 // One monitor for the new revocation preimage, no second on as we won't generate a new
3196 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3197 check_added_monitors!(nodes[1], 1);
3198 let events = nodes[1].node.get_and_clear_pending_events();
3199 assert_eq!(events.len(), 1);
3201 Event::PendingHTLCsForwardable { .. } => { },
3202 _ => panic!("Unexpected event"),
3204 // Deliberately don't process the pending fail-back so they all fail back at once after
3205 // block connection just like the !deliver_bs_raa case
3208 let mut failed_htlcs = HashSet::new();
3209 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3211 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3212 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3213 check_added_monitors!(nodes[1], 1);
3214 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
3216 let events = nodes[1].node.get_and_clear_pending_events();
3217 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
3219 Event::PaymentFailed { ref payment_hash, .. } => {
3220 assert_eq!(*payment_hash, fourth_payment_hash);
3222 _ => panic!("Unexpected event"),
3224 if !deliver_bs_raa {
3226 Event::PendingHTLCsForwardable { .. } => { },
3227 _ => panic!("Unexpected event"),
3230 nodes[1].node.process_pending_htlc_forwards();
3231 check_added_monitors!(nodes[1], 1);
3233 let events = nodes[1].node.get_and_clear_pending_msg_events();
3234 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
3235 match events[if deliver_bs_raa { 1 } else { 0 }] {
3236 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3237 _ => panic!("Unexpected event"),
3241 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, .. } } => {
3242 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3243 assert_eq!(update_add_htlcs.len(), 1);
3244 assert!(update_fulfill_htlcs.is_empty());
3245 assert!(update_fail_htlcs.is_empty());
3246 assert!(update_fail_malformed_htlcs.is_empty());
3248 _ => panic!("Unexpected event"),
3251 match events[if deliver_bs_raa { 2 } else { 1 }] {
3252 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, .. } } => {
3253 assert!(update_add_htlcs.is_empty());
3254 assert_eq!(update_fail_htlcs.len(), 3);
3255 assert!(update_fulfill_htlcs.is_empty());
3256 assert!(update_fail_malformed_htlcs.is_empty());
3257 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3259 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3260 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3261 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3263 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3265 let events = nodes[0].node.get_and_clear_pending_msg_events();
3266 // If we delivered B's RAA we got an unknown preimage error, not something
3267 // that we should update our routing table for.
3268 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
3269 for event in events {
3271 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
3272 _ => panic!("Unexpected event"),
3275 let events = nodes[0].node.get_and_clear_pending_events();
3276 assert_eq!(events.len(), 3);
3278 Event::PaymentFailed { ref payment_hash, .. } => {
3279 assert!(failed_htlcs.insert(payment_hash.0));
3281 _ => panic!("Unexpected event"),
3284 Event::PaymentFailed { ref payment_hash, .. } => {
3285 assert!(failed_htlcs.insert(payment_hash.0));
3287 _ => panic!("Unexpected event"),
3290 Event::PaymentFailed { ref payment_hash, .. } => {
3291 assert!(failed_htlcs.insert(payment_hash.0));
3293 _ => panic!("Unexpected event"),
3296 _ => panic!("Unexpected event"),
3299 assert!(failed_htlcs.contains(&first_payment_hash.0));
3300 assert!(failed_htlcs.contains(&second_payment_hash.0));
3301 assert!(failed_htlcs.contains(&third_payment_hash.0));
3305 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3306 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3307 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3308 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3309 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3313 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3314 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3315 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3316 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3317 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3321 fn fail_backward_pending_htlc_upon_channel_failure() {
3322 let chanmon_cfgs = create_chanmon_cfgs(2);
3323 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3324 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3325 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3326 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
3327 let logger = test_utils::TestLogger::new();
3329 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3331 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
3332 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3333 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();
3334 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
3335 check_added_monitors!(nodes[0], 1);
3337 let payment_event = {
3338 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3339 assert_eq!(events.len(), 1);
3340 SendEvent::from_event(events.remove(0))
3342 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3343 assert_eq!(payment_event.msgs.len(), 1);
3346 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3347 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3349 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3350 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();
3351 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
3352 check_added_monitors!(nodes[0], 0);
3354 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3357 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3359 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
3361 let secp_ctx = Secp256k1::new();
3362 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3363 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
3364 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3365 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();
3366 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3367 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3368 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3370 // Send a 0-msat update_add_htlc to fail the channel.
3371 let update_add_htlc = msgs::UpdateAddHTLC {
3377 onion_routing_packet,
3379 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3382 // Check that Alice fails backward the pending HTLC from the second payment.
3383 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3384 check_closed_broadcast!(nodes[0], true);
3385 check_added_monitors!(nodes[0], 1);
3389 fn test_htlc_ignore_latest_remote_commitment() {
3390 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3391 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3392 let chanmon_cfgs = create_chanmon_cfgs(2);
3393 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3394 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3395 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3396 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3398 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3399 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3400 check_closed_broadcast!(nodes[0], false);
3401 check_added_monitors!(nodes[0], 1);
3403 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3404 assert_eq!(node_txn.len(), 2);
3406 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3407 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3408 check_closed_broadcast!(nodes[1], false);
3409 check_added_monitors!(nodes[1], 1);
3411 // Duplicate the connect_block call since this may happen due to other listeners
3412 // registering new transactions
3413 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3417 fn test_force_close_fail_back() {
3418 // Check which HTLCs are failed-backwards on channel force-closure
3419 let chanmon_cfgs = create_chanmon_cfgs(3);
3420 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3421 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3422 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3423 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3424 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3425 let logger = test_utils::TestLogger::new();
3427 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3429 let mut payment_event = {
3430 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3431 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();
3432 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3433 check_added_monitors!(nodes[0], 1);
3435 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3436 assert_eq!(events.len(), 1);
3437 SendEvent::from_event(events.remove(0))
3440 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3441 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3443 expect_pending_htlcs_forwardable!(nodes[1]);
3445 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3446 assert_eq!(events_2.len(), 1);
3447 payment_event = SendEvent::from_event(events_2.remove(0));
3448 assert_eq!(payment_event.msgs.len(), 1);
3450 check_added_monitors!(nodes[1], 1);
3451 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3452 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3453 check_added_monitors!(nodes[2], 1);
3454 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3456 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3457 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3458 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3460 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3461 check_closed_broadcast!(nodes[2], false);
3462 check_added_monitors!(nodes[2], 1);
3464 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3465 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3466 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3467 // back to nodes[1] upon timeout otherwise.
3468 assert_eq!(node_txn.len(), 1);
3473 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
3474 txdata: vec![tx.clone()],
3476 connect_block(&nodes[1], &block, 1);
3478 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3479 check_closed_broadcast!(nodes[1], false);
3480 check_added_monitors!(nodes[1], 1);
3482 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3484 let mut monitors = nodes[2].chain_monitor.chain_monitor.monitors.lock().unwrap();
3485 monitors.get_mut(&OutPoint{ txid: Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), index: 0 }).unwrap()
3486 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &node_cfgs[2].fee_estimator, &&logger);
3488 connect_block(&nodes[2], &block, 1);
3489 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3490 assert_eq!(node_txn.len(), 1);
3491 assert_eq!(node_txn[0].input.len(), 1);
3492 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3493 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3494 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3496 check_spends!(node_txn[0], tx);
3500 fn test_unconf_chan() {
3501 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3502 let chanmon_cfgs = create_chanmon_cfgs(2);
3503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3506 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3508 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3509 assert_eq!(channel_state.by_id.len(), 1);
3510 assert_eq!(channel_state.short_to_id.len(), 1);
3511 mem::drop(channel_state);
3513 let mut headers = Vec::new();
3514 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3515 headers.push(header.clone());
3517 header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3518 headers.push(header.clone());
3520 while !headers.is_empty() {
3521 nodes[0].node.block_disconnected(&headers.pop().unwrap());
3523 check_closed_broadcast!(nodes[0], false);
3524 check_added_monitors!(nodes[0], 1);
3525 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3526 assert_eq!(channel_state.by_id.len(), 0);
3527 assert_eq!(channel_state.short_to_id.len(), 0);
3531 fn test_simple_peer_disconnect() {
3532 // Test that we can reconnect when there are no lost messages
3533 let chanmon_cfgs = create_chanmon_cfgs(3);
3534 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3535 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3536 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3537 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3538 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3540 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3541 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3542 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3544 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3545 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3546 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3547 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3549 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3550 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3551 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3553 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3554 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3555 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3556 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3558 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3559 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3561 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3562 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3564 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3566 let events = nodes[0].node.get_and_clear_pending_events();
3567 assert_eq!(events.len(), 2);
3569 Event::PaymentSent { payment_preimage } => {
3570 assert_eq!(payment_preimage, payment_preimage_3);
3572 _ => panic!("Unexpected event"),
3575 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3576 assert_eq!(payment_hash, payment_hash_5);
3577 assert!(rejected_by_dest);
3579 _ => panic!("Unexpected event"),
3583 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3584 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3587 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3588 // Test that we can reconnect when in-flight HTLC updates get dropped
3589 let chanmon_cfgs = create_chanmon_cfgs(2);
3590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3592 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3593 if messages_delivered == 0 {
3594 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3595 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3597 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3600 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3602 let logger = test_utils::TestLogger::new();
3603 let payment_event = {
3604 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3605 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3606 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3607 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3608 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3609 check_added_monitors!(nodes[0], 1);
3611 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3612 assert_eq!(events.len(), 1);
3613 SendEvent::from_event(events.remove(0))
3615 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3617 if messages_delivered < 2 {
3618 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3620 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3621 if messages_delivered >= 3 {
3622 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3623 check_added_monitors!(nodes[1], 1);
3624 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3626 if messages_delivered >= 4 {
3627 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3628 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3629 check_added_monitors!(nodes[0], 1);
3631 if messages_delivered >= 5 {
3632 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3633 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3634 // No commitment_signed so get_event_msg's assert(len == 1) passes
3635 check_added_monitors!(nodes[0], 1);
3637 if messages_delivered >= 6 {
3638 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3639 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3640 check_added_monitors!(nodes[1], 1);
3647 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3648 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3649 if messages_delivered < 3 {
3650 // Even if the funding_locked messages get exchanged, as long as nothing further was
3651 // received on either side, both sides will need to resend them.
3652 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3653 } else if messages_delivered == 3 {
3654 // nodes[0] still wants its RAA + commitment_signed
3655 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3656 } else if messages_delivered == 4 {
3657 // nodes[0] still wants its commitment_signed
3658 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3659 } else if messages_delivered == 5 {
3660 // nodes[1] still wants its final RAA
3661 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3662 } else if messages_delivered == 6 {
3663 // Everything was delivered...
3664 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3667 let events_1 = nodes[1].node.get_and_clear_pending_events();
3668 assert_eq!(events_1.len(), 1);
3670 Event::PendingHTLCsForwardable { .. } => { },
3671 _ => panic!("Unexpected event"),
3674 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3675 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3676 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3678 nodes[1].node.process_pending_htlc_forwards();
3680 let events_2 = nodes[1].node.get_and_clear_pending_events();
3681 assert_eq!(events_2.len(), 1);
3683 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3684 assert_eq!(payment_hash_1, *payment_hash);
3685 assert_eq!(*payment_secret, None);
3686 assert_eq!(amt, 1000000);
3688 _ => panic!("Unexpected event"),
3691 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3692 check_added_monitors!(nodes[1], 1);
3694 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3695 assert_eq!(events_3.len(), 1);
3696 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3697 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3698 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3699 assert!(updates.update_add_htlcs.is_empty());
3700 assert!(updates.update_fail_htlcs.is_empty());
3701 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3702 assert!(updates.update_fail_malformed_htlcs.is_empty());
3703 assert!(updates.update_fee.is_none());
3704 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3706 _ => panic!("Unexpected event"),
3709 if messages_delivered >= 1 {
3710 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3712 let events_4 = nodes[0].node.get_and_clear_pending_events();
3713 assert_eq!(events_4.len(), 1);
3715 Event::PaymentSent { ref payment_preimage } => {
3716 assert_eq!(payment_preimage_1, *payment_preimage);
3718 _ => panic!("Unexpected event"),
3721 if messages_delivered >= 2 {
3722 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3723 check_added_monitors!(nodes[0], 1);
3724 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3726 if messages_delivered >= 3 {
3727 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3728 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3729 check_added_monitors!(nodes[1], 1);
3731 if messages_delivered >= 4 {
3732 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3733 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3734 // No commitment_signed so get_event_msg's assert(len == 1) passes
3735 check_added_monitors!(nodes[1], 1);
3737 if messages_delivered >= 5 {
3738 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3739 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3740 check_added_monitors!(nodes[0], 1);
3747 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3748 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3749 if messages_delivered < 2 {
3750 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3751 //TODO: Deduplicate PaymentSent events, then enable this if:
3752 //if messages_delivered < 1 {
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 } else if messages_delivered == 2 {
3763 // nodes[0] still wants its RAA + commitment_signed
3764 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3765 } else if messages_delivered == 3 {
3766 // nodes[0] still wants its commitment_signed
3767 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3768 } else if messages_delivered == 4 {
3769 // nodes[1] still wants its final RAA
3770 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3771 } else if messages_delivered == 5 {
3772 // Everything was delivered...
3773 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3776 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3777 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3778 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3780 // Channel should still work fine...
3781 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3782 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(),
3783 &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels().iter().collect::<Vec<_>>()),
3784 &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3785 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3786 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3790 fn test_drop_messages_peer_disconnect_a() {
3791 do_test_drop_messages_peer_disconnect(0);
3792 do_test_drop_messages_peer_disconnect(1);
3793 do_test_drop_messages_peer_disconnect(2);
3794 do_test_drop_messages_peer_disconnect(3);
3798 fn test_drop_messages_peer_disconnect_b() {
3799 do_test_drop_messages_peer_disconnect(4);
3800 do_test_drop_messages_peer_disconnect(5);
3801 do_test_drop_messages_peer_disconnect(6);
3805 fn test_funding_peer_disconnect() {
3806 // Test that we can lock in our funding tx while disconnected
3807 let chanmon_cfgs = create_chanmon_cfgs(2);
3808 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3809 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3810 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3811 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3813 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3814 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3816 confirm_transaction(&nodes[0], &tx);
3817 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3818 assert_eq!(events_1.len(), 1);
3820 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3821 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3823 _ => panic!("Unexpected event"),
3826 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3828 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3829 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3831 confirm_transaction(&nodes[1], &tx);
3832 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3833 assert_eq!(events_2.len(), 2);
3834 let funding_locked = match events_2[0] {
3835 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3836 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3839 _ => panic!("Unexpected event"),
3841 let bs_announcement_sigs = match events_2[1] {
3842 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3843 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3846 _ => panic!("Unexpected event"),
3849 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3851 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3852 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3853 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3854 assert_eq!(events_3.len(), 2);
3855 let as_announcement_sigs = match events_3[0] {
3856 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3857 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3860 _ => panic!("Unexpected event"),
3862 let (as_announcement, as_update) = match events_3[1] {
3863 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3864 (msg.clone(), update_msg.clone())
3866 _ => panic!("Unexpected event"),
3869 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3870 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3871 assert_eq!(events_4.len(), 1);
3872 let (_, bs_update) = match events_4[0] {
3873 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3874 (msg.clone(), update_msg.clone())
3876 _ => panic!("Unexpected event"),
3879 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3880 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3881 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3883 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3884 let logger = test_utils::TestLogger::new();
3885 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();
3886 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3887 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3891 fn test_drop_messages_peer_disconnect_dual_htlc() {
3892 // Test that we can handle reconnecting when both sides of a channel have pending
3893 // commitment_updates when we disconnect.
3894 let chanmon_cfgs = create_chanmon_cfgs(2);
3895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3897 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3898 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3899 let logger = test_utils::TestLogger::new();
3901 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3903 // Now try to send a second payment which will fail to send
3904 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3905 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3906 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();
3907 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3908 check_added_monitors!(nodes[0], 1);
3910 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3911 assert_eq!(events_1.len(), 1);
3913 MessageSendEvent::UpdateHTLCs { .. } => {},
3914 _ => panic!("Unexpected event"),
3917 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3918 check_added_monitors!(nodes[1], 1);
3920 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3921 assert_eq!(events_2.len(), 1);
3923 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 } } => {
3924 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3925 assert!(update_add_htlcs.is_empty());
3926 assert_eq!(update_fulfill_htlcs.len(), 1);
3927 assert!(update_fail_htlcs.is_empty());
3928 assert!(update_fail_malformed_htlcs.is_empty());
3929 assert!(update_fee.is_none());
3931 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3932 let events_3 = nodes[0].node.get_and_clear_pending_events();
3933 assert_eq!(events_3.len(), 1);
3935 Event::PaymentSent { ref payment_preimage } => {
3936 assert_eq!(*payment_preimage, payment_preimage_1);
3938 _ => panic!("Unexpected event"),
3941 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3942 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3943 // No commitment_signed so get_event_msg's assert(len == 1) passes
3944 check_added_monitors!(nodes[0], 1);
3946 _ => panic!("Unexpected event"),
3949 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3950 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3952 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3953 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3954 assert_eq!(reestablish_1.len(), 1);
3955 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3956 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3957 assert_eq!(reestablish_2.len(), 1);
3959 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3960 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3961 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3962 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3964 assert!(as_resp.0.is_none());
3965 assert!(bs_resp.0.is_none());
3967 assert!(bs_resp.1.is_none());
3968 assert!(bs_resp.2.is_none());
3970 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3972 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3973 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3974 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3975 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3976 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3977 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3978 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3979 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3980 // No commitment_signed so get_event_msg's assert(len == 1) passes
3981 check_added_monitors!(nodes[1], 1);
3983 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3984 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3985 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3986 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3987 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3988 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3989 assert!(bs_second_commitment_signed.update_fee.is_none());
3990 check_added_monitors!(nodes[1], 1);
3992 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3993 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3994 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3995 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3996 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3997 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3998 assert!(as_commitment_signed.update_fee.is_none());
3999 check_added_monitors!(nodes[0], 1);
4001 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4002 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4003 // No commitment_signed so get_event_msg's assert(len == 1) passes
4004 check_added_monitors!(nodes[0], 1);
4006 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4007 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4008 // No commitment_signed so get_event_msg's assert(len == 1) passes
4009 check_added_monitors!(nodes[1], 1);
4011 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4012 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4013 check_added_monitors!(nodes[1], 1);
4015 expect_pending_htlcs_forwardable!(nodes[1]);
4017 let events_5 = nodes[1].node.get_and_clear_pending_events();
4018 assert_eq!(events_5.len(), 1);
4020 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
4021 assert_eq!(payment_hash_2, *payment_hash);
4022 assert_eq!(*payment_secret, None);
4024 _ => panic!("Unexpected event"),
4027 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4028 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4029 check_added_monitors!(nodes[0], 1);
4031 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
4034 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4035 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4036 // to avoid our counterparty failing the channel.
4037 let chanmon_cfgs = create_chanmon_cfgs(2);
4038 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4039 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4040 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4042 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4043 let logger = test_utils::TestLogger::new();
4045 let our_payment_hash = if send_partial_mpp {
4046 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4047 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();
4048 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
4049 let payment_secret = PaymentSecret([0xdb; 32]);
4050 // Use the utility function send_payment_along_path to send the payment with MPP data which
4051 // indicates there are more HTLCs coming.
4052 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
4053 check_added_monitors!(nodes[0], 1);
4054 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4055 assert_eq!(events.len(), 1);
4056 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4057 // hop should *not* yet generate any PaymentReceived event(s).
4058 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
4061 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4064 let mut block = Block {
4065 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4068 connect_block(&nodes[0], &block, 101);
4069 connect_block(&nodes[1], &block, 101);
4070 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4071 block.header.prev_blockhash = block.block_hash();
4072 connect_block(&nodes[0], &block, i);
4073 connect_block(&nodes[1], &block, i);
4076 expect_pending_htlcs_forwardable!(nodes[1]);
4078 check_added_monitors!(nodes[1], 1);
4079 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4080 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4081 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4082 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4083 assert!(htlc_timeout_updates.update_fee.is_none());
4085 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4086 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4087 // 100_000 msat as u64, followed by a height of 123 as u32
4088 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
4089 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
4090 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4094 fn test_htlc_timeout() {
4095 do_test_htlc_timeout(true);
4096 do_test_htlc_timeout(false);
4099 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4100 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4101 let chanmon_cfgs = create_chanmon_cfgs(3);
4102 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4103 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4104 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4105 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4106 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4107 let logger = test_utils::TestLogger::new();
4109 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4110 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4112 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4113 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();
4114 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
4116 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4117 check_added_monitors!(nodes[1], 1);
4119 // Now attempt to route a second payment, which should be placed in the holding cell
4120 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4122 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
4123 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();
4124 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
4125 check_added_monitors!(nodes[0], 1);
4126 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4127 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4128 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4129 expect_pending_htlcs_forwardable!(nodes[1]);
4130 check_added_monitors!(nodes[1], 0);
4132 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
4133 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();
4134 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
4135 check_added_monitors!(nodes[1], 0);
4138 let mut block = Block {
4139 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
4142 connect_block(&nodes[1], &block, 101);
4143 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
4144 block.header.prev_blockhash = block.block_hash();
4145 connect_block(&nodes[1], &block, i);
4148 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4149 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4151 block.header.prev_blockhash = block.block_hash();
4152 connect_block(&nodes[1], &block, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS);
4155 expect_pending_htlcs_forwardable!(nodes[1]);
4156 check_added_monitors!(nodes[1], 1);
4157 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4158 assert_eq!(fail_commit.len(), 1);
4159 match fail_commit[0] {
4160 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4161 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4162 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4164 _ => unreachable!(),
4166 expect_payment_failed!(nodes[0], second_payment_hash, false);
4167 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
4169 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
4170 _ => panic!("Unexpected event"),
4173 panic!("Unexpected event");
4176 expect_payment_failed!(nodes[1], second_payment_hash, true);
4181 fn test_holding_cell_htlc_add_timeouts() {
4182 do_test_holding_cell_htlc_add_timeouts(false);
4183 do_test_holding_cell_htlc_add_timeouts(true);
4187 fn test_invalid_channel_announcement() {
4188 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
4189 let secp_ctx = Secp256k1::new();
4190 let chanmon_cfgs = create_chanmon_cfgs(2);
4191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4193 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4195 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
4197 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
4198 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
4199 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4200 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
4202 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 } );
4204 let as_bitcoin_key = as_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4205 let bs_bitcoin_key = bs_chan.get_keys().inner.holder_channel_pubkeys.funding_pubkey;
4207 let as_network_key = nodes[0].node.get_our_node_id();
4208 let bs_network_key = nodes[1].node.get_our_node_id();
4210 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
4212 let mut chan_announcement;
4214 macro_rules! dummy_unsigned_msg {
4216 msgs::UnsignedChannelAnnouncement {
4217 features: ChannelFeatures::known(),
4218 chain_hash: genesis_block(Network::Testnet).header.block_hash(),
4219 short_channel_id: as_chan.get_short_channel_id().unwrap(),
4220 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
4221 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
4222 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
4223 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
4224 excess_data: Vec::new(),
4229 macro_rules! sign_msg {
4230 ($unsigned_msg: expr) => {
4231 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
4232 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_keys().inner.funding_key);
4233 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_keys().inner.funding_key);
4234 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
4235 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
4236 chan_announcement = msgs::ChannelAnnouncement {
4237 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
4238 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
4239 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
4240 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
4241 contents: $unsigned_msg
4246 let unsigned_msg = dummy_unsigned_msg!();
4247 sign_msg!(unsigned_msg);
4248 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
4249 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 } );
4251 // Configured with Network::Testnet
4252 let mut unsigned_msg = dummy_unsigned_msg!();
4253 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.block_hash();
4254 sign_msg!(unsigned_msg);
4255 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4257 let mut unsigned_msg = dummy_unsigned_msg!();
4258 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
4259 sign_msg!(unsigned_msg);
4260 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
4264 fn test_no_txn_manager_serialize_deserialize() {
4265 let chanmon_cfgs = create_chanmon_cfgs(2);
4266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4268 let logger: test_utils::TestLogger;
4269 let fee_estimator: test_utils::TestFeeEstimator;
4270 let persister: test_utils::TestPersister;
4271 let new_chain_monitor: test_utils::TestChainMonitor;
4272 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4273 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4275 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
4277 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4279 let nodes_0_serialized = nodes[0].node.encode();
4280 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4281 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4283 logger = test_utils::TestLogger::new();
4284 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4285 persister = test_utils::TestPersister::new();
4286 let keys_manager = &chanmon_cfgs[0].keys_manager;
4287 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4288 nodes[0].chain_monitor = &new_chain_monitor;
4289 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4290 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4291 &mut chan_0_monitor_read, keys_manager).unwrap();
4292 assert!(chan_0_monitor_read.is_empty());
4294 let mut nodes_0_read = &nodes_0_serialized[..];
4295 let config = UserConfig::default();
4296 let (_, nodes_0_deserialized_tmp) = {
4297 let mut channel_monitors = HashMap::new();
4298 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4299 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4300 default_config: config,
4302 fee_estimator: &fee_estimator,
4303 chain_monitor: nodes[0].chain_monitor,
4304 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4309 nodes_0_deserialized = nodes_0_deserialized_tmp;
4310 assert!(nodes_0_read.is_empty());
4312 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4313 nodes[0].node = &nodes_0_deserialized;
4314 assert_eq!(nodes[0].node.list_channels().len(), 1);
4315 check_added_monitors!(nodes[0], 1);
4317 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4318 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4319 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4320 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4322 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4323 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4324 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4325 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4327 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4328 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4329 for node in nodes.iter() {
4330 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4331 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4332 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4335 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4339 fn test_manager_serialize_deserialize_events() {
4340 // This test makes sure the events field in ChannelManager survives de/serialization
4341 let chanmon_cfgs = create_chanmon_cfgs(2);
4342 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4343 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4344 let fee_estimator: test_utils::TestFeeEstimator;
4345 let persister: test_utils::TestPersister;
4346 let logger: test_utils::TestLogger;
4347 let new_chain_monitor: test_utils::TestChainMonitor;
4348 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4349 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4351 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
4352 let channel_value = 100000;
4353 let push_msat = 10001;
4354 let a_flags = InitFeatures::known();
4355 let b_flags = InitFeatures::known();
4356 let node_a = nodes.remove(0);
4357 let node_b = nodes.remove(0);
4358 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
4359 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()));
4360 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()));
4362 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
4364 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
4365 check_added_monitors!(node_a, 0);
4367 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()));
4369 let mut added_monitors = node_b.chain_monitor.added_monitors.lock().unwrap();
4370 assert_eq!(added_monitors.len(), 1);
4371 assert_eq!(added_monitors[0].0, funding_output);
4372 added_monitors.clear();
4375 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()));
4377 let mut added_monitors = node_a.chain_monitor.added_monitors.lock().unwrap();
4378 assert_eq!(added_monitors.len(), 1);
4379 assert_eq!(added_monitors[0].0, funding_output);
4380 added_monitors.clear();
4382 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4387 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4388 let nodes_0_serialized = nodes[0].node.encode();
4389 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4390 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4392 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4393 logger = test_utils::TestLogger::new();
4394 persister = test_utils::TestPersister::new();
4395 let keys_manager = &chanmon_cfgs[0].keys_manager;
4396 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4397 nodes[0].chain_monitor = &new_chain_monitor;
4398 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4399 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4400 &mut chan_0_monitor_read, keys_manager).unwrap();
4401 assert!(chan_0_monitor_read.is_empty());
4403 let mut nodes_0_read = &nodes_0_serialized[..];
4404 let config = UserConfig::default();
4405 let (_, nodes_0_deserialized_tmp) = {
4406 let mut channel_monitors = HashMap::new();
4407 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4408 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4409 default_config: config,
4411 fee_estimator: &fee_estimator,
4412 chain_monitor: nodes[0].chain_monitor,
4413 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4418 nodes_0_deserialized = nodes_0_deserialized_tmp;
4419 assert!(nodes_0_read.is_empty());
4421 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4423 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4424 nodes[0].node = &nodes_0_deserialized;
4426 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4427 let events_4 = nodes[0].node.get_and_clear_pending_events();
4428 assert_eq!(events_4.len(), 1);
4430 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4431 assert_eq!(user_channel_id, 42);
4432 assert_eq!(*funding_txo, funding_output);
4434 _ => panic!("Unexpected event"),
4437 // Make sure the channel is functioning as though the de/serialization never happened
4438 assert_eq!(nodes[0].node.list_channels().len(), 1);
4439 check_added_monitors!(nodes[0], 1);
4441 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4442 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4443 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4444 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4446 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4447 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4448 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4449 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4451 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4452 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4453 for node in nodes.iter() {
4454 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4455 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4456 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4459 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4463 fn test_simple_manager_serialize_deserialize() {
4464 let chanmon_cfgs = create_chanmon_cfgs(2);
4465 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4466 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4467 let logger: test_utils::TestLogger;
4468 let fee_estimator: test_utils::TestFeeEstimator;
4469 let persister: test_utils::TestPersister;
4470 let new_chain_monitor: test_utils::TestChainMonitor;
4471 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4472 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4473 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4475 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4476 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4478 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4480 let nodes_0_serialized = nodes[0].node.encode();
4481 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4482 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut chan_0_monitor_serialized).unwrap();
4484 logger = test_utils::TestLogger::new();
4485 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4486 persister = test_utils::TestPersister::new();
4487 let keys_manager = &chanmon_cfgs[0].keys_manager;
4488 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4489 nodes[0].chain_monitor = &new_chain_monitor;
4490 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4491 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(
4492 &mut chan_0_monitor_read, keys_manager).unwrap();
4493 assert!(chan_0_monitor_read.is_empty());
4495 let mut nodes_0_read = &nodes_0_serialized[..];
4496 let (_, nodes_0_deserialized_tmp) = {
4497 let mut channel_monitors = HashMap::new();
4498 channel_monitors.insert(chan_0_monitor.get_funding_txo().0, &mut chan_0_monitor);
4499 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4500 default_config: UserConfig::default(),
4502 fee_estimator: &fee_estimator,
4503 chain_monitor: nodes[0].chain_monitor,
4504 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4509 nodes_0_deserialized = nodes_0_deserialized_tmp;
4510 assert!(nodes_0_read.is_empty());
4512 assert!(nodes[0].chain_monitor.watch_channel(chan_0_monitor.get_funding_txo().0, chan_0_monitor).is_ok());
4513 nodes[0].node = &nodes_0_deserialized;
4514 check_added_monitors!(nodes[0], 1);
4516 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4518 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4519 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4523 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4524 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4525 let chanmon_cfgs = create_chanmon_cfgs(4);
4526 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4527 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4528 let logger: test_utils::TestLogger;
4529 let fee_estimator: test_utils::TestFeeEstimator;
4530 let persister: test_utils::TestPersister;
4531 let new_chain_monitor: test_utils::TestChainMonitor;
4532 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4533 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4534 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4535 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4536 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4538 let mut node_0_stale_monitors_serialized = Vec::new();
4539 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4540 let mut writer = test_utils::TestVecWriter(Vec::new());
4541 monitor.1.write(&mut writer).unwrap();
4542 node_0_stale_monitors_serialized.push(writer.0);
4545 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4547 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4548 let nodes_0_serialized = nodes[0].node.encode();
4550 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4551 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4552 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4553 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4555 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4557 let mut node_0_monitors_serialized = Vec::new();
4558 for monitor in nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter() {
4559 let mut writer = test_utils::TestVecWriter(Vec::new());
4560 monitor.1.write(&mut writer).unwrap();
4561 node_0_monitors_serialized.push(writer.0);
4564 logger = test_utils::TestLogger::new();
4565 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4566 persister = test_utils::TestPersister::new();
4567 let keys_manager = &chanmon_cfgs[0].keys_manager;
4568 new_chain_monitor = test_utils::TestChainMonitor::new(Some(nodes[0].chain_source), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator, &persister, keys_manager);
4569 nodes[0].chain_monitor = &new_chain_monitor;
4572 let mut node_0_stale_monitors = Vec::new();
4573 for serialized in node_0_stale_monitors_serialized.iter() {
4574 let mut read = &serialized[..];
4575 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
4576 assert!(read.is_empty());
4577 node_0_stale_monitors.push(monitor);
4580 let mut node_0_monitors = Vec::new();
4581 for serialized in node_0_monitors_serialized.iter() {
4582 let mut read = &serialized[..];
4583 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, keys_manager).unwrap();
4584 assert!(read.is_empty());
4585 node_0_monitors.push(monitor);
4588 let mut nodes_0_read = &nodes_0_serialized[..];
4589 if let Err(msgs::DecodeError::InvalidValue) =
4590 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4591 default_config: UserConfig::default(),
4593 fee_estimator: &fee_estimator,
4594 chain_monitor: nodes[0].chain_monitor,
4595 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4597 channel_monitors: node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4599 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4602 let mut nodes_0_read = &nodes_0_serialized[..];
4603 let (_, nodes_0_deserialized_tmp) =
4604 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4605 default_config: UserConfig::default(),
4607 fee_estimator: &fee_estimator,
4608 chain_monitor: nodes[0].chain_monitor,
4609 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4611 channel_monitors: node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().0, monitor) }).collect(),
4613 nodes_0_deserialized = nodes_0_deserialized_tmp;
4614 assert!(nodes_0_read.is_empty());
4616 { // Channel close should result in a commitment tx and an HTLC tx
4617 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4618 assert_eq!(txn.len(), 2);
4619 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4620 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4623 for monitor in node_0_monitors.drain(..) {
4624 assert!(nodes[0].chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor).is_ok());
4625 check_added_monitors!(nodes[0], 1);
4627 nodes[0].node = &nodes_0_deserialized;
4629 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4630 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4631 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4632 //... and we can even still claim the payment!
4633 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4635 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4636 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4637 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4638 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4639 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4640 assert_eq!(msg_events.len(), 1);
4641 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4643 &ErrorAction::SendErrorMessage { ref msg } => {
4644 assert_eq!(msg.channel_id, channel_id);
4646 _ => panic!("Unexpected event!"),
4651 macro_rules! check_spendable_outputs {
4652 ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4654 let events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4655 let mut txn = Vec::new();
4656 for event in events {
4658 Event::SpendableOutputs { ref outputs } => {
4659 for outp in outputs {
4661 SpendableOutputDescriptor::StaticOutputCounterpartyPayment { ref outpoint, ref output, ref key_derivation_params } => {
4663 previous_output: outpoint.into_bitcoin_outpoint(),
4664 script_sig: Script::new(),
4666 witness: Vec::new(),
4669 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4670 value: output.value,
4672 let mut spend_tx = Transaction {
4678 spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4679 let secp_ctx = Secp256k1::new();
4680 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4681 let remotepubkey = keys.pubkeys().payment_point;
4682 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4683 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4684 let remotesig = secp_ctx.sign(&sighash, &keys.inner.payment_key);
4685 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4686 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4687 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4690 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref revocation_pubkey } => {
4692 previous_output: outpoint.into_bitcoin_outpoint(),
4693 script_sig: Script::new(),
4694 sequence: *to_self_delay as u32,
4695 witness: Vec::new(),
4698 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4699 value: output.value,
4701 let mut spend_tx = Transaction {
4707 let secp_ctx = Secp256k1::new();
4708 let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4709 if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, &keys.inner.delayed_payment_base_key) {
4711 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4712 let witness_script = chan_utils::get_revokeable_redeemscript(revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4713 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
4714 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4715 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4716 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4717 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4718 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4719 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4723 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4724 let secp_ctx = Secp256k1::new();
4726 previous_output: outpoint.into_bitcoin_outpoint(),
4727 script_sig: Script::new(),
4729 witness: Vec::new(),
4732 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4733 value: output.value,
4735 let mut spend_tx = Transaction {
4739 output: vec![outp.clone()],
4741 spend_tx.output[0].value -= (spend_tx.get_weight() + 2 + 1 + 73 + 35 + 3) as u64 / 4; // (Max weight + 3 (to round up)) / 4
4743 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4745 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4747 Err(_) => panic!("Your RNG is busted"),
4750 Err(_) => panic!("Your rng is busted"),
4753 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4754 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4755 let sighash = Message::from_slice(&bip143::SigHashCache::new(&spend_tx).signature_hash(0, &witness_script, output.value, SigHashType::All)[..]).unwrap();
4756 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4757 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4758 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4759 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4765 _ => panic!("Unexpected event"),
4774 fn test_claim_sizeable_push_msat() {
4775 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4776 let chanmon_cfgs = create_chanmon_cfgs(2);
4777 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4778 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4779 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4781 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4782 nodes[1].node.force_close_channel(&chan.2);
4783 check_closed_broadcast!(nodes[1], false);
4784 check_added_monitors!(nodes[1], 1);
4785 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4786 assert_eq!(node_txn.len(), 1);
4787 check_spends!(node_txn[0], chan.3);
4788 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
4790 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4791 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4792 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4794 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4795 assert_eq!(spend_txn.len(), 1);
4796 check_spends!(spend_txn[0], node_txn[0]);
4800 fn test_claim_on_remote_sizeable_push_msat() {
4801 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4802 // to_remote output is encumbered by a P2WPKH
4803 let chanmon_cfgs = create_chanmon_cfgs(2);
4804 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4805 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4806 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4808 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4809 nodes[0].node.force_close_channel(&chan.2);
4810 check_closed_broadcast!(nodes[0], false);
4811 check_added_monitors!(nodes[0], 1);
4813 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4814 assert_eq!(node_txn.len(), 1);
4815 check_spends!(node_txn[0], chan.3);
4816 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
4818 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4819 connect_block(&nodes[1], &Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4820 check_closed_broadcast!(nodes[1], false);
4821 check_added_monitors!(nodes[1], 1);
4822 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4824 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4825 assert_eq!(spend_txn.len(), 1);
4826 check_spends!(spend_txn[0], node_txn[0]);
4830 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4831 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4832 // to_remote output is encumbered by a P2WPKH
4834 let chanmon_cfgs = create_chanmon_cfgs(2);
4835 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4836 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4837 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4839 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4840 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4841 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4842 assert_eq!(revoked_local_txn[0].input.len(), 1);
4843 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4845 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4846 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4847 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4848 check_closed_broadcast!(nodes[1], false);
4849 check_added_monitors!(nodes[1], 1);
4851 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4852 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4853 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4854 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4856 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4857 assert_eq!(spend_txn.len(), 2);
4858 check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4859 check_spends!(spend_txn[1], node_txn[0]);
4863 fn test_static_spendable_outputs_preimage_tx() {
4864 let chanmon_cfgs = create_chanmon_cfgs(2);
4865 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4866 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4867 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4869 // Create some initial channels
4870 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4872 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4874 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4875 assert_eq!(commitment_tx[0].input.len(), 1);
4876 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4878 // Settle A's commitment tx on B's chain
4879 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4880 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4881 check_added_monitors!(nodes[1], 1);
4882 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4883 check_added_monitors!(nodes[1], 1);
4884 let events = nodes[1].node.get_and_clear_pending_msg_events();
4886 MessageSendEvent::UpdateHTLCs { .. } => {},
4887 _ => panic!("Unexpected event"),
4890 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4891 _ => panic!("Unexepected event"),
4894 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4895 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4896 assert_eq!(node_txn.len(), 3);
4897 check_spends!(node_txn[0], commitment_tx[0]);
4898 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4899 check_spends!(node_txn[1], chan_1.3);
4900 check_spends!(node_txn[2], node_txn[1]);
4902 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4903 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4904 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4906 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4907 assert_eq!(spend_txn.len(), 1);
4908 check_spends!(spend_txn[0], node_txn[0]);
4912 fn test_static_spendable_outputs_timeout_tx() {
4913 let chanmon_cfgs = create_chanmon_cfgs(2);
4914 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4915 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4916 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4918 // Create some initial channels
4919 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4921 // Rebalance the network a bit by relaying one payment through all the channels ...
4922 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4924 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4926 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4927 assert_eq!(commitment_tx[0].input.len(), 1);
4928 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4930 // Settle A's commitment tx on B' chain
4931 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4932 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4933 check_added_monitors!(nodes[1], 1);
4934 let events = nodes[1].node.get_and_clear_pending_msg_events();
4936 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4937 _ => panic!("Unexpected event"),
4940 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4941 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4942 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4943 check_spends!(node_txn[0], commitment_tx[0].clone());
4944 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4945 check_spends!(node_txn[1], chan_1.3.clone());
4946 check_spends!(node_txn[2], node_txn[1]);
4948 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4949 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4950 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4951 expect_payment_failed!(nodes[1], our_payment_hash, true);
4953 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4954 assert_eq!(spend_txn.len(), 2); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4955 check_spends!(spend_txn[1], node_txn[0]);
4959 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4960 let chanmon_cfgs = create_chanmon_cfgs(2);
4961 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4962 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4963 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4965 // Create some initial channels
4966 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4968 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4969 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4970 assert_eq!(revoked_local_txn[0].input.len(), 1);
4971 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4973 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4975 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4976 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4977 check_closed_broadcast!(nodes[1], false);
4978 check_added_monitors!(nodes[1], 1);
4980 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4981 assert_eq!(node_txn.len(), 2);
4982 assert_eq!(node_txn[0].input.len(), 2);
4983 check_spends!(node_txn[0], revoked_local_txn[0]);
4985 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4986 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4987 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
4989 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4990 assert_eq!(spend_txn.len(), 1);
4991 check_spends!(spend_txn[0], node_txn[0]);
4995 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4996 let chanmon_cfgs = create_chanmon_cfgs(2);
4997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5001 // Create some initial channels
5002 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5004 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5005 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5006 assert_eq!(revoked_local_txn[0].input.len(), 1);
5007 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5009 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5011 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5012 // A will generate HTLC-Timeout from revoked commitment tx
5013 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5014 check_closed_broadcast!(nodes[0], false);
5015 check_added_monitors!(nodes[0], 1);
5017 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5018 assert_eq!(revoked_htlc_txn.len(), 2);
5019 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5020 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5021 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5022 check_spends!(revoked_htlc_txn[1], chan_1.3);
5024 // B will generate justice tx from A's revoked commitment/HTLC tx
5025 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
5026 check_closed_broadcast!(nodes[1], false);
5027 check_added_monitors!(nodes[1], 1);
5029 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5030 assert_eq!(node_txn.len(), 3); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs, ChannelManager: local commitment tx
5031 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5032 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5033 // transactions next...
5034 assert_eq!(node_txn[0].input.len(), 3);
5035 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5037 assert_eq!(node_txn[1].input.len(), 2);
5038 check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
5039 if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5040 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5042 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5043 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5046 assert_eq!(node_txn[2].input.len(), 1);
5047 check_spends!(node_txn[2], chan_1.3);
5049 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5050 connect_block(&nodes[1], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5051 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5053 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
5054 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5055 assert_eq!(spend_txn.len(), 1);
5056 assert_eq!(spend_txn[0].input.len(), 1);
5057 check_spends!(spend_txn[0], node_txn[1]);
5061 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
5062 let chanmon_cfgs = create_chanmon_cfgs(2);
5063 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5064 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5065 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5067 // Create some initial channels
5068 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5070 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
5071 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5072 assert_eq!(revoked_local_txn[0].input.len(), 1);
5073 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
5075 // The to-be-revoked commitment tx should have one HTLC and one to_remote output
5076 assert_eq!(revoked_local_txn[0].output.len(), 2);
5078 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
5080 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5081 // B will generate HTLC-Success from revoked commitment tx
5082 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
5083 check_closed_broadcast!(nodes[1], false);
5084 check_added_monitors!(nodes[1], 1);
5085 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5087 assert_eq!(revoked_htlc_txn.len(), 2);
5088 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
5089 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5090 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
5092 // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
5093 let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
5094 assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
5096 // A will generate justice tx from B's revoked commitment/HTLC tx
5097 connect_block(&nodes[0], &Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
5098 check_closed_broadcast!(nodes[0], false);
5099 check_added_monitors!(nodes[0], 1);
5101 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5102 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
5104 // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
5105 // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
5106 // transactions next...
5107 assert_eq!(node_txn[0].input.len(), 2);
5108 check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
5109 if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
5110 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5112 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
5113 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5116 assert_eq!(node_txn[1].input.len(), 1);
5117 check_spends!(node_txn[1], revoked_htlc_txn[0]);
5119 check_spends!(node_txn[2], chan_1.3);
5121 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5122 connect_block(&nodes[0], &Block { header: header_1, txdata: vec![node_txn[1].clone()] }, 1);
5123 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5125 // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
5126 // didn't try to generate any new transactions.
5128 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
5129 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5130 assert_eq!(spend_txn.len(), 2);
5131 assert_eq!(spend_txn[0].input.len(), 1);
5132 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
5133 assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
5134 check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
5138 fn test_onchain_to_onchain_claim() {
5139 // Test that in case of channel closure, we detect the state of output and claim HTLC
5140 // on downstream peer's remote commitment tx.
5141 // First, have C claim an HTLC against its own latest commitment transaction.
5142 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
5144 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
5147 let chanmon_cfgs = create_chanmon_cfgs(3);
5148 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5149 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5150 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5152 // Create some initial channels
5153 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5154 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5156 // Rebalance the network a bit by relaying one payment through all the channels ...
5157 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5158 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
5160 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
5161 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
5162 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
5163 check_spends!(commitment_tx[0], chan_2.3);
5164 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
5165 check_added_monitors!(nodes[2], 1);
5166 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5167 assert!(updates.update_add_htlcs.is_empty());
5168 assert!(updates.update_fail_htlcs.is_empty());
5169 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5170 assert!(updates.update_fail_malformed_htlcs.is_empty());
5172 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5173 check_closed_broadcast!(nodes[2], false);
5174 check_added_monitors!(nodes[2], 1);
5176 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
5177 assert_eq!(c_txn.len(), 3);
5178 assert_eq!(c_txn[0], c_txn[2]);
5179 assert_eq!(commitment_tx[0], c_txn[1]);
5180 check_spends!(c_txn[1], chan_2.3);
5181 check_spends!(c_txn[2], c_txn[1]);
5182 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
5183 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5184 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5185 assert_eq!(c_txn[0].lock_time, 0); // Success tx
5187 // 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
5188 connect_block(&nodes[1], &Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
5190 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5191 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
5192 assert_eq!(b_txn.len(), 3);
5193 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
5194 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
5195 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5196 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
5197 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5198 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor
5199 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5200 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5201 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
5204 check_added_monitors!(nodes[1], 1);
5205 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5206 check_added_monitors!(nodes[1], 1);
5207 match msg_events[0] {
5208 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5209 _ => panic!("Unexpected event"),
5211 match msg_events[1] {
5212 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, .. } } => {
5213 assert!(update_add_htlcs.is_empty());
5214 assert!(update_fail_htlcs.is_empty());
5215 assert_eq!(update_fulfill_htlcs.len(), 1);
5216 assert!(update_fail_malformed_htlcs.is_empty());
5217 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
5219 _ => panic!("Unexpected event"),
5221 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
5222 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
5223 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
5224 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5225 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
5226 assert_eq!(b_txn.len(), 3);
5227 check_spends!(b_txn[1], chan_1.3);
5228 check_spends!(b_txn[2], b_txn[1]);
5229 check_spends!(b_txn[0], commitment_tx[0]);
5230 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5231 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
5232 assert_eq!(b_txn[0].lock_time, 0); // Success tx
5234 check_closed_broadcast!(nodes[1], false);
5235 check_added_monitors!(nodes[1], 1);
5239 fn test_duplicate_payment_hash_one_failure_one_success() {
5240 // Topology : A --> B --> C
5241 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
5242 let chanmon_cfgs = create_chanmon_cfgs(3);
5243 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5244 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5245 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5247 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5248 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5250 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
5251 *nodes[0].network_payment_count.borrow_mut() -= 1;
5252 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
5254 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5255 assert_eq!(commitment_txn[0].input.len(), 1);
5256 check_spends!(commitment_txn[0], chan_2.3);
5258 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5259 connect_block(&nodes[1], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5260 check_closed_broadcast!(nodes[1], false);
5261 check_added_monitors!(nodes[1], 1);
5263 let htlc_timeout_tx;
5264 { // Extract one of the two HTLC-Timeout transaction
5265 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5266 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
5267 assert_eq!(node_txn.len(), 5);
5268 check_spends!(node_txn[0], commitment_txn[0]);
5269 assert_eq!(node_txn[0].input.len(), 1);
5270 check_spends!(node_txn[1], commitment_txn[0]);
5271 assert_eq!(node_txn[1].input.len(), 1);
5272 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
5273 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5274 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5275 check_spends!(node_txn[2], chan_2.3);
5276 check_spends!(node_txn[3], node_txn[2]);
5277 check_spends!(node_txn[4], node_txn[2]);
5278 htlc_timeout_tx = node_txn[1].clone();
5281 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
5282 connect_block(&nodes[2], &Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
5283 check_added_monitors!(nodes[2], 3);
5284 let events = nodes[2].node.get_and_clear_pending_msg_events();
5286 MessageSendEvent::UpdateHTLCs { .. } => {},
5287 _ => panic!("Unexpected event"),
5290 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5291 _ => panic!("Unexepected event"),
5293 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5294 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)
5295 check_spends!(htlc_success_txn[2], chan_2.3);
5296 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
5297 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
5298 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
5299 assert_eq!(htlc_success_txn[0].input.len(), 1);
5300 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5301 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
5302 assert_eq!(htlc_success_txn[1].input.len(), 1);
5303 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5304 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
5305 check_spends!(htlc_success_txn[0], commitment_txn[0]);
5306 check_spends!(htlc_success_txn[1], commitment_txn[0]);
5308 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_timeout_tx] }, 200);
5309 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 200, true, header.block_hash());
5310 expect_pending_htlcs_forwardable!(nodes[1]);
5311 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5312 assert!(htlc_updates.update_add_htlcs.is_empty());
5313 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5314 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
5315 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5316 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5317 check_added_monitors!(nodes[1], 1);
5319 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5320 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5322 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5323 let events = nodes[0].node.get_and_clear_pending_msg_events();
5324 assert_eq!(events.len(), 1);
5326 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
5328 _ => { panic!("Unexpected event"); }
5331 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
5333 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5334 connect_block(&nodes[1], &Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
5335 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5336 assert!(updates.update_add_htlcs.is_empty());
5337 assert!(updates.update_fail_htlcs.is_empty());
5338 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5339 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
5340 assert!(updates.update_fail_malformed_htlcs.is_empty());
5341 check_added_monitors!(nodes[1], 1);
5343 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5344 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5346 let events = nodes[0].node.get_and_clear_pending_events();
5348 Event::PaymentSent { ref payment_preimage } => {
5349 assert_eq!(*payment_preimage, our_payment_preimage);
5351 _ => panic!("Unexpected event"),
5356 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5357 let chanmon_cfgs = create_chanmon_cfgs(2);
5358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5360 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5362 // Create some initial channels
5363 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5365 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
5366 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5367 assert_eq!(local_txn[0].input.len(), 1);
5368 check_spends!(local_txn[0], chan_1.3);
5370 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5371 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
5372 check_added_monitors!(nodes[1], 1);
5373 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5374 connect_block(&nodes[1], &Block { header, txdata: vec![local_txn[0].clone()] }, 1);
5375 check_added_monitors!(nodes[1], 1);
5376 let events = nodes[1].node.get_and_clear_pending_msg_events();
5378 MessageSendEvent::UpdateHTLCs { .. } => {},
5379 _ => panic!("Unexpected event"),
5382 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5383 _ => panic!("Unexepected event"),
5386 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5387 assert_eq!(node_txn[0].input.len(), 1);
5388 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5389 check_spends!(node_txn[0], local_txn[0]);
5390 vec![node_txn[0].clone(), node_txn[2].clone()]
5393 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5394 connect_block(&nodes[1], &Block { header: header_201, txdata: node_txn.clone() }, 201);
5395 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5397 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5398 let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
5399 assert_eq!(spend_txn.len(), 2);
5400 check_spends!(spend_txn[0], node_txn[0]);
5401 check_spends!(spend_txn[1], node_txn[1]);
5404 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5405 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5406 // unrevoked commitment transaction.
5407 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5408 // a remote RAA before they could be failed backwards (and combinations thereof).
5409 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5410 // use the same payment hashes.
5411 // Thus, we use a six-node network:
5416 // And test where C fails back to A/B when D announces its latest commitment transaction
5417 let chanmon_cfgs = create_chanmon_cfgs(6);
5418 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5419 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5420 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5421 let logger = test_utils::TestLogger::new();
5423 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5424 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5425 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5426 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5427 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5429 // Rebalance and check output sanity...
5430 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5431 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5432 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5434 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
5436 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
5438 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
5439 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5440 let our_node_id = &nodes[1].node.get_our_node_id();
5441 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5443 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5445 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
5447 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5449 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5450 let route = get_route(our_node_id, &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5452 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5454 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5457 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5459 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();
5460 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
5463 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
5465 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();
5466 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5468 // Double-check that six of the new HTLC were added
5469 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5470 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5471 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5472 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5474 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5475 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5476 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5477 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5478 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5479 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5480 check_added_monitors!(nodes[4], 0);
5481 expect_pending_htlcs_forwardable!(nodes[4]);
5482 check_added_monitors!(nodes[4], 1);
5484 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5485 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5486 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5487 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5488 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5489 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5491 // Fail 3rd below-dust and 7th above-dust HTLCs
5492 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5493 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5494 check_added_monitors!(nodes[5], 0);
5495 expect_pending_htlcs_forwardable!(nodes[5]);
5496 check_added_monitors!(nodes[5], 1);
5498 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5499 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5500 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5501 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5503 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5505 expect_pending_htlcs_forwardable!(nodes[3]);
5506 check_added_monitors!(nodes[3], 1);
5507 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5508 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5509 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5510 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5511 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5512 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5513 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5514 if deliver_last_raa {
5515 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5517 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5520 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5521 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5522 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5523 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5525 // We now broadcast the latest commitment transaction, which *should* result in failures for
5526 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5527 // the non-broadcast above-dust HTLCs.
5529 // Alternatively, we may broadcast the previous commitment transaction, which should only
5530 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5531 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5533 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5534 if announce_latest {
5535 connect_block(&nodes[2], &Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5537 connect_block(&nodes[2], &Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5539 connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
5540 check_closed_broadcast!(nodes[2], false);
5541 expect_pending_htlcs_forwardable!(nodes[2]);
5542 check_added_monitors!(nodes[2], 3);
5544 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5545 assert_eq!(cs_msgs.len(), 2);
5546 let mut a_done = false;
5547 for msg in cs_msgs {
5549 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5550 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5551 // should be failed-backwards here.
5552 let target = if *node_id == nodes[0].node.get_our_node_id() {
5553 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5554 for htlc in &updates.update_fail_htlcs {
5555 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 });
5557 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5562 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5563 for htlc in &updates.update_fail_htlcs {
5564 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5566 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5567 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5570 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5571 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5572 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5573 if announce_latest {
5574 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5575 if *node_id == nodes[0].node.get_our_node_id() {
5576 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5579 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5581 _ => panic!("Unexpected event"),
5585 let as_events = nodes[0].node.get_and_clear_pending_events();
5586 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5587 let mut as_failds = HashSet::new();
5588 for event in as_events.iter() {
5589 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5590 assert!(as_failds.insert(*payment_hash));
5591 if *payment_hash != payment_hash_2 {
5592 assert_eq!(*rejected_by_dest, deliver_last_raa);
5594 assert!(!rejected_by_dest);
5596 } else { panic!("Unexpected event"); }
5598 assert!(as_failds.contains(&payment_hash_1));
5599 assert!(as_failds.contains(&payment_hash_2));
5600 if announce_latest {
5601 assert!(as_failds.contains(&payment_hash_3));
5602 assert!(as_failds.contains(&payment_hash_5));
5604 assert!(as_failds.contains(&payment_hash_6));
5606 let bs_events = nodes[1].node.get_and_clear_pending_events();
5607 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5608 let mut bs_failds = HashSet::new();
5609 for event in bs_events.iter() {
5610 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5611 assert!(bs_failds.insert(*payment_hash));
5612 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5613 assert_eq!(*rejected_by_dest, deliver_last_raa);
5615 assert!(!rejected_by_dest);
5617 } else { panic!("Unexpected event"); }
5619 assert!(bs_failds.contains(&payment_hash_1));
5620 assert!(bs_failds.contains(&payment_hash_2));
5621 if announce_latest {
5622 assert!(bs_failds.contains(&payment_hash_4));
5624 assert!(bs_failds.contains(&payment_hash_5));
5626 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5627 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5628 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5629 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5630 // PaymentFailureNetworkUpdates.
5631 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5632 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5633 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5634 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5635 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5637 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5638 _ => panic!("Unexpected event"),
5644 fn test_fail_backwards_latest_remote_announce_a() {
5645 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5649 fn test_fail_backwards_latest_remote_announce_b() {
5650 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5654 fn test_fail_backwards_previous_remote_announce() {
5655 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5656 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5657 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5661 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5662 let chanmon_cfgs = create_chanmon_cfgs(2);
5663 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5664 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5665 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5667 // Create some initial channels
5668 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5670 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5671 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5672 assert_eq!(local_txn[0].input.len(), 1);
5673 check_spends!(local_txn[0], chan_1.3);
5675 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5676 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5677 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5678 check_closed_broadcast!(nodes[0], false);
5679 check_added_monitors!(nodes[0], 1);
5681 let htlc_timeout = {
5682 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5683 assert_eq!(node_txn[0].input.len(), 1);
5684 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5685 check_spends!(node_txn[0], local_txn[0]);
5689 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5690 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5691 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5692 expect_payment_failed!(nodes[0], our_payment_hash, true);
5694 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5695 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5696 assert_eq!(spend_txn.len(), 2);
5697 check_spends!(spend_txn[0], local_txn[0]);
5698 check_spends!(spend_txn[1], htlc_timeout);
5702 fn test_key_derivation_params() {
5703 // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with
5704 // a key manager rotation to test that key_derivation_params returned in DynamicOutputP2WSH
5705 // let us re-derive the channel key set to then derive a delayed_payment_key.
5707 let chanmon_cfgs = create_chanmon_cfgs(3);
5709 // We manually create the node configuration to backup the seed.
5710 let seed = [42; 32];
5711 let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5712 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, &keys_manager);
5713 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: &keys_manager, node_seed: seed };
5714 let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5715 node_cfgs.remove(0);
5716 node_cfgs.insert(0, node);
5718 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5719 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5721 // Create some initial channels
5722 // Create a dummy channel to advance index by one and thus test re-derivation correctness
5724 let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5725 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5726 assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5728 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5729 let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5730 let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5731 assert_eq!(local_txn_1[0].input.len(), 1);
5732 check_spends!(local_txn_1[0], chan_1.3);
5734 // We check funding pubkey are unique
5735 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]));
5736 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]));
5737 if from_0_funding_key_0 == from_1_funding_key_0
5738 || from_0_funding_key_0 == from_1_funding_key_1
5739 || from_0_funding_key_1 == from_1_funding_key_0
5740 || from_0_funding_key_1 == from_1_funding_key_1 {
5741 panic!("Funding pubkeys aren't unique");
5744 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5745 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5746 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn_1[0].clone()] }, 200);
5747 check_closed_broadcast!(nodes[0], false);
5748 check_added_monitors!(nodes[0], 1);
5750 let htlc_timeout = {
5751 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5752 assert_eq!(node_txn[0].input.len(), 1);
5753 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5754 check_spends!(node_txn[0], local_txn_1[0]);
5758 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5759 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5760 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
5761 expect_payment_failed!(nodes[0], our_payment_hash, true);
5763 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5764 let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5765 let spend_txn = check_spendable_outputs!(nodes[0], 1, new_keys_manager, 100000);
5766 assert_eq!(spend_txn.len(), 2);
5767 check_spends!(spend_txn[0], local_txn_1[0]);
5768 check_spends!(spend_txn[1], htlc_timeout);
5772 fn test_static_output_closing_tx() {
5773 let chanmon_cfgs = create_chanmon_cfgs(2);
5774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5776 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5778 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5780 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5781 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5783 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5784 connect_block(&nodes[0], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5785 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5787 let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5788 assert_eq!(spend_txn.len(), 1);
5789 check_spends!(spend_txn[0], closing_tx);
5791 connect_block(&nodes[1], &Block { header, txdata: vec![closing_tx.clone()] }, 0);
5792 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
5794 let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5795 assert_eq!(spend_txn.len(), 1);
5796 check_spends!(spend_txn[0], closing_tx);
5799 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5800 let chanmon_cfgs = create_chanmon_cfgs(2);
5801 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5802 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5803 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5804 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5806 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5808 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5809 // present in B's local commitment transaction, but none of A's commitment transactions.
5810 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5811 check_added_monitors!(nodes[1], 1);
5813 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5814 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5815 let events = nodes[0].node.get_and_clear_pending_events();
5816 assert_eq!(events.len(), 1);
5818 Event::PaymentSent { payment_preimage } => {
5819 assert_eq!(payment_preimage, our_payment_preimage);
5821 _ => panic!("Unexpected event"),
5824 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5825 check_added_monitors!(nodes[0], 1);
5826 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5827 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5828 check_added_monitors!(nodes[1], 1);
5830 let mut block = Block {
5831 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5834 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5835 connect_block(&nodes[1], &block, i);
5836 block.header.prev_blockhash = block.block_hash();
5838 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5839 check_closed_broadcast!(nodes[1], false);
5840 check_added_monitors!(nodes[1], 1);
5843 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5844 let chanmon_cfgs = create_chanmon_cfgs(2);
5845 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5846 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5847 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5848 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5849 let logger = test_utils::TestLogger::new();
5851 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5852 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5853 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();
5854 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5855 check_added_monitors!(nodes[0], 1);
5857 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5859 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5860 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5861 // to "time out" the HTLC.
5863 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5865 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5866 connect_block(&nodes[0], &Block { header, txdata: Vec::new()}, i);
5867 header.prev_blockhash = header.block_hash();
5869 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5870 check_closed_broadcast!(nodes[0], false);
5871 check_added_monitors!(nodes[0], 1);
5874 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5875 let chanmon_cfgs = create_chanmon_cfgs(3);
5876 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5877 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5878 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5879 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5881 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5882 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5883 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5884 // actually revoked.
5885 let htlc_value = if use_dust { 50000 } else { 3000000 };
5886 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5887 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5888 expect_pending_htlcs_forwardable!(nodes[1]);
5889 check_added_monitors!(nodes[1], 1);
5891 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5892 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5893 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5894 check_added_monitors!(nodes[0], 1);
5895 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5896 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5897 check_added_monitors!(nodes[1], 1);
5898 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5899 check_added_monitors!(nodes[1], 1);
5900 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5902 if check_revoke_no_close {
5903 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5904 check_added_monitors!(nodes[0], 1);
5907 let mut block = Block {
5908 header: BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 },
5911 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5912 connect_block(&nodes[0], &block, i);
5913 block.header.prev_blockhash = block.block_hash();
5915 if !check_revoke_no_close {
5916 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5917 check_closed_broadcast!(nodes[0], false);
5918 check_added_monitors!(nodes[0], 1);
5920 expect_payment_failed!(nodes[0], our_payment_hash, true);
5924 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5925 // There are only a few cases to test here:
5926 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5927 // broadcastable commitment transactions result in channel closure,
5928 // * its included in an unrevoked-but-previous remote commitment transaction,
5929 // * its included in the latest remote or local commitment transactions.
5930 // We test each of the three possible commitment transactions individually and use both dust and
5932 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5933 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5934 // tested for at least one of the cases in other tests.
5936 fn htlc_claim_single_commitment_only_a() {
5937 do_htlc_claim_local_commitment_only(true);
5938 do_htlc_claim_local_commitment_only(false);
5940 do_htlc_claim_current_remote_commitment_only(true);
5941 do_htlc_claim_current_remote_commitment_only(false);
5945 fn htlc_claim_single_commitment_only_b() {
5946 do_htlc_claim_previous_remote_commitment_only(true, false);
5947 do_htlc_claim_previous_remote_commitment_only(false, false);
5948 do_htlc_claim_previous_remote_commitment_only(true, true);
5949 do_htlc_claim_previous_remote_commitment_only(false, true);
5954 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5955 let chanmon_cfgs = create_chanmon_cfgs(2);
5956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5958 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5959 //Force duplicate channel ids
5960 for node in nodes.iter() {
5961 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5964 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5965 let channel_value_satoshis=10000;
5966 let push_msat=10001;
5967 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5968 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5969 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5971 //Create a second channel with a channel_id collision
5972 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5976 fn bolt2_open_channel_sending_node_checks_part2() {
5977 let chanmon_cfgs = create_chanmon_cfgs(2);
5978 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5979 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5980 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5982 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5983 let channel_value_satoshis=2^24;
5984 let push_msat=10001;
5985 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5987 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5988 let channel_value_satoshis=10000;
5989 // Test when push_msat is equal to 1000 * funding_satoshis.
5990 let push_msat=1000*channel_value_satoshis+1;
5991 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5993 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5994 let channel_value_satoshis=10000;
5995 let push_msat=10001;
5996 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
5997 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5998 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
6000 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
6001 // 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
6002 assert!(node0_to_1_send_open_channel.channel_flags<=1);
6004 // 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.
6005 assert!(BREAKDOWN_TIMEOUT>0);
6006 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
6008 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
6009 let chain_hash=genesis_block(Network::Testnet).header.block_hash();
6010 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
6012 // 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.
6013 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
6014 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
6015 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
6016 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
6017 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
6020 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
6021 // originated from our node, its failure is surfaced to the user. We trigger this failure to
6022 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
6023 // is no longer affordable once it's freed.
6025 fn test_fail_holding_cell_htlc_upon_free() {
6026 let chanmon_cfgs = create_chanmon_cfgs(2);
6027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6029 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6030 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6031 let logger = test_utils::TestLogger::new();
6033 // First nodes[0] generates an update_fee, setting the channel's
6034 // pending_update_fee.
6035 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 20).unwrap();
6036 check_added_monitors!(nodes[0], 1);
6038 let events = nodes[0].node.get_and_clear_pending_msg_events();
6039 assert_eq!(events.len(), 1);
6040 let (update_msg, commitment_signed) = match events[0] {
6041 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6042 (update_fee.as_ref(), commitment_signed)
6044 _ => panic!("Unexpected event"),
6047 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6049 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6050 let channel_reserve = chan_stat.channel_reserve_msat;
6051 let feerate = get_feerate!(nodes[0], chan.2);
6053 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6054 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6055 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1);
6056 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6057 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();
6059 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6060 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6061 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6062 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6064 // Flush the pending fee update.
6065 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6066 let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6067 check_added_monitors!(nodes[1], 1);
6068 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
6069 check_added_monitors!(nodes[0], 1);
6071 // Upon receipt of the RAA, there will be an attempt to resend the holding cell
6072 // HTLC, but now that the fee has been raised the payment will now fail, causing
6073 // us to surface its failure to the user.
6074 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6075 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6076 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 1 HTLC updates".to_string(), 1);
6077 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);
6078 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6080 // Check that the payment failed to be sent out.
6081 let events = nodes[0].node.get_and_clear_pending_events();
6082 assert_eq!(events.len(), 1);
6084 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6085 assert_eq!(our_payment_hash.clone(), *payment_hash);
6086 assert_eq!(*rejected_by_dest, false);
6087 assert_eq!(*error_code, None);
6088 assert_eq!(*error_data, None);
6090 _ => panic!("Unexpected event"),
6094 // Test that if multiple HTLCs are released from the holding cell and one is
6095 // valid but the other is no longer valid upon release, the valid HTLC can be
6096 // successfully completed while the other one fails as expected.
6098 fn test_free_and_fail_holding_cell_htlcs() {
6099 let chanmon_cfgs = create_chanmon_cfgs(2);
6100 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6101 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6102 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6103 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6104 let logger = test_utils::TestLogger::new();
6106 // First nodes[0] generates an update_fee, setting the channel's
6107 // pending_update_fee.
6108 nodes[0].node.update_fee(chan.2, get_feerate!(nodes[0], chan.2) + 200).unwrap();
6109 check_added_monitors!(nodes[0], 1);
6111 let events = nodes[0].node.get_and_clear_pending_msg_events();
6112 assert_eq!(events.len(), 1);
6113 let (update_msg, commitment_signed) = match events[0] {
6114 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6115 (update_fee.as_ref(), commitment_signed)
6117 _ => panic!("Unexpected event"),
6120 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
6122 let mut chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6123 let channel_reserve = chan_stat.channel_reserve_msat;
6124 let feerate = get_feerate!(nodes[0], chan.2);
6126 // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
6127 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
6129 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
6130 let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1) - amt_1;
6131 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6132 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();
6133 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();
6135 // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6136 nodes[0].node.send_payment(&route_1, payment_hash_1, &None).unwrap();
6137 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6138 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6139 nodes[0].node.send_payment(&route_2, payment_hash_2, &None).unwrap();
6140 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6141 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6143 // Flush the pending fee update.
6144 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6145 let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6146 check_added_monitors!(nodes[1], 1);
6147 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6148 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6149 check_added_monitors!(nodes[0], 2);
6151 // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6152 // but now that the fee has been raised the second payment will now fail, causing us
6153 // to surface its failure to the user. The first payment should succeed.
6154 chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6155 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6156 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), "Freeing holding cell with 2 HTLC updates".to_string(), 1);
6157 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);
6158 nodes[0].logger.assert_log("lightning::ln::channel".to_string(), failure_log.to_string(), 1);
6160 // Check that the second payment failed to be sent out.
6161 let events = nodes[0].node.get_and_clear_pending_events();
6162 assert_eq!(events.len(), 1);
6164 &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, ref error_code, ref error_data } => {
6165 assert_eq!(payment_hash_2.clone(), *payment_hash);
6166 assert_eq!(*rejected_by_dest, false);
6167 assert_eq!(*error_code, None);
6168 assert_eq!(*error_data, None);
6170 _ => panic!("Unexpected event"),
6173 // Complete the first payment and the RAA from the fee update.
6174 let (payment_event, send_raa_event) = {
6175 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6176 assert_eq!(msgs.len(), 2);
6177 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6179 let raa = match send_raa_event {
6180 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6181 _ => panic!("Unexpected event"),
6183 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6184 check_added_monitors!(nodes[1], 1);
6185 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6186 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6187 let events = nodes[1].node.get_and_clear_pending_events();
6188 assert_eq!(events.len(), 1);
6190 Event::PendingHTLCsForwardable { .. } => {},
6191 _ => panic!("Unexpected event"),
6193 nodes[1].node.process_pending_htlc_forwards();
6194 let events = nodes[1].node.get_and_clear_pending_events();
6195 assert_eq!(events.len(), 1);
6197 Event::PaymentReceived { .. } => {},
6198 _ => panic!("Unexpected event"),
6200 nodes[1].node.claim_funds(payment_preimage_1, &None, amt_1);
6201 check_added_monitors!(nodes[1], 1);
6202 let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6203 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6204 commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6205 let events = nodes[0].node.get_and_clear_pending_events();
6206 assert_eq!(events.len(), 1);
6208 Event::PaymentSent { ref payment_preimage } => {
6209 assert_eq!(*payment_preimage, payment_preimage_1);
6211 _ => panic!("Unexpected event"),
6215 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6216 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6217 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6220 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6221 let chanmon_cfgs = create_chanmon_cfgs(3);
6222 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6223 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6224 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6225 let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6226 let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6227 let logger = test_utils::TestLogger::new();
6229 // First nodes[1] generates an update_fee, setting the channel's
6230 // pending_update_fee.
6231 nodes[1].node.update_fee(chan_1_2.2, get_feerate!(nodes[1], chan_1_2.2) + 20).unwrap();
6232 check_added_monitors!(nodes[1], 1);
6234 let events = nodes[1].node.get_and_clear_pending_msg_events();
6235 assert_eq!(events.len(), 1);
6236 let (update_msg, commitment_signed) = match events[0] {
6237 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6238 (update_fee.as_ref(), commitment_signed)
6240 _ => panic!("Unexpected event"),
6243 nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6245 let mut chan_stat = get_channel_value_stat!(nodes[0], chan_0_1.2);
6246 let channel_reserve = chan_stat.channel_reserve_msat;
6247 let feerate = get_feerate!(nodes[0], chan_0_1.2);
6249 // Send a payment which passes reserve checks but gets stuck in the holding cell.
6251 let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
6252 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6253 let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1) - total_routing_fee_msat;
6254 let payment_event = {
6255 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6256 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();
6257 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6258 check_added_monitors!(nodes[0], 1);
6260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6261 assert_eq!(events.len(), 1);
6263 SendEvent::from_event(events.remove(0))
6265 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6266 check_added_monitors!(nodes[1], 0);
6267 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6268 expect_pending_htlcs_forwardable!(nodes[1]);
6270 chan_stat = get_channel_value_stat!(nodes[1], chan_1_2.2);
6271 assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6273 // Flush the pending fee update.
6274 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6275 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6276 check_added_monitors!(nodes[2], 1);
6277 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6278 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6279 check_added_monitors!(nodes[1], 2);
6281 // A final RAA message is generated to finalize the fee update.
6282 let events = nodes[1].node.get_and_clear_pending_msg_events();
6283 assert_eq!(events.len(), 1);
6285 let raa_msg = match &events[0] {
6286 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6289 _ => panic!("Unexpected event"),
6292 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6293 check_added_monitors!(nodes[2], 1);
6294 assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6296 // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6297 let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6298 assert_eq!(process_htlc_forwards_event.len(), 1);
6299 match &process_htlc_forwards_event[0] {
6300 &Event::PendingHTLCsForwardable { .. } => {},
6301 _ => panic!("Unexpected event"),
6304 // In response, we call ChannelManager's process_pending_htlc_forwards
6305 nodes[1].node.process_pending_htlc_forwards();
6306 check_added_monitors!(nodes[1], 1);
6308 // This causes the HTLC to be failed backwards.
6309 let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6310 assert_eq!(fail_event.len(), 1);
6311 let (fail_msg, commitment_signed) = match &fail_event[0] {
6312 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6313 assert_eq!(updates.update_add_htlcs.len(), 0);
6314 assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6315 assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6316 assert_eq!(updates.update_fail_htlcs.len(), 1);
6317 (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6319 _ => panic!("Unexpected event"),
6322 // Pass the failure messages back to nodes[0].
6323 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6324 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6326 // Complete the HTLC failure+removal process.
6327 let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6328 check_added_monitors!(nodes[0], 1);
6329 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6330 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6331 check_added_monitors!(nodes[1], 2);
6332 let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6333 assert_eq!(final_raa_event.len(), 1);
6334 let raa = match &final_raa_event[0] {
6335 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6336 _ => panic!("Unexpected event"),
6338 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6339 let fail_msg_event = nodes[0].node.get_and_clear_pending_msg_events();
6340 assert_eq!(fail_msg_event.len(), 1);
6341 match &fail_msg_event[0] {
6342 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
6343 _ => panic!("Unexpected event"),
6345 let failure_event = nodes[0].node.get_and_clear_pending_events();
6346 assert_eq!(failure_event.len(), 1);
6347 match &failure_event[0] {
6348 &Event::PaymentFailed { rejected_by_dest, .. } => {
6349 assert!(!rejected_by_dest);
6351 _ => panic!("Unexpected event"),
6353 check_added_monitors!(nodes[0], 1);
6356 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6357 // 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.
6358 //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.
6361 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6362 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6363 let chanmon_cfgs = create_chanmon_cfgs(2);
6364 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6365 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6366 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6367 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6369 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6370 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6371 let logger = test_utils::TestLogger::new();
6372 let mut route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6373 route.paths[0][0].fee_msat = 100;
6375 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6376 assert!(regex::Regex::new(r"Cannot send less than their minimum HTLC value \(\d+\)").unwrap().is_match(err)));
6377 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6378 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
6382 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6383 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6384 let chanmon_cfgs = create_chanmon_cfgs(2);
6385 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6386 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6387 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6388 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6389 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6391 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6392 let logger = test_utils::TestLogger::new();
6393 let 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();
6394 route.paths[0][0].fee_msat = 0;
6395 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6396 assert_eq!(err, "Cannot send 0-msat HTLC"));
6398 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6399 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6403 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6404 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
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 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 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6416 check_added_monitors!(nodes[0], 1);
6417 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6418 updates.update_add_htlcs[0].amount_msat = 0;
6420 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6421 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6422 check_closed_broadcast!(nodes[1], true).unwrap();
6423 check_added_monitors!(nodes[1], 1);
6427 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6428 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6429 //It is enforced when constructing a route.
6430 let chanmon_cfgs = create_chanmon_cfgs(2);
6431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6433 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6434 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6435 let logger = test_utils::TestLogger::new();
6437 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6439 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6440 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();
6441 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { ref err },
6442 assert_eq!(err, &"Channel CLTV overflowed?"));
6446 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6447 //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.
6448 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6449 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6450 let chanmon_cfgs = create_chanmon_cfgs(2);
6451 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6452 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6453 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6454 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6455 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().counterparty_max_accepted_htlcs as u64;
6457 let logger = test_utils::TestLogger::new();
6458 for i in 0..max_accepted_htlcs {
6459 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6460 let payment_event = {
6461 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6462 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();
6463 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6464 check_added_monitors!(nodes[0], 1);
6466 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6467 assert_eq!(events.len(), 1);
6468 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6469 assert_eq!(htlcs[0].htlc_id, i);
6473 SendEvent::from_event(events.remove(0))
6475 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6476 check_added_monitors!(nodes[1], 0);
6477 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6479 expect_pending_htlcs_forwardable!(nodes[1]);
6480 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6482 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6483 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6484 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();
6485 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6486 assert!(regex::Regex::new(r"Cannot push more than their max accepted HTLCs \(\d+\)").unwrap().is_match(err)));
6488 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6489 nodes[0].logger.assert_log_contains("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6493 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6494 //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.
6495 let chanmon_cfgs = create_chanmon_cfgs(2);
6496 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6497 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6498 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6499 let channel_value = 100000;
6500 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6501 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat;
6503 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6505 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6506 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6507 let logger = test_utils::TestLogger::new();
6508 let route = get_route(&nodes[0].node.get_our_node_id(), &net_graph_msg_handler.network_graph.read().unwrap(), &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6509 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { ref err },
6510 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)));
6512 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6513 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);
6515 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6518 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6520 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6521 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6522 let chanmon_cfgs = create_chanmon_cfgs(2);
6523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6525 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6526 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6527 let htlc_minimum_msat: u64;
6529 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6530 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6531 htlc_minimum_msat = channel.get_holder_htlc_minimum_msat();
6534 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6535 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6536 let logger = test_utils::TestLogger::new();
6537 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();
6538 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6539 check_added_monitors!(nodes[0], 1);
6540 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6541 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6542 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6543 assert!(nodes[1].node.list_channels().is_empty());
6544 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6545 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()));
6546 check_added_monitors!(nodes[1], 1);
6550 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6551 //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
6552 let chanmon_cfgs = create_chanmon_cfgs(2);
6553 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6554 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6555 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6556 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6557 let logger = test_utils::TestLogger::new();
6559 let chan_stat = get_channel_value_stat!(nodes[0], chan.2);
6560 let channel_reserve = chan_stat.channel_reserve_msat;
6561 let feerate = get_feerate!(nodes[0], chan.2);
6562 // The 2* and +1 are for the fee spike reserve.
6563 let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1);
6565 let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6566 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6567 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6568 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();
6569 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6570 check_added_monitors!(nodes[0], 1);
6571 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6573 // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6574 // at this time channel-initiatee receivers are not required to enforce that senders
6575 // respect the fee_spike_reserve.
6576 updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6577 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6579 assert!(nodes[1].node.list_channels().is_empty());
6580 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6581 assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6582 check_added_monitors!(nodes[1], 1);
6586 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6587 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6588 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6589 let chanmon_cfgs = create_chanmon_cfgs(2);
6590 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6591 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6592 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6593 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6594 let logger = test_utils::TestLogger::new();
6596 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6597 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6599 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6600 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();
6602 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6603 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6604 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6605 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6607 let mut msg = msgs::UpdateAddHTLC {
6611 payment_hash: our_payment_hash,
6612 cltv_expiry: htlc_cltv,
6613 onion_routing_packet: onion_packet.clone(),
6616 for i in 0..super::channel::OUR_MAX_HTLCS {
6617 msg.htlc_id = i as u64;
6618 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6620 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6621 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6623 assert!(nodes[1].node.list_channels().is_empty());
6624 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6625 assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6626 check_added_monitors!(nodes[1], 1);
6630 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6631 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6632 let chanmon_cfgs = create_chanmon_cfgs(2);
6633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6635 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6636 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6637 let logger = test_utils::TestLogger::new();
6639 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6640 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6641 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();
6642 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6643 check_added_monitors!(nodes[0], 1);
6644 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6645 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6646 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6648 assert!(nodes[1].node.list_channels().is_empty());
6649 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6650 assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6651 check_added_monitors!(nodes[1], 1);
6655 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6656 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6657 let chanmon_cfgs = create_chanmon_cfgs(2);
6658 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6659 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6660 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6661 let logger = test_utils::TestLogger::new();
6663 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6664 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6665 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6666 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();
6667 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6668 check_added_monitors!(nodes[0], 1);
6669 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6670 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6671 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6673 assert!(nodes[1].node.list_channels().is_empty());
6674 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6675 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6676 check_added_monitors!(nodes[1], 1);
6680 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6681 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6682 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6683 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6684 let chanmon_cfgs = create_chanmon_cfgs(2);
6685 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6686 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6687 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6688 let logger = test_utils::TestLogger::new();
6690 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6691 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6692 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6693 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();
6694 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6695 check_added_monitors!(nodes[0], 1);
6696 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6697 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6699 //Disconnect and Reconnect
6700 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6701 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6702 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6703 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6704 assert_eq!(reestablish_1.len(), 1);
6705 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6706 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6707 assert_eq!(reestablish_2.len(), 1);
6708 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6709 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6710 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6711 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6714 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6715 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6716 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6717 check_added_monitors!(nodes[1], 1);
6718 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6720 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6722 assert!(nodes[1].node.list_channels().is_empty());
6723 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6724 assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6725 check_added_monitors!(nodes[1], 1);
6729 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6730 //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.
6732 let chanmon_cfgs = create_chanmon_cfgs(2);
6733 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6734 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6735 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6736 let logger = test_utils::TestLogger::new();
6737 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6738 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6739 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6740 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();
6741 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6743 check_added_monitors!(nodes[0], 1);
6744 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6745 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6747 let update_msg = msgs::UpdateFulfillHTLC{
6750 payment_preimage: our_payment_preimage,
6753 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6755 assert!(nodes[0].node.list_channels().is_empty());
6756 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6757 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()));
6758 check_added_monitors!(nodes[0], 1);
6762 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6763 //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.
6765 let chanmon_cfgs = create_chanmon_cfgs(2);
6766 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6767 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6768 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6769 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6770 let logger = test_utils::TestLogger::new();
6772 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6773 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6774 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();
6775 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6776 check_added_monitors!(nodes[0], 1);
6777 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6778 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6780 let update_msg = msgs::UpdateFailHTLC{
6783 reason: msgs::OnionErrorPacket { data: Vec::new()},
6786 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6788 assert!(nodes[0].node.list_channels().is_empty());
6789 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6790 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()));
6791 check_added_monitors!(nodes[0], 1);
6795 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6796 //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.
6798 let chanmon_cfgs = create_chanmon_cfgs(2);
6799 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6800 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6801 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6802 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6803 let logger = test_utils::TestLogger::new();
6805 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6806 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6807 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();
6808 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6809 check_added_monitors!(nodes[0], 1);
6810 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6811 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6813 let update_msg = msgs::UpdateFailMalformedHTLC{
6816 sha256_of_onion: [1; 32],
6817 failure_code: 0x8000,
6820 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6822 assert!(nodes[0].node.list_channels().is_empty());
6823 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6824 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()));
6825 check_added_monitors!(nodes[0], 1);
6829 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6830 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6832 let chanmon_cfgs = create_chanmon_cfgs(2);
6833 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6834 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6835 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6836 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6838 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6840 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6841 check_added_monitors!(nodes[1], 1);
6843 let events = nodes[1].node.get_and_clear_pending_msg_events();
6844 assert_eq!(events.len(), 1);
6845 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6847 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, .. } } => {
6848 assert!(update_add_htlcs.is_empty());
6849 assert_eq!(update_fulfill_htlcs.len(), 1);
6850 assert!(update_fail_htlcs.is_empty());
6851 assert!(update_fail_malformed_htlcs.is_empty());
6852 assert!(update_fee.is_none());
6853 update_fulfill_htlcs[0].clone()
6855 _ => panic!("Unexpected event"),
6859 update_fulfill_msg.htlc_id = 1;
6861 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6863 assert!(nodes[0].node.list_channels().is_empty());
6864 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6865 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6866 check_added_monitors!(nodes[0], 1);
6870 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6871 //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.
6873 let chanmon_cfgs = create_chanmon_cfgs(2);
6874 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6875 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6876 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6877 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6879 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6881 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6882 check_added_monitors!(nodes[1], 1);
6884 let events = nodes[1].node.get_and_clear_pending_msg_events();
6885 assert_eq!(events.len(), 1);
6886 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6888 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, .. } } => {
6889 assert!(update_add_htlcs.is_empty());
6890 assert_eq!(update_fulfill_htlcs.len(), 1);
6891 assert!(update_fail_htlcs.is_empty());
6892 assert!(update_fail_malformed_htlcs.is_empty());
6893 assert!(update_fee.is_none());
6894 update_fulfill_htlcs[0].clone()
6896 _ => panic!("Unexpected event"),
6900 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6902 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6904 assert!(nodes[0].node.list_channels().is_empty());
6905 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6906 assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6907 check_added_monitors!(nodes[0], 1);
6911 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6912 //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.
6914 let chanmon_cfgs = create_chanmon_cfgs(2);
6915 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6916 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6917 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6918 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6919 let logger = test_utils::TestLogger::new();
6921 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6922 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6923 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();
6924 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6925 check_added_monitors!(nodes[0], 1);
6927 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6928 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6930 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6931 check_added_monitors!(nodes[1], 0);
6932 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6934 let events = nodes[1].node.get_and_clear_pending_msg_events();
6936 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6938 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, .. } } => {
6939 assert!(update_add_htlcs.is_empty());
6940 assert!(update_fulfill_htlcs.is_empty());
6941 assert!(update_fail_htlcs.is_empty());
6942 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6943 assert!(update_fee.is_none());
6944 update_fail_malformed_htlcs[0].clone()
6946 _ => panic!("Unexpected event"),
6949 update_msg.failure_code &= !0x8000;
6950 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6952 assert!(nodes[0].node.list_channels().is_empty());
6953 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6954 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6955 check_added_monitors!(nodes[0], 1);
6959 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6960 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6961 // * 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.
6963 let chanmon_cfgs = create_chanmon_cfgs(3);
6964 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6965 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6966 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6967 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6968 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6969 let logger = test_utils::TestLogger::new();
6971 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6974 let mut payment_event = {
6975 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6976 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();
6977 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6978 check_added_monitors!(nodes[0], 1);
6979 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6980 assert_eq!(events.len(), 1);
6981 SendEvent::from_event(events.remove(0))
6983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6984 check_added_monitors!(nodes[1], 0);
6985 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6986 expect_pending_htlcs_forwardable!(nodes[1]);
6987 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6988 assert_eq!(events_2.len(), 1);
6989 check_added_monitors!(nodes[1], 1);
6990 payment_event = SendEvent::from_event(events_2.remove(0));
6991 assert_eq!(payment_event.msgs.len(), 1);
6994 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6995 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6996 check_added_monitors!(nodes[2], 0);
6997 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6999 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
7000 assert_eq!(events_3.len(), 1);
7001 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
7003 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 } } => {
7004 assert!(update_add_htlcs.is_empty());
7005 assert!(update_fulfill_htlcs.is_empty());
7006 assert!(update_fail_htlcs.is_empty());
7007 assert_eq!(update_fail_malformed_htlcs.len(), 1);
7008 assert!(update_fee.is_none());
7009 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
7011 _ => panic!("Unexpected event"),
7015 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
7017 check_added_monitors!(nodes[1], 0);
7018 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
7019 expect_pending_htlcs_forwardable!(nodes[1]);
7020 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
7021 assert_eq!(events_4.len(), 1);
7023 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
7025 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, .. } } => {
7026 assert!(update_add_htlcs.is_empty());
7027 assert!(update_fulfill_htlcs.is_empty());
7028 assert_eq!(update_fail_htlcs.len(), 1);
7029 assert!(update_fail_malformed_htlcs.is_empty());
7030 assert!(update_fee.is_none());
7032 _ => panic!("Unexpected event"),
7035 check_added_monitors!(nodes[1], 1);
7038 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7039 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7040 // 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
7041 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7043 let chanmon_cfgs = create_chanmon_cfgs(2);
7044 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7045 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7046 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7047 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7049 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7051 // We route 2 dust-HTLCs between A and B
7052 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7053 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7054 route_payment(&nodes[0], &[&nodes[1]], 1000000);
7056 // Cache one local commitment tx as previous
7057 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7059 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7060 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
7061 check_added_monitors!(nodes[1], 0);
7062 expect_pending_htlcs_forwardable!(nodes[1]);
7063 check_added_monitors!(nodes[1], 1);
7065 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7066 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7067 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7068 check_added_monitors!(nodes[0], 1);
7070 // Cache one local commitment tx as lastest
7071 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7073 let events = nodes[0].node.get_and_clear_pending_msg_events();
7075 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7076 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7078 _ => panic!("Unexpected event"),
7081 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7082 assert_eq!(node_id, nodes[1].node.get_our_node_id());
7084 _ => panic!("Unexpected event"),
7087 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7088 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7089 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7091 if announce_latest {
7092 connect_block(&nodes[0], &Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
7094 connect_block(&nodes[0], &Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
7097 check_closed_broadcast!(nodes[0], false);
7098 check_added_monitors!(nodes[0], 1);
7100 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7101 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 1, true, header.block_hash());
7102 let events = nodes[0].node.get_and_clear_pending_events();
7103 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
7104 assert_eq!(events.len(), 2);
7105 let mut first_failed = false;
7106 for event in events {
7108 Event::PaymentFailed { payment_hash, .. } => {
7109 if payment_hash == payment_hash_1 {
7110 assert!(!first_failed);
7111 first_failed = true;
7113 assert_eq!(payment_hash, payment_hash_2);
7116 _ => panic!("Unexpected event"),
7122 fn test_failure_delay_dust_htlc_local_commitment() {
7123 do_test_failure_delay_dust_htlc_local_commitment(true);
7124 do_test_failure_delay_dust_htlc_local_commitment(false);
7127 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7128 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7129 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7130 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7131 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7132 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7133 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7135 let chanmon_cfgs = create_chanmon_cfgs(3);
7136 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7137 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7138 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7139 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7141 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().holder_dust_limit_satoshis;
7143 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7144 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7146 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7147 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7149 // We revoked bs_commitment_tx
7151 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7152 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
7155 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7156 let mut timeout_tx = Vec::new();
7158 // We fail dust-HTLC 1 by broadcast of local commitment tx
7159 connect_block(&nodes[0], &Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
7160 check_closed_broadcast!(nodes[0], false);
7161 check_added_monitors!(nodes[0], 1);
7162 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7163 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7164 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7165 expect_payment_failed!(nodes[0], dust_hash, true);
7166 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7167 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7168 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7169 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7170 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7171 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7172 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7173 expect_payment_failed!(nodes[0], non_dust_hash, true);
7175 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7176 connect_block(&nodes[0], &Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
7177 check_closed_broadcast!(nodes[0], false);
7178 check_added_monitors!(nodes[0], 1);
7179 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7180 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7181 let parent_hash = connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 2, true, header.block_hash());
7182 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7184 expect_payment_failed!(nodes[0], dust_hash, true);
7185 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7186 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
7187 connect_block(&nodes[0], &Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
7188 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7189 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7190 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 8, true, header_3.block_hash());
7191 expect_payment_failed!(nodes[0], non_dust_hash, true);
7193 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
7195 let events = nodes[0].node.get_and_clear_pending_events();
7196 assert_eq!(events.len(), 2);
7199 Event::PaymentFailed { payment_hash, .. } => {
7200 if payment_hash == dust_hash { first = true; }
7201 else { first = false; }
7203 _ => panic!("Unexpected event"),
7206 Event::PaymentFailed { payment_hash, .. } => {
7207 if first { assert_eq!(payment_hash, non_dust_hash); }
7208 else { assert_eq!(payment_hash, dust_hash); }
7210 _ => panic!("Unexpected event"),
7217 fn test_sweep_outbound_htlc_failure_update() {
7218 do_test_sweep_outbound_htlc_failure_update(false, true);
7219 do_test_sweep_outbound_htlc_failure_update(false, false);
7220 do_test_sweep_outbound_htlc_failure_update(true, false);
7224 fn test_upfront_shutdown_script() {
7225 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
7226 // enforce it at shutdown message
7228 let mut config = UserConfig::default();
7229 config.channel_options.announced_channel = true;
7230 config.peer_channel_config_limits.force_announced_channel_preference = false;
7231 config.channel_options.commit_upfront_shutdown_pubkey = false;
7232 let user_cfgs = [None, Some(config), None];
7233 let chanmon_cfgs = create_chanmon_cfgs(3);
7234 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7235 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
7236 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7238 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
7239 let flags = InitFeatures::known();
7240 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7241 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7242 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7243 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7244 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
7245 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7246 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()));
7247 check_added_monitors!(nodes[2], 1);
7249 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
7250 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
7251 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7252 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
7253 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
7254 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
7255 let events = nodes[2].node.get_and_clear_pending_msg_events();
7256 assert_eq!(events.len(), 1);
7258 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7259 _ => panic!("Unexpected event"),
7262 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
7263 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
7264 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
7265 nodes[0].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7266 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
7267 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7268 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
7269 let events = nodes[1].node.get_and_clear_pending_msg_events();
7270 assert_eq!(events.len(), 1);
7272 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
7273 _ => panic!("Unexpected event"),
7276 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7277 // channel smoothly, opt-out is from channel initiator here
7278 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
7279 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7280 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7281 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7282 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7283 let events = nodes[0].node.get_and_clear_pending_msg_events();
7284 assert_eq!(events.len(), 1);
7286 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7287 _ => panic!("Unexpected event"),
7290 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
7291 //// channel smoothly
7292 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
7293 nodes[1].node.close_channel(&OutPoint { txid: chan.3.txid(), index: 0 }.to_channel_id()).unwrap();
7294 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
7295 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
7296 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
7297 let events = nodes[0].node.get_and_clear_pending_msg_events();
7298 assert_eq!(events.len(), 2);
7300 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7301 _ => panic!("Unexpected event"),
7304 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
7305 _ => panic!("Unexpected event"),
7310 fn test_user_configurable_csv_delay() {
7311 // We test our channel constructors yield errors when we pass them absurd csv delay
7313 let mut low_our_to_self_config = UserConfig::default();
7314 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
7315 let mut high_their_to_self_config = UserConfig::default();
7316 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
7317 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7318 let chanmon_cfgs = create_chanmon_cfgs(2);
7319 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7320 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7321 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7323 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
7324 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, &low_our_to_self_config) {
7326 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())); },
7327 _ => panic!("Unexpected event"),
7329 } else { assert!(false) }
7331 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7332 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7333 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7334 open_channel.to_self_delay = 200;
7335 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7337 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())); },
7338 _ => panic!("Unexpected event"),
7340 } else { assert!(false); }
7342 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7343 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7344 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()));
7345 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7346 accept_channel.to_self_delay = 200;
7347 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7348 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7350 &ErrorAction::SendErrorMessage { ref msg } => {
7351 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()));
7353 _ => { assert!(false); }
7355 } else { assert!(false); }
7357 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7358 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7359 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7360 open_channel.to_self_delay = 200;
7361 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7363 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())); },
7364 _ => panic!("Unexpected event"),
7366 } else { assert!(false); }
7370 fn test_data_loss_protect() {
7371 // We want to be sure that :
7372 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7373 // (but this is not quite true - we broadcast during Drop because chanmon is out of sync with chanmgr)
7374 // * we close channel in case of detecting other being fallen behind
7375 // * we are able to claim our own outputs thanks to to_remote being static
7376 // TODO: this test is incomplete and the data_loss_protect implementation is incomplete - see issue #775
7382 let chanmon_cfgs = create_chanmon_cfgs(2);
7383 let keys_manager = &chanmon_cfgs[0].keys_manager;
7386 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7387 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7388 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7390 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7392 // Cache node A state before any channel update
7393 let previous_node_state = nodes[0].node.encode();
7394 let mut previous_chain_monitor_state = test_utils::TestVecWriter(Vec::new());
7395 nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write(&mut previous_chain_monitor_state).unwrap();
7397 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7398 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7400 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7401 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7403 // Restore node A from previous state
7404 logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7405 let mut chain_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chain_monitor_state.0), keys_manager).unwrap().1;
7406 chain_source = test_utils::TestChainSource::new(Network::Testnet);
7407 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7408 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7409 persister = test_utils::TestPersister::new();
7410 monitor = test_utils::TestChainMonitor::new(Some(&chain_source), &tx_broadcaster, &logger, &fee_estimator, &persister, keys_manager);
7412 let mut channel_monitors = HashMap::new();
7413 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chain_monitor);
7414 <(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 {
7415 keys_manager: keys_manager,
7416 fee_estimator: &fee_estimator,
7417 chain_monitor: &monitor,
7419 tx_broadcaster: &tx_broadcaster,
7420 default_config: UserConfig::default(),
7424 nodes[0].node = &node_state_0;
7425 assert!(monitor.watch_channel(OutPoint { txid: chan.3.txid(), index: 0 }, chain_monitor).is_ok());
7426 nodes[0].chain_monitor = &monitor;
7427 nodes[0].chain_source = &chain_source;
7429 check_added_monitors!(nodes[0], 1);
7431 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7432 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7434 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7436 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7437 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7438 check_added_monitors!(nodes[0], 1);
7441 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7442 assert_eq!(node_txn.len(), 0);
7445 let mut reestablish_1 = Vec::with_capacity(1);
7446 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7447 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7448 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7449 reestablish_1.push(msg.clone());
7450 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7451 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7453 &ErrorAction::SendErrorMessage { ref msg } => {
7454 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");
7456 _ => panic!("Unexpected event!"),
7459 panic!("Unexpected event")
7463 // Check we close channel detecting A is fallen-behind
7464 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7465 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7466 check_added_monitors!(nodes[1], 1);
7469 // Check A is able to claim to_remote output
7470 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7471 assert_eq!(node_txn.len(), 1);
7472 check_spends!(node_txn[0], chan.3);
7473 assert_eq!(node_txn[0].output.len(), 2);
7474 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7475 connect_block(&nodes[0], &Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7476 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 0, true, header.block_hash());
7477 let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7478 assert_eq!(spend_txn.len(), 1);
7479 check_spends!(spend_txn[0], node_txn[0]);
7483 fn test_check_htlc_underpaying() {
7484 // Send payment through A -> B but A is maliciously
7485 // sending a probe payment (i.e less than expected value0
7486 // to B, B should refuse payment.
7488 let chanmon_cfgs = create_chanmon_cfgs(2);
7489 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7490 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7491 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7493 // Create some initial channels
7494 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7496 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7498 // Node 3 is expecting payment of 100_000 but receive 10_000,
7499 // fail htlc like we didn't know the preimage.
7500 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7501 nodes[1].node.process_pending_htlc_forwards();
7503 let events = nodes[1].node.get_and_clear_pending_msg_events();
7504 assert_eq!(events.len(), 1);
7505 let (update_fail_htlc, commitment_signed) = match events[0] {
7506 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 } } => {
7507 assert!(update_add_htlcs.is_empty());
7508 assert!(update_fulfill_htlcs.is_empty());
7509 assert_eq!(update_fail_htlcs.len(), 1);
7510 assert!(update_fail_malformed_htlcs.is_empty());
7511 assert!(update_fee.is_none());
7512 (update_fail_htlcs[0].clone(), commitment_signed)
7514 _ => panic!("Unexpected event"),
7516 check_added_monitors!(nodes[1], 1);
7518 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7519 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7521 // 10_000 msat as u64, followed by a height of 99 as u32
7522 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7523 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7524 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7525 nodes[1].node.get_and_clear_pending_events();
7529 fn test_announce_disable_channels() {
7530 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7531 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7533 let chanmon_cfgs = create_chanmon_cfgs(2);
7534 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7535 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7536 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7538 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7539 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7540 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7543 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7544 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7546 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7547 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7548 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7549 assert_eq!(msg_events.len(), 3);
7550 for e in msg_events {
7552 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7553 let short_id = msg.contents.short_channel_id;
7554 // Check generated channel_update match list in PendingChannelUpdate
7555 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7556 panic!("Generated ChannelUpdate for wrong chan!");
7559 _ => panic!("Unexpected event"),
7563 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7564 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7565 assert_eq!(reestablish_1.len(), 3);
7566 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7567 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7568 assert_eq!(reestablish_2.len(), 3);
7570 // Reestablish chan_1
7571 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7572 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7573 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7574 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7575 // Reestablish chan_2
7576 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7577 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7578 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7579 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7580 // Reestablish chan_3
7581 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7582 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7583 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7584 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7586 nodes[0].node.timer_chan_freshness_every_min();
7587 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7591 fn test_bump_penalty_txn_on_revoked_commitment() {
7592 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7593 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7595 let chanmon_cfgs = create_chanmon_cfgs(2);
7596 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7597 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7598 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7600 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7601 let logger = test_utils::TestLogger::new();
7604 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7605 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7606 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();
7607 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7609 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7610 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7611 assert_eq!(revoked_txn[0].output.len(), 4);
7612 assert_eq!(revoked_txn[0].input.len(), 1);
7613 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7614 let revoked_txid = revoked_txn[0].txid();
7616 let mut penalty_sum = 0;
7617 for outp in revoked_txn[0].output.iter() {
7618 if outp.script_pubkey.is_v0_p2wsh() {
7619 penalty_sum += outp.value;
7623 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7624 let header_114 = connect_blocks(&nodes[1], 114, 0, false, Default::default());
7626 // Actually revoke tx by claiming a HTLC
7627 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7628 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7629 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7630 check_added_monitors!(nodes[1], 1);
7632 // One or more justice tx should have been broadcast, check it
7636 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7637 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7638 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7639 assert_eq!(node_txn[0].output.len(), 1);
7640 check_spends!(node_txn[0], revoked_txn[0]);
7641 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7642 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7643 penalty_1 = node_txn[0].txid();
7647 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7648 let header = connect_blocks(&nodes[1], 3, 115, true, header.block_hash());
7649 let mut penalty_2 = penalty_1;
7650 let mut feerate_2 = 0;
7652 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7653 assert_eq!(node_txn.len(), 1);
7654 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7655 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7656 assert_eq!(node_txn[0].output.len(), 1);
7657 check_spends!(node_txn[0], revoked_txn[0]);
7658 penalty_2 = node_txn[0].txid();
7659 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7660 assert_ne!(penalty_2, penalty_1);
7661 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7662 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7663 // Verify 25% bump heuristic
7664 assert!(feerate_2 * 100 >= feerate_1 * 125);
7668 assert_ne!(feerate_2, 0);
7670 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7671 connect_blocks(&nodes[1], 3, 118, true, header);
7673 let mut feerate_3 = 0;
7675 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7676 assert_eq!(node_txn.len(), 1);
7677 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7678 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7679 assert_eq!(node_txn[0].output.len(), 1);
7680 check_spends!(node_txn[0], revoked_txn[0]);
7681 penalty_3 = node_txn[0].txid();
7682 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7683 assert_ne!(penalty_3, penalty_2);
7684 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7685 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7686 // Verify 25% bump heuristic
7687 assert!(feerate_3 * 100 >= feerate_2 * 125);
7691 assert_ne!(feerate_3, 0);
7693 nodes[1].node.get_and_clear_pending_events();
7694 nodes[1].node.get_and_clear_pending_msg_events();
7698 fn test_bump_penalty_txn_on_revoked_htlcs() {
7699 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7700 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7702 let chanmon_cfgs = create_chanmon_cfgs(2);
7703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7705 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7707 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7708 // Lock HTLC in both directions
7709 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7710 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7712 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7713 assert_eq!(revoked_local_txn[0].input.len(), 1);
7714 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7716 // Revoke local commitment tx
7717 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7719 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7720 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7721 connect_block(&nodes[1], &Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7722 check_closed_broadcast!(nodes[1], false);
7723 check_added_monitors!(nodes[1], 1);
7725 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7726 assert_eq!(revoked_htlc_txn.len(), 4);
7727 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7728 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7729 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7730 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7731 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7732 assert_eq!(revoked_htlc_txn[1].output.len(), 1);
7733 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7734 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7735 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7736 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7737 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7738 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7739 assert_eq!(revoked_htlc_txn[0].output.len(), 1);
7740 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7743 // Broadcast set of revoked txn on A
7744 let header_128 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7745 connect_block(&nodes[0], &Block { header: header_128, txdata: vec![revoked_local_txn[0].clone()] }, 128);
7746 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7747 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7748 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7753 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7754 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7755 // Verify claim tx are spending revoked HTLC txn
7757 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7758 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7759 // which are included in the same block (they are broadcasted because we scan the
7760 // transactions linearly and generate claims as we go, they likely should be removed in the
7762 assert_eq!(node_txn[0].input.len(), 1);
7763 check_spends!(node_txn[0], revoked_local_txn[0]);
7764 assert_eq!(node_txn[1].input.len(), 1);
7765 check_spends!(node_txn[1], revoked_local_txn[0]);
7766 assert_eq!(node_txn[2].input.len(), 1);
7767 check_spends!(node_txn[2], revoked_local_txn[0]);
7769 // Each of the three justice transactions claim a separate (single) output of the three
7770 // available, which we check here:
7771 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7772 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7773 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7775 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7776 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7778 // node_txn[3] is the local commitment tx broadcast just because (and somewhat in case of
7779 // reorgs, though its not clear its ever worth broadcasting conflicting txn like this when
7780 // a remote commitment tx has already been confirmed).
7781 check_spends!(node_txn[3], chan.3);
7783 // node_txn[4] spends the revoked outputs from the revoked_htlc_txn (which only have one
7784 // output, checked above).
7785 assert_eq!(node_txn[4].input.len(), 2);
7786 assert_eq!(node_txn[4].output.len(), 1);
7787 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7789 first = node_txn[4].txid();
7790 // Store both feerates for later comparison
7791 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7792 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7793 penalty_txn = vec![node_txn[2].clone()];
7797 // Connect one more block to see if bumped penalty are issued for HTLC txn
7798 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7799 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
7800 let header_131 = BlockHeader { version: 0x20000000, prev_blockhash: header_130.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7801 connect_block(&nodes[0], &Block { header: header_131, txdata: Vec::new() }, 131);
7803 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7804 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7806 check_spends!(node_txn[0], revoked_local_txn[0]);
7807 check_spends!(node_txn[1], revoked_local_txn[0]);
7808 // Note that these are both bogus - they spend outputs already claimed in block 129:
7809 if node_txn[0].input[0].previous_output == revoked_htlc_txn[0].input[0].previous_output {
7810 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7812 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7813 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7819 // Few more blocks to confirm penalty txn
7820 let header_135 = connect_blocks(&nodes[0], 4, 131, true, header_131.block_hash());
7821 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7822 let header_144 = connect_blocks(&nodes[0], 9, 135, true, header_135);
7824 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7825 assert_eq!(node_txn.len(), 1);
7827 assert_eq!(node_txn[0].input.len(), 2);
7828 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7829 // Verify bumped tx is different and 25% bump heuristic
7830 assert_ne!(first, node_txn[0].txid());
7831 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7832 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7833 assert!(feerate_2 * 100 > feerate_1 * 125);
7834 let txn = vec![node_txn[0].clone()];
7838 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7839 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7840 connect_block(&nodes[0], &Block { header: header_145, txdata: node_txn }, 145);
7841 connect_blocks(&nodes[0], 20, 145, true, header_145.block_hash());
7843 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7844 // We verify than no new transaction has been broadcast because previously
7845 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7846 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7847 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7848 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7849 // up bumped justice generation.
7850 assert_eq!(node_txn.len(), 0);
7853 check_closed_broadcast!(nodes[0], false);
7854 check_added_monitors!(nodes[0], 1);
7858 fn test_bump_penalty_txn_on_remote_commitment() {
7859 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7860 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7863 // Provide preimage for one
7864 // Check aggregation
7866 let chanmon_cfgs = create_chanmon_cfgs(2);
7867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7869 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7871 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7872 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7873 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7875 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7876 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7877 assert_eq!(remote_txn[0].output.len(), 4);
7878 assert_eq!(remote_txn[0].input.len(), 1);
7879 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7881 // Claim a HTLC without revocation (provide B monitor with preimage)
7882 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7883 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7884 connect_block(&nodes[1], &Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7885 check_added_monitors!(nodes[1], 2);
7887 // One or more claim tx should have been broadcast, check it
7890 let feerate_timeout;
7891 let feerate_preimage;
7893 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7894 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7895 assert_eq!(node_txn[0].input.len(), 1);
7896 assert_eq!(node_txn[1].input.len(), 1);
7897 check_spends!(node_txn[0], remote_txn[0]);
7898 check_spends!(node_txn[1], remote_txn[0]);
7899 check_spends!(node_txn[2], chan.3);
7900 check_spends!(node_txn[3], node_txn[2]);
7901 check_spends!(node_txn[4], node_txn[2]);
7902 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7903 timeout = node_txn[0].txid();
7904 let index = node_txn[0].input[0].previous_output.vout;
7905 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7906 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7908 preimage = node_txn[1].txid();
7909 let index = node_txn[1].input[0].previous_output.vout;
7910 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7911 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7913 timeout = node_txn[1].txid();
7914 let index = node_txn[1].input[0].previous_output.vout;
7915 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7916 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7918 preimage = node_txn[0].txid();
7919 let index = node_txn[0].input[0].previous_output.vout;
7920 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7921 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7925 assert_ne!(feerate_timeout, 0);
7926 assert_ne!(feerate_preimage, 0);
7928 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7929 connect_blocks(&nodes[1], 15, 1, true, header.block_hash());
7931 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7932 assert_eq!(node_txn.len(), 2);
7933 assert_eq!(node_txn[0].input.len(), 1);
7934 assert_eq!(node_txn[1].input.len(), 1);
7935 check_spends!(node_txn[0], remote_txn[0]);
7936 check_spends!(node_txn[1], remote_txn[0]);
7937 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7938 let index = node_txn[0].input[0].previous_output.vout;
7939 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7940 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7941 assert!(new_feerate * 100 > feerate_timeout * 125);
7942 assert_ne!(timeout, node_txn[0].txid());
7944 let index = node_txn[1].input[0].previous_output.vout;
7945 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7946 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7947 assert!(new_feerate * 100 > feerate_preimage * 125);
7948 assert_ne!(preimage, node_txn[1].txid());
7950 let index = node_txn[1].input[0].previous_output.vout;
7951 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7952 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7953 assert!(new_feerate * 100 > feerate_timeout * 125);
7954 assert_ne!(timeout, node_txn[1].txid());
7956 let index = node_txn[0].input[0].previous_output.vout;
7957 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7958 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7959 assert!(new_feerate * 100 > feerate_preimage * 125);
7960 assert_ne!(preimage, node_txn[0].txid());
7965 nodes[1].node.get_and_clear_pending_events();
7966 nodes[1].node.get_and_clear_pending_msg_events();
7970 fn test_set_outpoints_partial_claiming() {
7971 // - remote party claim tx, new bump tx
7972 // - disconnect remote claiming tx, new bump
7973 // - disconnect tx, see no tx anymore
7974 let chanmon_cfgs = create_chanmon_cfgs(2);
7975 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7976 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7977 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7979 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7980 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7981 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7983 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7984 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7985 assert_eq!(remote_txn.len(), 3);
7986 assert_eq!(remote_txn[0].output.len(), 4);
7987 assert_eq!(remote_txn[0].input.len(), 1);
7988 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7989 check_spends!(remote_txn[1], remote_txn[0]);
7990 check_spends!(remote_txn[2], remote_txn[0]);
7992 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7993 let prev_header_100 = connect_blocks(&nodes[1], 100, 0, false, Default::default());
7994 // Provide node A with both preimage
7995 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7996 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7997 check_added_monitors!(nodes[0], 2);
7998 nodes[0].node.get_and_clear_pending_events();
7999 nodes[0].node.get_and_clear_pending_msg_events();
8001 // Connect blocks on node A commitment transaction
8002 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8003 connect_block(&nodes[0], &Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
8004 check_closed_broadcast!(nodes[0], false);
8005 check_added_monitors!(nodes[0], 1);
8006 // Verify node A broadcast tx claiming both HTLCs
8008 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8009 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
8010 assert_eq!(node_txn.len(), 4);
8011 check_spends!(node_txn[0], remote_txn[0]);
8012 check_spends!(node_txn[1], chan.3);
8013 check_spends!(node_txn[2], node_txn[1]);
8014 check_spends!(node_txn[3], node_txn[1]);
8015 assert_eq!(node_txn[0].input.len(), 2);
8019 // Connect blocks on node B
8020 connect_blocks(&nodes[1], 135, 0, false, Default::default());
8021 check_closed_broadcast!(nodes[1], false);
8022 check_added_monitors!(nodes[1], 1);
8023 // Verify node B broadcast 2 HTLC-timeout txn
8024 let partial_claim_tx = {
8025 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8026 assert_eq!(node_txn.len(), 3);
8027 check_spends!(node_txn[1], node_txn[0]);
8028 check_spends!(node_txn[2], node_txn[0]);
8029 assert_eq!(node_txn[1].input.len(), 1);
8030 assert_eq!(node_txn[2].input.len(), 1);
8034 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
8035 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8036 connect_block(&nodes[0], &Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
8038 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8039 assert_eq!(node_txn.len(), 1);
8040 check_spends!(node_txn[0], remote_txn[0]);
8041 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
8044 nodes[0].node.get_and_clear_pending_msg_events();
8046 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
8047 disconnect_block(&nodes[0], &header, 102);
8049 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8050 assert_eq!(node_txn.len(), 1);
8051 check_spends!(node_txn[0], remote_txn[0]);
8052 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
8056 //// Disconnect one more block and then reconnect multiple no transaction should be generated
8057 disconnect_block(&nodes[0], &header, 101);
8058 connect_blocks(&nodes[1], 15, 101, false, prev_header_100);
8060 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8061 assert_eq!(node_txn.len(), 0);
8067 fn test_counterparty_raa_skip_no_crash() {
8068 // Previously, if our counterparty sent two RAAs in a row without us having provided a
8069 // commitment transaction, we would have happily carried on and provided them the next
8070 // commitment transaction based on one RAA forward. This would probably eventually have led to
8071 // channel closure, but it would not have resulted in funds loss. Still, our
8072 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
8073 // check simply that the channel is closed in response to such an RAA, but don't check whether
8074 // we decide to punish our counterparty for revoking their funds (as we don't currently
8076 let chanmon_cfgs = create_chanmon_cfgs(2);
8077 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8078 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8079 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8080 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
8082 let mut guard = nodes[0].node.channel_state.lock().unwrap();
8083 let keys = &guard.by_id.get_mut(&channel_id).unwrap().holder_keys;
8084 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
8085 let per_commitment_secret = keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
8086 // Must revoke without gaps
8087 keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
8088 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
8089 &SecretKey::from_slice(&keys.release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
8091 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
8092 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
8093 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
8094 check_added_monitors!(nodes[1], 1);
8098 fn test_bump_txn_sanitize_tracking_maps() {
8099 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
8100 // verify we clean then right after expiration of ANTI_REORG_DELAY.
8102 let chanmon_cfgs = create_chanmon_cfgs(2);
8103 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8104 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8105 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8107 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
8108 // Lock HTLC in both directions
8109 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8110 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
8112 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
8113 assert_eq!(revoked_local_txn[0].input.len(), 1);
8114 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
8116 // Revoke local commitment tx
8117 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
8119 // Broadcast set of revoked txn on A
8120 let header_128 = connect_blocks(&nodes[0], 128, 0, false, Default::default());
8121 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
8123 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8124 connect_block(&nodes[0], &Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
8125 check_closed_broadcast!(nodes[0], false);
8126 check_added_monitors!(nodes[0], 1);
8128 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8129 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
8130 check_spends!(node_txn[0], revoked_local_txn[0]);
8131 check_spends!(node_txn[1], revoked_local_txn[0]);
8132 check_spends!(node_txn[2], revoked_local_txn[0]);
8133 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
8137 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8138 connect_block(&nodes[0], &Block { header: header_130, txdata: penalty_txn }, 130);
8139 connect_blocks(&nodes[0], 5, 130, false, header_130.block_hash());
8141 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8142 if let Some(monitor) = monitors.get(&OutPoint { txid: chan.3.txid(), index: 0 }) {
8143 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
8144 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
8150 fn test_override_channel_config() {
8151 let chanmon_cfgs = create_chanmon_cfgs(2);
8152 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8153 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8154 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8156 // Node0 initiates a channel to node1 using the override config.
8157 let mut override_config = UserConfig::default();
8158 override_config.own_channel_config.our_to_self_delay = 200;
8160 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
8162 // Assert the channel created by node0 is using the override config.
8163 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8164 assert_eq!(res.channel_flags, 0);
8165 assert_eq!(res.to_self_delay, 200);
8169 fn test_override_0msat_htlc_minimum() {
8170 let mut zero_config = UserConfig::default();
8171 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
8172 let chanmon_cfgs = create_chanmon_cfgs(2);
8173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
8175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8177 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
8178 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8179 assert_eq!(res.htlc_minimum_msat, 1);
8181 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
8182 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8183 assert_eq!(res.htlc_minimum_msat, 1);
8187 fn test_simple_payment_secret() {
8188 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
8189 // features, however.
8190 let chanmon_cfgs = create_chanmon_cfgs(3);
8191 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8192 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8193 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8195 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8196 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
8197 let logger = test_utils::TestLogger::new();
8199 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8200 let payment_secret = PaymentSecret([0xdb; 32]);
8201 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8202 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();
8203 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
8204 // Claiming with all the correct values but the wrong secret should result in nothing...
8205 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
8206 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
8207 // ...but with the right secret we should be able to claim all the way back
8208 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
8212 fn test_simple_mpp() {
8213 // Simple test of sending a multi-path payment.
8214 let chanmon_cfgs = create_chanmon_cfgs(4);
8215 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8216 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8217 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8219 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8220 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8221 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8222 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
8223 let logger = test_utils::TestLogger::new();
8225 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
8226 let payment_secret = PaymentSecret([0xdb; 32]);
8227 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
8228 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();
8229 let path = route.paths[0].clone();
8230 route.paths.push(path);
8231 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
8232 route.paths[0][0].short_channel_id = chan_1_id;
8233 route.paths[0][1].short_channel_id = chan_3_id;
8234 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
8235 route.paths[1][0].short_channel_id = chan_2_id;
8236 route.paths[1][1].short_channel_id = chan_4_id;
8237 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
8238 // Claiming with all the correct values but the wrong secret should result in nothing...
8239 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
8240 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
8241 // ...but with the right secret we should be able to claim all the way back
8242 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
8246 fn test_update_err_monitor_lockdown() {
8247 // Our monitor will lock update of local commitment transaction if a broadcastion condition
8248 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8249 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
8251 // This scenario may happen in a watchtower setup, where watchtower process a block height
8252 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8253 // commitment at same time.
8255 let chanmon_cfgs = create_chanmon_cfgs(2);
8256 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8257 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8258 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8260 // Create some initial channel
8261 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8262 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8264 // Rebalance the network to generate htlc in the two directions
8265 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8267 // Route a HTLC from node 0 to node 1 (but don't settle)
8268 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8270 // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8271 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8272 let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8273 let persister = test_utils::TestPersister::new();
8275 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8276 let monitor = monitors.get(&outpoint).unwrap();
8277 let mut w = test_utils::TestVecWriter(Vec::new());
8278 monitor.write(&mut w).unwrap();
8279 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8280 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8281 assert!(new_monitor == *monitor);
8282 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8283 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8286 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8287 watchtower.chain_monitor.block_connected(&header, &[], 200);
8289 // Try to update ChannelMonitor
8290 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
8291 check_added_monitors!(nodes[1], 1);
8292 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8293 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8294 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8295 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8296 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8297 if let Err(_) = watchtower.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8298 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8299 } else { assert!(false); }
8300 } else { assert!(false); };
8301 // Our local monitor is in-sync and hasn't processed yet timeout
8302 check_added_monitors!(nodes[0], 1);
8303 let events = nodes[0].node.get_and_clear_pending_events();
8304 assert_eq!(events.len(), 1);
8308 fn test_concurrent_monitor_claim() {
8309 // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8310 // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8311 // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8312 // state N+1 confirms. Alice claims output from state N+1.
8314 let chanmon_cfgs = create_chanmon_cfgs(2);
8315 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8316 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8317 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8319 // Create some initial channel
8320 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
8321 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8323 // Rebalance the network to generate htlc in the two directions
8324 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
8326 // Route a HTLC from node 0 to node 1 (but don't settle)
8327 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8329 // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8330 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8331 let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8332 let persister = test_utils::TestPersister::new();
8333 let watchtower_alice = {
8334 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8335 let monitor = monitors.get(&outpoint).unwrap();
8336 let mut w = test_utils::TestVecWriter(Vec::new());
8337 monitor.write(&mut w).unwrap();
8338 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8339 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8340 assert!(new_monitor == *monitor);
8341 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8342 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8345 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8346 watchtower_alice.chain_monitor.block_connected(&header, &vec![], 135);
8348 // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8350 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8351 assert_eq!(txn.len(), 2);
8355 // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8356 let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8357 let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8358 let persister = test_utils::TestPersister::new();
8359 let watchtower_bob = {
8360 let monitors = nodes[0].chain_monitor.chain_monitor.monitors.lock().unwrap();
8361 let monitor = monitors.get(&outpoint).unwrap();
8362 let mut w = test_utils::TestVecWriter(Vec::new());
8363 monitor.write(&mut w).unwrap();
8364 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
8365 &mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
8366 assert!(new_monitor == *monitor);
8367 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8368 assert!(watchtower.watch_channel(outpoint, new_monitor).is_ok());
8371 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8372 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 134);
8374 // Route another payment to generate another update with still previous HTLC pending
8375 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
8377 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
8378 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();
8379 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
8381 check_added_monitors!(nodes[1], 1);
8383 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8384 assert_eq!(updates.update_add_htlcs.len(), 1);
8385 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8386 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
8387 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
8388 // Watchtower Alice should already have seen the block and reject the update
8389 if let Err(_) = watchtower_alice.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8390 if let Ok(_) = watchtower_bob.chain_monitor.update_channel(outpoint, update.clone()) {} else { assert!(false); }
8391 if let Ok(_) = nodes[0].chain_monitor.update_channel(outpoint, update) {} else { assert!(false); }
8392 } else { assert!(false); }
8393 } else { assert!(false); };
8394 // Our local monitor is in-sync and hasn't processed yet timeout
8395 check_added_monitors!(nodes[0], 1);
8397 //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8398 watchtower_bob.chain_monitor.block_connected(&header, &vec![], 135);
8400 // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8403 let mut txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8404 assert_eq!(txn.len(), 2);
8405 bob_state_y = txn[0].clone();
8409 // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8410 watchtower_alice.chain_monitor.block_connected(&header, &vec![(0, &bob_state_y)], 136);
8412 let htlc_txn = chanmon_cfgs[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8413 // We broadcast twice the transaction, once due to the HTLC-timeout, once due
8414 // the onchain detection of the HTLC output
8415 assert_eq!(htlc_txn.len(), 2);
8416 check_spends!(htlc_txn[0], bob_state_y);
8417 check_spends!(htlc_txn[1], bob_state_y);
8422 fn test_pre_lockin_no_chan_closed_update() {
8423 // Test that if a peer closes a channel in response to a funding_created message we don't
8424 // generate a channel update (as the channel cannot appear on chain without a funding_signed
8427 // Doing so would imply a channel monitor update before the initial channel monitor
8428 // registration, violating our API guarantees.
8430 // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8431 // then opening a second channel with the same funding output as the first (which is not
8432 // rejected because the first channel does not exist in the ChannelManager) and closing it
8433 // before receiving funding_signed.
8434 let chanmon_cfgs = create_chanmon_cfgs(2);
8435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8437 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8439 // Create an initial channel
8440 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8441 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8442 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8443 let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8444 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_chan_msg);
8446 // Move the first channel through the funding flow...
8447 let (temporary_channel_id, _tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8449 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8450 check_added_monitors!(nodes[0], 0);
8452 let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8453 let channel_id = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8454 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8455 assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8459 fn test_htlc_no_detection() {
8460 // This test is a mutation to underscore the detection logic bug we had
8461 // before #653. HTLC value routed is above the remaining balance, thus
8462 // inverting HTLC and `to_remote` output. HTLC will come second and
8463 // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8464 // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8465 // outputs order detection for correct spending children filtring.
8467 let chanmon_cfgs = create_chanmon_cfgs(2);
8468 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8469 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8470 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8472 // Create some initial channels
8473 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8475 send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000, 1_000_000);
8476 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8477 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8478 assert_eq!(local_txn[0].input.len(), 1);
8479 assert_eq!(local_txn[0].output.len(), 3);
8480 check_spends!(local_txn[0], chan_1.3);
8482 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8483 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8484 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8485 // We deliberately connect the local tx twice as this should provoke a failure calling
8486 // this test before #653 fix.
8487 connect_block(&nodes[0], &Block { header, txdata: vec![local_txn[0].clone()] }, 200);
8488 check_closed_broadcast!(nodes[0], false);
8489 check_added_monitors!(nodes[0], 1);
8491 let htlc_timeout = {
8492 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8493 assert_eq!(node_txn[0].input.len(), 1);
8494 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8495 check_spends!(node_txn[0], local_txn[0]);
8499 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.block_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
8500 connect_block(&nodes[0], &Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
8501 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1, 201, true, header_201.block_hash());
8502 expect_payment_failed!(nodes[0], our_payment_hash, true);
8505 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8506 // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8507 // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8508 // Carol, Alice would be the upstream node, and Carol the downstream.)
8510 // Steps of the test:
8511 // 1) Alice sends a HTLC to Carol through Bob.
8512 // 2) Carol doesn't settle the HTLC.
8513 // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8514 // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8515 // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8516 // but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8517 // 5) Carol release the preimage to Bob off-chain.
8518 // 6) Bob claims the offered output on the broadcasted commitment.
8519 let chanmon_cfgs = create_chanmon_cfgs(3);
8520 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8521 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8522 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8524 // Create some initial channels
8525 let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8526 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001, InitFeatures::known(), InitFeatures::known());
8528 // Steps (1) and (2):
8529 // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8530 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3_000_000);
8532 // Check that Alice's commitment transaction now contains an output for this HTLC.
8533 let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8534 check_spends!(alice_txn[0], chan_ab.3);
8535 assert_eq!(alice_txn[0].output.len(), 2);
8536 check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8537 assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8538 assert_eq!(alice_txn.len(), 2);
8540 // Steps (3) and (4):
8541 // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8542 // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8543 let mut force_closing_node = 0; // Alice force-closes
8544 if !broadcast_alice { force_closing_node = 1; } // Bob force-closes
8545 nodes[force_closing_node].node.force_close_channel(&chan_ab.2);
8546 check_closed_broadcast!(nodes[force_closing_node], false);
8547 check_added_monitors!(nodes[force_closing_node], 1);
8548 if go_onchain_before_fulfill {
8549 let txn_to_broadcast = match broadcast_alice {
8550 true => alice_txn.clone(),
8551 false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8553 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8554 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8555 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8556 if broadcast_alice {
8557 check_closed_broadcast!(nodes[1], false);
8558 check_added_monitors!(nodes[1], 1);
8560 assert_eq!(bob_txn.len(), 1);
8561 check_spends!(bob_txn[0], chan_ab.3);
8565 // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8566 // process of removing the HTLC from their commitment transactions.
8567 assert!(nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000));
8568 check_added_monitors!(nodes[2], 1);
8569 let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8570 assert!(carol_updates.update_add_htlcs.is_empty());
8571 assert!(carol_updates.update_fail_htlcs.is_empty());
8572 assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8573 assert!(carol_updates.update_fee.is_none());
8574 assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8576 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8577 // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8578 if !go_onchain_before_fulfill && broadcast_alice {
8579 let events = nodes[1].node.get_and_clear_pending_msg_events();
8580 assert_eq!(events.len(), 1);
8582 MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8583 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8585 _ => panic!("Unexpected event"),
8588 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8589 // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8590 // Carol<->Bob's updated commitment transaction info.
8591 check_added_monitors!(nodes[1], 2);
8593 let events = nodes[1].node.get_and_clear_pending_msg_events();
8594 assert_eq!(events.len(), 2);
8595 let bob_revocation = match events[0] {
8596 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8597 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8600 _ => panic!("Unexpected event"),
8602 let bob_updates = match events[1] {
8603 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8604 assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8607 _ => panic!("Unexpected event"),
8610 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8611 check_added_monitors!(nodes[2], 1);
8612 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8613 check_added_monitors!(nodes[2], 1);
8615 let events = nodes[2].node.get_and_clear_pending_msg_events();
8616 assert_eq!(events.len(), 1);
8617 let carol_revocation = match events[0] {
8618 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8619 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8622 _ => panic!("Unexpected event"),
8624 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8625 check_added_monitors!(nodes[1], 1);
8627 // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8628 // here's where we put said channel's commitment tx on-chain.
8629 let mut txn_to_broadcast = alice_txn.clone();
8630 if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8631 if !go_onchain_before_fulfill {
8632 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
8633 connect_block(&nodes[1], &Block { header, txdata: vec![txn_to_broadcast[0].clone()]}, 1);
8634 // If Bob was the one to force-close, he will have already passed these checks earlier.
8635 if broadcast_alice {
8636 check_closed_broadcast!(nodes[1], false);
8637 check_added_monitors!(nodes[1], 1);
8639 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8640 if broadcast_alice {
8641 // In `connect_block()`, the ChainMonitor and ChannelManager are separately notified about a
8642 // new block being connected. The ChannelManager being notified triggers a monitor update,
8643 // which triggers broadcasting our commitment tx and an HTLC-claiming tx. The ChainMonitor
8644 // being notified triggers the HTLC-claiming tx redundantly, resulting in 3 total txs being
8646 assert_eq!(bob_txn.len(), 3);
8647 check_spends!(bob_txn[1], chan_ab.3);
8649 assert_eq!(bob_txn.len(), 2);
8650 check_spends!(bob_txn[0], chan_ab.3);
8655 // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8656 // broadcasted commitment transaction.
8658 let bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8659 if go_onchain_before_fulfill {
8660 // Bob should now have an extra broadcasted tx, for the preimage-claiming transaction.
8661 assert_eq!(bob_txn.len(), 2);
8663 let script_weight = match broadcast_alice {
8664 true => OFFERED_HTLC_SCRIPT_WEIGHT,
8665 false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8667 // If Alice force-closed and Bob didn't receive her commitment transaction until after he
8668 // received Carol's fulfill, he broadcasts the HTLC-output-claiming transaction first. Else if
8669 // Bob force closed or if he found out about Alice's commitment tx before receiving Carol's
8670 // fulfill, then he broadcasts the HTLC-output-claiming transaction second.
8671 if broadcast_alice && !go_onchain_before_fulfill {
8672 check_spends!(bob_txn[0], txn_to_broadcast[0]);
8673 assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8675 check_spends!(bob_txn[1], txn_to_broadcast[0]);
8676 assert_eq!(bob_txn[1].input[0].witness.last().unwrap().len(), script_weight);
8682 fn test_onchain_htlc_settlement_after_close() {
8683 do_test_onchain_htlc_settlement_after_close(true, true);
8684 do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8685 do_test_onchain_htlc_settlement_after_close(true, false);
8686 do_test_onchain_htlc_settlement_after_close(false, false);
8690 fn test_duplicate_chan_id() {
8691 // Test that if a given peer tries to open a channel with the same channel_id as one that is
8692 // already open we reject it and keep the old channel.
8694 // Previously, full_stack_target managed to figure out that if you tried to open two channels
8695 // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
8696 // the existing channel when we detect the duplicate new channel, screwing up our monitor
8697 // updating logic for the existing channel.
8698 let chanmon_cfgs = create_chanmon_cfgs(2);
8699 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8700 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8701 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8703 // Create an initial channel
8704 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8705 let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8706 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8707 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()));
8709 // Try to create a second channel with the same temporary_channel_id as the first and check
8710 // that it is rejected.
8711 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8713 let events = nodes[1].node.get_and_clear_pending_msg_events();
8714 assert_eq!(events.len(), 1);
8716 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8717 // Technically, at this point, nodes[1] would be justified in thinking both the
8718 // first (valid) and second (invalid) channels are closed, given they both have
8719 // the same non-temporary channel_id. However, currently we do not, so we just
8720 // move forward with it.
8721 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8722 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8724 _ => panic!("Unexpected event"),
8728 // Move the first channel through the funding flow...
8729 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
8731 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
8732 check_added_monitors!(nodes[0], 0);
8734 let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8735 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
8737 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
8738 assert_eq!(added_monitors.len(), 1);
8739 assert_eq!(added_monitors[0].0, funding_output);
8740 added_monitors.clear();
8742 let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
8744 let funding_outpoint = ::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
8745 let channel_id = funding_outpoint.to_channel_id();
8747 // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
8750 // First try to open a second channel with a temporary channel id equal to the txid-based one.
8751 // Technically this is allowed by the spec, but we don't support it and there's little reason
8752 // to. Still, it shouldn't cause any other issues.
8753 open_chan_msg.temporary_channel_id = channel_id;
8754 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_msg);
8756 let events = nodes[1].node.get_and_clear_pending_msg_events();
8757 assert_eq!(events.len(), 1);
8759 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8760 // Technically, at this point, nodes[1] would be justified in thinking both
8761 // channels are closed, but currently we do not, so we just move forward with it.
8762 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
8763 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8765 _ => panic!("Unexpected event"),
8769 // Now try to create a second channel which has a duplicate funding output.
8770 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
8771 let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8772 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_chan_2_msg);
8773 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()));
8774 create_funding_transaction(&nodes[0], 100000, 42); // Get and check the FundingGenerationReady event
8776 let funding_created = {
8777 let mut a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
8778 let mut as_chan = a_channel_lock.by_id.get_mut(&open_chan_2_msg.temporary_channel_id).unwrap();
8779 let logger = test_utils::TestLogger::new();
8780 as_chan.get_outbound_funding_created(funding_outpoint, &&logger).unwrap()
8782 check_added_monitors!(nodes[0], 0);
8783 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
8784 // At this point we'll try to add a duplicate channel monitor, which will be rejected, but
8785 // still needs to be cleared here.
8786 check_added_monitors!(nodes[1], 1);
8788 // ...still, nodes[1] will reject the duplicate channel.
8790 let events = nodes[1].node.get_and_clear_pending_msg_events();
8791 assert_eq!(events.len(), 1);
8793 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
8794 // Technically, at this point, nodes[1] would be justified in thinking both
8795 // channels are closed, but currently we do not, so we just move forward with it.
8796 assert_eq!(msg.channel_id, channel_id);
8797 assert_eq!(node_id, nodes[0].node.get_our_node_id());
8799 _ => panic!("Unexpected event"),
8803 // finally, finish creating the original channel and send a payment over it to make sure
8804 // everything is functional.
8805 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
8807 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
8808 assert_eq!(added_monitors.len(), 1);
8809 assert_eq!(added_monitors[0].0, funding_output);
8810 added_monitors.clear();
8813 let events_4 = nodes[0].node.get_and_clear_pending_events();
8814 assert_eq!(events_4.len(), 1);
8816 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
8817 assert_eq!(user_channel_id, 42);
8818 assert_eq!(*funding_txo, funding_output);
8820 _ => panic!("Unexpected event"),
8823 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
8824 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
8825 update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
8826 send_payment(&nodes[0], &[&nodes[1]], 8000000, 8_000_000);