1 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
2 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
3 //! claim outputs on-chain.
5 use chain::transaction::OutPoint;
6 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
7 use chain::chaininterface;
8 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channelmonitor;
13 use ln::channel::{Channel, ChannelError};
14 use ln::{chan_utils, onion_utils};
15 use ln::router::{Route, RouteHop};
16 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
18 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
20 use util::{byte_utils, test_utils};
21 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
22 use util::errors::APIError;
23 use util::ser::{Writeable, Writer, ReadableArgs};
24 use util::config::UserConfig;
25 use util::logger::Logger;
27 use bitcoin::util::hash::BitcoinHash;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hash_types::{Txid, BlockHash};
30 use bitcoin::util::bip143;
31 use bitcoin::util::address::Address;
32 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
33 use bitcoin::blockdata::block::{Block, BlockHeader};
34 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
35 use bitcoin::blockdata::script::{Builder, Script};
36 use bitcoin::blockdata::opcodes;
37 use bitcoin::blockdata::constants::genesis_block;
38 use bitcoin::network::constants::Network;
40 use bitcoin::hashes::sha256::Hash as Sha256;
41 use bitcoin::hashes::Hash;
43 use bitcoin::secp256k1::{Secp256k1, Message};
44 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
46 use std::collections::{BTreeSet, HashMap, HashSet};
47 use std::default::Default;
48 use std::sync::{Arc, Mutex};
49 use std::sync::atomic::Ordering;
52 use rand::{thread_rng, Rng};
54 use ln::functional_test_utils::*;
57 fn test_insane_channel_opens() {
58 // Stand up a network of 2 nodes
59 let chanmon_cfgs = create_chanmon_cfgs(2);
60 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
61 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
62 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
64 // Instantiate channel parameters where we push the maximum msats given our
66 let channel_value_sat = 31337; // same as funding satoshis
67 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_our_channel_reserve_satoshis(channel_value_sat);
68 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
70 // Have node0 initiate a channel to node1 with aforementioned parameters
71 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
73 // Extract the channel open message from node0 to node1
74 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
76 // Test helper that asserts we get the correct error string given a mutator
77 // that supposedly makes the channel open message insane
78 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
79 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
80 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
81 assert_eq!(msg_events.len(), 1);
82 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
84 &ErrorAction::SendErrorMessage { .. } => {
85 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
87 _ => panic!("unexpected event!"),
89 } else { assert!(false); }
92 use ln::channel::MAX_FUNDING_SATOSHIS;
93 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
95 // Test all mutations that would make the channel open message insane
96 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
98 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
100 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
102 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
104 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
106 insane_open_helper("Minimum htlc value is full channel value", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
108 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 });
110 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
112 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
116 fn test_async_inbound_update_fee() {
117 let chanmon_cfgs = create_chanmon_cfgs(2);
118 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
119 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
120 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
121 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
122 let channel_id = chan.2;
125 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
129 // send (1) commitment_signed -.
130 // <- update_add_htlc/commitment_signed
131 // send (2) RAA (awaiting remote revoke) -.
132 // (1) commitment_signed is delivered ->
133 // .- send (3) RAA (awaiting remote revoke)
134 // (2) RAA is delivered ->
135 // .- send (4) commitment_signed
136 // <- (3) RAA is delivered
137 // send (5) commitment_signed -.
138 // <- (4) commitment_signed is delivered
140 // (5) commitment_signed is delivered ->
142 // (6) RAA is delivered ->
144 // First nodes[0] generates an update_fee
145 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
146 check_added_monitors!(nodes[0], 1);
148 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
149 assert_eq!(events_0.len(), 1);
150 let (update_msg, commitment_signed) = match events_0[0] { // (1)
151 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
152 (update_fee.as_ref(), commitment_signed)
154 _ => panic!("Unexpected event"),
157 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
159 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
160 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
161 nodes[1].node.send_payment(&nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash, &None).unwrap();
162 check_added_monitors!(nodes[1], 1);
164 let payment_event = {
165 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
166 assert_eq!(events_1.len(), 1);
167 SendEvent::from_event(events_1.remove(0))
169 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
170 assert_eq!(payment_event.msgs.len(), 1);
172 // ...now when the messages get delivered everyone should be happy
173 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
174 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
175 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
176 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
177 check_added_monitors!(nodes[0], 1);
179 // deliver(1), generate (3):
180 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
181 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
182 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
183 check_added_monitors!(nodes[1], 1);
185 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
186 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
187 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
188 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
189 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
190 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
191 assert!(bs_update.update_fee.is_none()); // (4)
192 check_added_monitors!(nodes[1], 1);
194 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
195 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
196 assert!(as_update.update_add_htlcs.is_empty()); // (5)
197 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
198 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
199 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
200 assert!(as_update.update_fee.is_none()); // (5)
201 check_added_monitors!(nodes[0], 1);
203 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
204 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
205 // only (6) so get_event_msg's assert(len == 1) passes
206 check_added_monitors!(nodes[0], 1);
208 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
209 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
210 check_added_monitors!(nodes[1], 1);
212 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
213 check_added_monitors!(nodes[0], 1);
215 let events_2 = nodes[0].node.get_and_clear_pending_events();
216 assert_eq!(events_2.len(), 1);
218 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
219 _ => panic!("Unexpected event"),
222 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
223 check_added_monitors!(nodes[1], 1);
227 fn test_update_fee_unordered_raa() {
228 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
229 // crash in an earlier version of the update_fee patch)
230 let chanmon_cfgs = create_chanmon_cfgs(2);
231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
233 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
234 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
235 let channel_id = chan.2;
238 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
240 // First nodes[0] generates an update_fee
241 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
242 check_added_monitors!(nodes[0], 1);
244 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
245 assert_eq!(events_0.len(), 1);
246 let update_msg = match events_0[0] { // (1)
247 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
250 _ => panic!("Unexpected event"),
253 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
255 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
256 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
257 nodes[1].node.send_payment(&nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash, &None).unwrap();
258 check_added_monitors!(nodes[1], 1);
260 let payment_event = {
261 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
262 assert_eq!(events_1.len(), 1);
263 SendEvent::from_event(events_1.remove(0))
265 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
266 assert_eq!(payment_event.msgs.len(), 1);
268 // ...now when the messages get delivered everyone should be happy
269 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
270 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
271 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
272 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
273 check_added_monitors!(nodes[0], 1);
275 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
276 check_added_monitors!(nodes[1], 1);
278 // We can't continue, sadly, because our (1) now has a bogus signature
282 fn test_multi_flight_update_fee() {
283 let chanmon_cfgs = create_chanmon_cfgs(2);
284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
286 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
287 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
288 let channel_id = chan.2;
291 // update_fee/commitment_signed ->
292 // .- send (1) RAA and (2) commitment_signed
293 // update_fee (never committed) ->
295 // We have to manually generate the above update_fee, it is allowed by the protocol but we
296 // don't track which updates correspond to which revoke_and_ack responses so we're in
297 // AwaitingRAA mode and will not generate the update_fee yet.
298 // <- (1) RAA delivered
299 // (3) is generated and send (4) CS -.
300 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
301 // know the per_commitment_point to use for it.
302 // <- (2) commitment_signed delivered
304 // B should send no response here
305 // (4) commitment_signed delivered ->
306 // <- RAA/commitment_signed delivered
309 // First nodes[0] generates an update_fee
310 let initial_feerate = get_feerate!(nodes[0], channel_id);
311 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
312 check_added_monitors!(nodes[0], 1);
314 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
315 assert_eq!(events_0.len(), 1);
316 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
317 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
318 (update_fee.as_ref().unwrap(), commitment_signed)
320 _ => panic!("Unexpected event"),
323 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
324 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
325 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
326 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
327 check_added_monitors!(nodes[1], 1);
329 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
331 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
332 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
333 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
335 // Create the (3) update_fee message that nodes[0] will generate before it does...
336 let mut update_msg_2 = msgs::UpdateFee {
337 channel_id: update_msg_1.channel_id.clone(),
338 feerate_per_kw: (initial_feerate + 30) as u32,
341 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
343 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
345 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
347 // Deliver (1), generating (3) and (4)
348 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
349 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
350 check_added_monitors!(nodes[0], 1);
351 assert!(as_second_update.update_add_htlcs.is_empty());
352 assert!(as_second_update.update_fulfill_htlcs.is_empty());
353 assert!(as_second_update.update_fail_htlcs.is_empty());
354 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
355 // Check that the update_fee newly generated matches what we delivered:
356 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
357 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
359 // Deliver (2) commitment_signed
360 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
361 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
362 check_added_monitors!(nodes[0], 1);
363 // No commitment_signed so get_event_msg's assert(len == 1) passes
365 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
366 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
367 check_added_monitors!(nodes[1], 1);
370 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
371 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
372 check_added_monitors!(nodes[1], 1);
374 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
375 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
376 check_added_monitors!(nodes[0], 1);
378 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
379 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
380 // No commitment_signed so get_event_msg's assert(len == 1) passes
381 check_added_monitors!(nodes[0], 1);
383 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
384 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
385 check_added_monitors!(nodes[1], 1);
389 fn test_1_conf_open() {
390 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
391 // tests that we properly send one in that case.
392 let mut alice_config = UserConfig::default();
393 alice_config.own_channel_config.minimum_depth = 1;
394 alice_config.channel_options.announced_channel = true;
395 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
396 let mut bob_config = UserConfig::default();
397 bob_config.own_channel_config.minimum_depth = 1;
398 bob_config.channel_options.announced_channel = true;
399 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
400 let chanmon_cfgs = create_chanmon_cfgs(2);
401 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
402 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
403 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
405 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
406 assert!(nodes[0].chain_monitor.does_match_tx(&tx));
407 assert!(nodes[1].chain_monitor.does_match_tx(&tx));
409 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
410 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
411 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()));
413 nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
414 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
415 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
418 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
419 node.router.handle_channel_update(&as_update).unwrap();
420 node.router.handle_channel_update(&bs_update).unwrap();
424 fn do_test_sanity_on_in_flight_opens(steps: u8) {
425 // Previously, we had issues deserializing channels when we hadn't connected the first block
426 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
427 // serialization round-trips and simply do steps towards opening a channel and then drop the
430 let chanmon_cfgs = create_chanmon_cfgs(2);
431 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
432 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
433 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
435 if steps & 0b1000_0000 != 0{
436 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
437 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
438 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
441 if steps & 0x0f == 0 { return; }
442 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
443 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
445 if steps & 0x0f == 1 { return; }
446 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
447 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
449 if steps & 0x0f == 2 { return; }
450 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
452 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
454 if steps & 0x0f == 3 { return; }
455 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
456 check_added_monitors!(nodes[0], 0);
457 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
459 if steps & 0x0f == 4 { return; }
460 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
462 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
463 assert_eq!(added_monitors.len(), 1);
464 assert_eq!(added_monitors[0].0, funding_output);
465 added_monitors.clear();
467 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
469 if steps & 0x0f == 5 { return; }
470 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
472 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
473 assert_eq!(added_monitors.len(), 1);
474 assert_eq!(added_monitors[0].0, funding_output);
475 added_monitors.clear();
478 let events_4 = nodes[0].node.get_and_clear_pending_events();
479 assert_eq!(events_4.len(), 1);
481 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
482 assert_eq!(user_channel_id, 42);
483 assert_eq!(*funding_txo, funding_output);
485 _ => panic!("Unexpected event"),
488 if steps & 0x0f == 6 { return; }
489 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
491 if steps & 0x0f == 7 { return; }
492 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
493 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
497 fn test_sanity_on_in_flight_opens() {
498 do_test_sanity_on_in_flight_opens(0);
499 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
500 do_test_sanity_on_in_flight_opens(1);
501 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
502 do_test_sanity_on_in_flight_opens(2);
503 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
504 do_test_sanity_on_in_flight_opens(3);
505 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
506 do_test_sanity_on_in_flight_opens(4);
507 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
508 do_test_sanity_on_in_flight_opens(5);
509 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
510 do_test_sanity_on_in_flight_opens(6);
511 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
512 do_test_sanity_on_in_flight_opens(7);
513 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
514 do_test_sanity_on_in_flight_opens(8);
515 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
519 fn test_update_fee_vanilla() {
520 let chanmon_cfgs = create_chanmon_cfgs(2);
521 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
522 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
523 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
524 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
525 let channel_id = chan.2;
527 let feerate = get_feerate!(nodes[0], channel_id);
528 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
529 check_added_monitors!(nodes[0], 1);
531 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
532 assert_eq!(events_0.len(), 1);
533 let (update_msg, commitment_signed) = match events_0[0] {
534 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 } } => {
535 (update_fee.as_ref(), commitment_signed)
537 _ => panic!("Unexpected event"),
539 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
541 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
542 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
543 check_added_monitors!(nodes[1], 1);
545 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
546 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
547 check_added_monitors!(nodes[0], 1);
549 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
550 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
551 // No commitment_signed so get_event_msg's assert(len == 1) passes
552 check_added_monitors!(nodes[0], 1);
554 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
555 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
556 check_added_monitors!(nodes[1], 1);
560 fn test_update_fee_that_funder_cannot_afford() {
561 let chanmon_cfgs = create_chanmon_cfgs(2);
562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
565 let channel_value = 1888;
566 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
567 let channel_id = chan.2;
570 nodes[0].node.update_fee(channel_id, feerate).unwrap();
571 check_added_monitors!(nodes[0], 1);
572 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
574 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
576 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
578 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
579 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
581 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
583 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
584 let num_htlcs = commitment_tx.output.len() - 2;
585 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
586 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
587 actual_fee = channel_value - actual_fee;
588 assert_eq!(total_fee, actual_fee);
591 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
592 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
593 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
594 check_added_monitors!(nodes[0], 1);
596 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
598 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
600 //While producing the commitment_signed response after handling a received update_fee request the
601 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
602 //Should produce and error.
603 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
604 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
605 check_added_monitors!(nodes[1], 1);
606 check_closed_broadcast!(nodes[1], true);
610 fn test_update_fee_with_fundee_update_add_htlc() {
611 let chanmon_cfgs = create_chanmon_cfgs(2);
612 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
613 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
614 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
615 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
616 let channel_id = chan.2;
619 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
621 let feerate = get_feerate!(nodes[0], channel_id);
622 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
623 check_added_monitors!(nodes[0], 1);
625 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
626 assert_eq!(events_0.len(), 1);
627 let (update_msg, commitment_signed) = match events_0[0] {
628 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 } } => {
629 (update_fee.as_ref(), commitment_signed)
631 _ => panic!("Unexpected event"),
633 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
634 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
635 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
636 check_added_monitors!(nodes[1], 1);
638 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
640 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
642 // nothing happens since node[1] is in AwaitingRemoteRevoke
643 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
645 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
646 assert_eq!(added_monitors.len(), 0);
647 added_monitors.clear();
649 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
650 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
651 // node[1] has nothing to do
653 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
654 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
655 check_added_monitors!(nodes[0], 1);
657 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
658 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
659 // No commitment_signed so get_event_msg's assert(len == 1) passes
660 check_added_monitors!(nodes[0], 1);
661 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
662 check_added_monitors!(nodes[1], 1);
663 // AwaitingRemoteRevoke ends here
665 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
666 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
667 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
668 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
669 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
670 assert_eq!(commitment_update.update_fee.is_none(), true);
672 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
673 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
674 check_added_monitors!(nodes[0], 1);
675 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
677 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
678 check_added_monitors!(nodes[1], 1);
679 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
681 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
682 check_added_monitors!(nodes[1], 1);
683 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
684 // No commitment_signed so get_event_msg's assert(len == 1) passes
686 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
687 check_added_monitors!(nodes[0], 1);
688 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
690 expect_pending_htlcs_forwardable!(nodes[0]);
692 let events = nodes[0].node.get_and_clear_pending_events();
693 assert_eq!(events.len(), 1);
695 Event::PaymentReceived { .. } => { },
696 _ => panic!("Unexpected event"),
699 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
701 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
702 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
703 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
707 fn test_update_fee() {
708 let chanmon_cfgs = create_chanmon_cfgs(2);
709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
711 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
712 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
713 let channel_id = chan.2;
716 // (1) update_fee/commitment_signed ->
717 // <- (2) revoke_and_ack
718 // .- send (3) commitment_signed
719 // (4) update_fee/commitment_signed ->
720 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
721 // <- (3) commitment_signed delivered
722 // send (6) revoke_and_ack -.
723 // <- (5) deliver revoke_and_ack
724 // (6) deliver revoke_and_ack ->
725 // .- send (7) commitment_signed in response to (4)
726 // <- (7) deliver commitment_signed
729 // Create and deliver (1)...
730 let feerate = get_feerate!(nodes[0], channel_id);
731 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
732 check_added_monitors!(nodes[0], 1);
734 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
735 assert_eq!(events_0.len(), 1);
736 let (update_msg, commitment_signed) = match events_0[0] {
737 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 } } => {
738 (update_fee.as_ref(), commitment_signed)
740 _ => panic!("Unexpected event"),
742 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
744 // Generate (2) and (3):
745 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
746 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
747 check_added_monitors!(nodes[1], 1);
750 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
751 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
752 check_added_monitors!(nodes[0], 1);
754 // Create and deliver (4)...
755 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
756 check_added_monitors!(nodes[0], 1);
757 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
758 assert_eq!(events_0.len(), 1);
759 let (update_msg, commitment_signed) = match events_0[0] {
760 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 } } => {
761 (update_fee.as_ref(), commitment_signed)
763 _ => panic!("Unexpected event"),
766 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
767 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
768 check_added_monitors!(nodes[1], 1);
770 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
771 // No commitment_signed so get_event_msg's assert(len == 1) passes
773 // Handle (3), creating (6):
774 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
775 check_added_monitors!(nodes[0], 1);
776 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
777 // No commitment_signed so get_event_msg's assert(len == 1) passes
780 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
781 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
782 check_added_monitors!(nodes[0], 1);
784 // Deliver (6), creating (7):
785 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
786 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
787 assert!(commitment_update.update_add_htlcs.is_empty());
788 assert!(commitment_update.update_fulfill_htlcs.is_empty());
789 assert!(commitment_update.update_fail_htlcs.is_empty());
790 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
791 assert!(commitment_update.update_fee.is_none());
792 check_added_monitors!(nodes[1], 1);
795 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
796 check_added_monitors!(nodes[0], 1);
797 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
798 // No commitment_signed so get_event_msg's assert(len == 1) passes
800 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
801 check_added_monitors!(nodes[1], 1);
802 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
804 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
805 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
806 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
810 fn pre_funding_lock_shutdown_test() {
811 // Test sending a shutdown prior to funding_locked after funding generation
812 let chanmon_cfgs = create_chanmon_cfgs(2);
813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
815 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
816 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
817 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
818 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
819 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
821 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
822 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
823 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
824 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
825 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
827 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
828 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
829 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
830 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
831 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
832 assert!(node_0_none.is_none());
834 assert!(nodes[0].node.list_channels().is_empty());
835 assert!(nodes[1].node.list_channels().is_empty());
839 fn updates_shutdown_wait() {
840 // Test sending a shutdown with outstanding updates pending
841 let chanmon_cfgs = create_chanmon_cfgs(3);
842 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
843 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
844 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
845 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
846 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
847 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
848 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
850 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
852 nodes[0].node.close_channel(&chan_1.2).unwrap();
853 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
854 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
855 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
856 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
858 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
859 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
861 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
862 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
863 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
865 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
866 check_added_monitors!(nodes[2], 1);
867 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
868 assert!(updates.update_add_htlcs.is_empty());
869 assert!(updates.update_fail_htlcs.is_empty());
870 assert!(updates.update_fail_malformed_htlcs.is_empty());
871 assert!(updates.update_fee.is_none());
872 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
873 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
874 check_added_monitors!(nodes[1], 1);
875 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
876 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
878 assert!(updates_2.update_add_htlcs.is_empty());
879 assert!(updates_2.update_fail_htlcs.is_empty());
880 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
881 assert!(updates_2.update_fee.is_none());
882 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
883 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
884 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
886 let events = nodes[0].node.get_and_clear_pending_events();
887 assert_eq!(events.len(), 1);
889 Event::PaymentSent { ref payment_preimage } => {
890 assert_eq!(our_payment_preimage, *payment_preimage);
892 _ => panic!("Unexpected event"),
895 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
896 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
897 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
898 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
899 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
900 assert!(node_0_none.is_none());
902 assert!(nodes[0].node.list_channels().is_empty());
904 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
905 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
906 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
907 assert!(nodes[1].node.list_channels().is_empty());
908 assert!(nodes[2].node.list_channels().is_empty());
912 fn htlc_fail_async_shutdown() {
913 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
914 let chanmon_cfgs = create_chanmon_cfgs(3);
915 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
916 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
917 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
918 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
919 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
921 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
922 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
923 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
924 check_added_monitors!(nodes[0], 1);
925 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
926 assert_eq!(updates.update_add_htlcs.len(), 1);
927 assert!(updates.update_fulfill_htlcs.is_empty());
928 assert!(updates.update_fail_htlcs.is_empty());
929 assert!(updates.update_fail_malformed_htlcs.is_empty());
930 assert!(updates.update_fee.is_none());
932 nodes[1].node.close_channel(&chan_1.2).unwrap();
933 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
934 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
935 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
937 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
938 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
939 check_added_monitors!(nodes[1], 1);
940 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
941 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
943 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
944 assert!(updates_2.update_add_htlcs.is_empty());
945 assert!(updates_2.update_fulfill_htlcs.is_empty());
946 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
947 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
948 assert!(updates_2.update_fee.is_none());
950 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
951 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
953 expect_payment_failed!(nodes[0], our_payment_hash, false);
955 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
956 assert_eq!(msg_events.len(), 2);
957 let node_0_closing_signed = match msg_events[0] {
958 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
959 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
962 _ => panic!("Unexpected event"),
964 match msg_events[1] {
965 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
966 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
968 _ => panic!("Unexpected event"),
971 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
972 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
973 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
974 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
975 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
976 assert!(node_0_none.is_none());
978 assert!(nodes[0].node.list_channels().is_empty());
980 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
981 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
982 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
983 assert!(nodes[1].node.list_channels().is_empty());
984 assert!(nodes[2].node.list_channels().is_empty());
987 fn do_test_shutdown_rebroadcast(recv_count: u8) {
988 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
989 // messages delivered prior to disconnect
990 let chanmon_cfgs = create_chanmon_cfgs(3);
991 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
992 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
993 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
994 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
995 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
997 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
999 nodes[1].node.close_channel(&chan_1.2).unwrap();
1000 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1002 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1003 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1005 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1009 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1010 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1012 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1013 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1014 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1015 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1017 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1018 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1019 assert!(node_1_shutdown == node_1_2nd_shutdown);
1021 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1022 let node_0_2nd_shutdown = if recv_count > 0 {
1023 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1024 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1027 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1028 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1029 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1031 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1033 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1034 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1036 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1037 check_added_monitors!(nodes[2], 1);
1038 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1039 assert!(updates.update_add_htlcs.is_empty());
1040 assert!(updates.update_fail_htlcs.is_empty());
1041 assert!(updates.update_fail_malformed_htlcs.is_empty());
1042 assert!(updates.update_fee.is_none());
1043 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1044 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1045 check_added_monitors!(nodes[1], 1);
1046 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1047 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1049 assert!(updates_2.update_add_htlcs.is_empty());
1050 assert!(updates_2.update_fail_htlcs.is_empty());
1051 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1052 assert!(updates_2.update_fee.is_none());
1053 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1054 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1055 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1057 let events = nodes[0].node.get_and_clear_pending_events();
1058 assert_eq!(events.len(), 1);
1060 Event::PaymentSent { ref payment_preimage } => {
1061 assert_eq!(our_payment_preimage, *payment_preimage);
1063 _ => panic!("Unexpected event"),
1066 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1068 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1069 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1070 assert!(node_1_closing_signed.is_some());
1073 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1074 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1076 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1077 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1078 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1079 if recv_count == 0 {
1080 // If all closing_signeds weren't delivered we can just resume where we left off...
1081 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1083 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1084 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1085 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1087 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1088 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1089 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1091 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1092 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1094 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1095 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1096 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1098 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1099 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1100 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1101 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1102 assert!(node_0_none.is_none());
1104 // If one node, however, received + responded with an identical closing_signed we end
1105 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1106 // There isn't really anything better we can do simply, but in the future we might
1107 // explore storing a set of recently-closed channels that got disconnected during
1108 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1109 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1111 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1113 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1114 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1115 assert_eq!(msg_events.len(), 1);
1116 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1118 &ErrorAction::SendErrorMessage { ref msg } => {
1119 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1120 assert_eq!(msg.channel_id, chan_1.2);
1122 _ => panic!("Unexpected event!"),
1124 } else { panic!("Needed SendErrorMessage close"); }
1126 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1127 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1128 // closing_signed so we do it ourselves
1129 check_closed_broadcast!(nodes[0], false);
1130 check_added_monitors!(nodes[0], 1);
1133 assert!(nodes[0].node.list_channels().is_empty());
1135 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1136 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1137 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1138 assert!(nodes[1].node.list_channels().is_empty());
1139 assert!(nodes[2].node.list_channels().is_empty());
1143 fn test_shutdown_rebroadcast() {
1144 do_test_shutdown_rebroadcast(0);
1145 do_test_shutdown_rebroadcast(1);
1146 do_test_shutdown_rebroadcast(2);
1150 fn fake_network_test() {
1151 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1152 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1153 let chanmon_cfgs = create_chanmon_cfgs(4);
1154 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1155 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1156 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1158 // Create some initial channels
1159 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1160 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1161 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1163 // Rebalance the network a bit by relaying one payment through all the channels...
1164 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1165 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1166 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1167 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1169 // Send some more payments
1170 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1171 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1172 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1174 // Test failure packets
1175 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1176 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1178 // Add a new channel that skips 3
1179 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1181 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1182 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1183 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1184 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1185 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1186 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1187 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1189 // Do some rebalance loop payments, simultaneously
1190 let mut hops = Vec::with_capacity(3);
1191 hops.push(RouteHop {
1192 pubkey: nodes[2].node.get_our_node_id(),
1193 node_features: NodeFeatures::empty(),
1194 short_channel_id: chan_2.0.contents.short_channel_id,
1195 channel_features: ChannelFeatures::empty(),
1197 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1199 hops.push(RouteHop {
1200 pubkey: nodes[3].node.get_our_node_id(),
1201 node_features: NodeFeatures::empty(),
1202 short_channel_id: chan_3.0.contents.short_channel_id,
1203 channel_features: ChannelFeatures::empty(),
1205 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1207 hops.push(RouteHop {
1208 pubkey: nodes[1].node.get_our_node_id(),
1209 node_features: NodeFeatures::empty(),
1210 short_channel_id: chan_4.0.contents.short_channel_id,
1211 channel_features: ChannelFeatures::empty(),
1213 cltv_expiry_delta: TEST_FINAL_CLTV,
1215 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;
1216 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;
1217 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1219 let mut hops = Vec::with_capacity(3);
1220 hops.push(RouteHop {
1221 pubkey: nodes[3].node.get_our_node_id(),
1222 node_features: NodeFeatures::empty(),
1223 short_channel_id: chan_4.0.contents.short_channel_id,
1224 channel_features: ChannelFeatures::empty(),
1226 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1228 hops.push(RouteHop {
1229 pubkey: nodes[2].node.get_our_node_id(),
1230 node_features: NodeFeatures::empty(),
1231 short_channel_id: chan_3.0.contents.short_channel_id,
1232 channel_features: ChannelFeatures::empty(),
1234 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1236 hops.push(RouteHop {
1237 pubkey: nodes[1].node.get_our_node_id(),
1238 node_features: NodeFeatures::empty(),
1239 short_channel_id: chan_2.0.contents.short_channel_id,
1240 channel_features: ChannelFeatures::empty(),
1242 cltv_expiry_delta: TEST_FINAL_CLTV,
1244 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;
1245 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;
1246 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1248 // Claim the rebalances...
1249 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1250 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1252 // Add a duplicate new channel from 2 to 4
1253 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1255 // Send some payments across both channels
1256 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1257 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1258 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1261 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1262 let events = nodes[0].node.get_and_clear_pending_msg_events();
1263 assert_eq!(events.len(), 0);
1264 nodes[0].logger.assert_log("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);
1266 //TODO: Test that routes work again here as we've been notified that the channel is full
1268 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1269 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1270 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1272 // Close down the channels...
1273 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1274 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1275 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1276 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1277 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1281 fn holding_cell_htlc_counting() {
1282 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1283 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1284 // commitment dance rounds.
1285 let chanmon_cfgs = create_chanmon_cfgs(3);
1286 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1287 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1288 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1289 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1290 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1292 let mut payments = Vec::new();
1293 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1294 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1295 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1296 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1297 payments.push((payment_preimage, payment_hash));
1299 check_added_monitors!(nodes[1], 1);
1301 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1302 assert_eq!(events.len(), 1);
1303 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1304 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1306 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1307 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1309 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1310 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1311 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1312 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1313 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1314 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1316 // This should also be true if we try to forward a payment.
1317 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1318 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1319 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1320 check_added_monitors!(nodes[0], 1);
1322 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1323 assert_eq!(events.len(), 1);
1324 let payment_event = SendEvent::from_event(events.pop().unwrap());
1325 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1327 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1328 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1329 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1330 // fails), the second will process the resulting failure and fail the HTLC backward.
1331 expect_pending_htlcs_forwardable!(nodes[1]);
1332 expect_pending_htlcs_forwardable!(nodes[1]);
1333 check_added_monitors!(nodes[1], 1);
1335 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1336 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1337 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1339 let events = nodes[0].node.get_and_clear_pending_msg_events();
1340 assert_eq!(events.len(), 1);
1342 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1343 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1345 _ => panic!("Unexpected event"),
1348 expect_payment_failed!(nodes[0], payment_hash_2, false);
1350 // Now forward all the pending HTLCs and claim them back
1351 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1352 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1353 check_added_monitors!(nodes[2], 1);
1355 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1356 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1357 check_added_monitors!(nodes[1], 1);
1358 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1360 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1361 check_added_monitors!(nodes[1], 1);
1362 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1364 for ref update in as_updates.update_add_htlcs.iter() {
1365 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1367 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1368 check_added_monitors!(nodes[2], 1);
1369 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1370 check_added_monitors!(nodes[2], 1);
1371 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1373 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1374 check_added_monitors!(nodes[1], 1);
1375 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1376 check_added_monitors!(nodes[1], 1);
1377 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1379 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1380 check_added_monitors!(nodes[2], 1);
1382 expect_pending_htlcs_forwardable!(nodes[2]);
1384 let events = nodes[2].node.get_and_clear_pending_events();
1385 assert_eq!(events.len(), payments.len());
1386 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1388 &Event::PaymentReceived { ref payment_hash, .. } => {
1389 assert_eq!(*payment_hash, *hash);
1391 _ => panic!("Unexpected event"),
1395 for (preimage, _) in payments.drain(..) {
1396 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1399 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1403 fn duplicate_htlc_test() {
1404 // Test that we accept duplicate payment_hash HTLCs across the network and that
1405 // claiming/failing them are all separate and don't affect each other
1406 let chanmon_cfgs = create_chanmon_cfgs(6);
1407 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1408 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1409 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1411 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1412 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1413 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1414 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1415 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1416 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1418 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1420 *nodes[0].network_payment_count.borrow_mut() -= 1;
1421 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1423 *nodes[0].network_payment_count.borrow_mut() -= 1;
1424 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1426 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1427 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1428 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1432 fn test_duplicate_htlc_different_direction_onchain() {
1433 // Test that ChannelMonitor doesn't generate 2 preimage txn
1434 // when we have 2 HTLCs with same preimage that go across a node
1435 // in opposite directions.
1436 let chanmon_cfgs = create_chanmon_cfgs(2);
1437 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1438 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1439 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1441 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1444 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1446 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1448 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1449 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1451 // Provide preimage to node 0 by claiming payment
1452 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1453 check_added_monitors!(nodes[0], 1);
1455 // Broadcast node 1 commitment txn
1456 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1458 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1459 let mut has_both_htlcs = 0; // check htlcs match ones committed
1460 for outp in remote_txn[0].output.iter() {
1461 if outp.value == 800_000 / 1000 {
1462 has_both_htlcs += 1;
1463 } else if outp.value == 900_000 / 1000 {
1464 has_both_htlcs += 1;
1467 assert_eq!(has_both_htlcs, 2);
1469 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1470 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1471 check_added_monitors!(nodes[0], 1);
1473 // Check we only broadcast 1 timeout tx
1474 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1475 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()) };
1476 assert_eq!(claim_txn.len(), 5);
1477 check_spends!(claim_txn[2], chan_1.3);
1478 check_spends!(claim_txn[3], claim_txn[2]);
1479 assert_eq!(htlc_pair.0.input.len(), 1);
1480 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1481 check_spends!(htlc_pair.0, remote_txn[0]);
1482 assert_eq!(htlc_pair.1.input.len(), 1);
1483 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1484 check_spends!(htlc_pair.1, remote_txn[0]);
1486 let events = nodes[0].node.get_and_clear_pending_msg_events();
1487 assert_eq!(events.len(), 2);
1490 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1491 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, .. } } => {
1492 assert!(update_add_htlcs.is_empty());
1493 assert!(update_fail_htlcs.is_empty());
1494 assert_eq!(update_fulfill_htlcs.len(), 1);
1495 assert!(update_fail_malformed_htlcs.is_empty());
1496 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1498 _ => panic!("Unexpected event"),
1503 fn do_channel_reserve_test(test_recv: bool) {
1505 let chanmon_cfgs = create_chanmon_cfgs(3);
1506 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1507 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1508 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1509 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1510 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1512 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1513 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1515 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1516 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1518 macro_rules! get_route_and_payment_hash {
1519 ($recv_value: expr) => {{
1520 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1521 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1522 (route, payment_hash, payment_preimage)
1526 macro_rules! expect_forward {
1528 let mut events = $node.node.get_and_clear_pending_msg_events();
1529 assert_eq!(events.len(), 1);
1530 check_added_monitors!($node, 1);
1531 let payment_event = SendEvent::from_event(events.remove(0));
1536 let feemsat = 239; // somehow we know?
1537 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1539 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1541 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1543 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1544 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1545 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1546 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1547 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1548 nodes[0].logger.assert_log("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);
1551 let mut htlc_id = 0;
1552 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1553 // nodes[0]'s wealth
1555 let amt_msat = recv_value_0 + total_fee_msat;
1556 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1559 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1562 let (stat01_, stat11_, stat12_, stat22_) = (
1563 get_channel_value_stat!(nodes[0], chan_1.2),
1564 get_channel_value_stat!(nodes[1], chan_1.2),
1565 get_channel_value_stat!(nodes[1], chan_2.2),
1566 get_channel_value_stat!(nodes[2], chan_2.2),
1569 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1570 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1571 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1572 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1573 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1577 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1578 // attempt to get channel_reserve violation
1579 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1580 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1581 assert_eq!(err, "Cannot send value that would put us over their reserve value"));
1582 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1583 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 1);
1586 // adding pending output
1587 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1588 let amt_msat_1 = recv_value_1 + total_fee_msat;
1590 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1591 let payment_event_1 = {
1592 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1593 check_added_monitors!(nodes[0], 1);
1595 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1596 assert_eq!(events.len(), 1);
1597 SendEvent::from_event(events.remove(0))
1599 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1601 // channel reserve test with htlc pending output > 0
1602 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1604 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1605 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1606 assert_eq!(err, "Cannot send value that would put us over their reserve value"));
1607 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1608 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 2);
1612 // test channel_reserve test on nodes[1] side
1613 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1615 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1616 let secp_ctx = Secp256k1::new();
1617 let session_priv = SecretKey::from_slice(&{
1618 let mut session_key = [0; 32];
1619 let mut rng = thread_rng();
1620 rng.fill_bytes(&mut session_key);
1622 }).expect("RNG is bad!");
1624 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1625 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1626 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1627 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1628 let msg = msgs::UpdateAddHTLC {
1629 channel_id: chan_1.2,
1631 amount_msat: htlc_msat,
1632 payment_hash: our_payment_hash,
1633 cltv_expiry: htlc_cltv,
1634 onion_routing_packet: onion_packet,
1638 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1639 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1640 assert_eq!(nodes[1].node.list_channels().len(), 1);
1641 assert_eq!(nodes[1].node.list_channels().len(), 1);
1642 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1643 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
1644 check_added_monitors!(nodes[1], 1);
1649 // split the rest to test holding cell
1650 let recv_value_21 = recv_value_2/2;
1651 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1653 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1654 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), stat.channel_reserve_msat);
1657 // now see if they go through on both sides
1658 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1659 // but this will stuck in the holding cell
1660 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1661 check_added_monitors!(nodes[0], 0);
1662 let events = nodes[0].node.get_and_clear_pending_events();
1663 assert_eq!(events.len(), 0);
1665 // test with outbound holding cell amount > 0
1667 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1668 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1669 assert_eq!(err, "Cannot send value that would put us over their reserve value"));
1670 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1671 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 3);
1674 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1675 // this will also stuck in the holding cell
1676 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1677 check_added_monitors!(nodes[0], 0);
1678 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1679 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1681 // flush the pending htlc
1682 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1683 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1684 check_added_monitors!(nodes[1], 1);
1686 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1687 check_added_monitors!(nodes[0], 1);
1688 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1690 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1691 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1692 // No commitment_signed so get_event_msg's assert(len == 1) passes
1693 check_added_monitors!(nodes[0], 1);
1695 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1696 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1697 check_added_monitors!(nodes[1], 1);
1699 expect_pending_htlcs_forwardable!(nodes[1]);
1701 let ref payment_event_11 = expect_forward!(nodes[1]);
1702 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1703 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1705 expect_pending_htlcs_forwardable!(nodes[2]);
1706 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1708 // flush the htlcs in the holding cell
1709 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1711 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1712 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1713 expect_pending_htlcs_forwardable!(nodes[1]);
1715 let ref payment_event_3 = expect_forward!(nodes[1]);
1716 assert_eq!(payment_event_3.msgs.len(), 2);
1717 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1718 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1720 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1721 expect_pending_htlcs_forwardable!(nodes[2]);
1723 let events = nodes[2].node.get_and_clear_pending_events();
1724 assert_eq!(events.len(), 2);
1726 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1727 assert_eq!(our_payment_hash_21, *payment_hash);
1728 assert_eq!(*payment_secret, None);
1729 assert_eq!(recv_value_21, amt);
1731 _ => panic!("Unexpected event"),
1734 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1735 assert_eq!(our_payment_hash_22, *payment_hash);
1736 assert_eq!(None, *payment_secret);
1737 assert_eq!(recv_value_22, amt);
1739 _ => panic!("Unexpected event"),
1742 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1743 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1744 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1746 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);
1747 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1748 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1749 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1751 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1752 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1756 fn channel_reserve_test() {
1757 do_channel_reserve_test(false);
1758 do_channel_reserve_test(true);
1762 fn channel_reserve_in_flight_removes() {
1763 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1764 // can send to its counterparty, but due to update ordering, the other side may not yet have
1765 // considered those HTLCs fully removed.
1766 // This tests that we don't count HTLCs which will not be included in the next remote
1767 // commitment transaction towards the reserve value (as it implies no commitment transaction
1768 // will be generated which violates the remote reserve value).
1769 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1771 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1772 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1773 // you only consider the value of the first HTLC, it may not),
1774 // * start routing a third HTLC from A to B,
1775 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1776 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1777 // * deliver the first fulfill from B
1778 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1780 // * deliver A's response CS and RAA.
1781 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1782 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1783 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1784 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1785 let chanmon_cfgs = create_chanmon_cfgs(2);
1786 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1787 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1788 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1789 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1791 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1792 // Route the first two HTLCs.
1793 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1794 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1796 // Start routing the third HTLC (this is just used to get everyone in the right state).
1797 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1799 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1800 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1801 check_added_monitors!(nodes[0], 1);
1802 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1803 assert_eq!(events.len(), 1);
1804 SendEvent::from_event(events.remove(0))
1807 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1808 // initial fulfill/CS.
1809 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1810 check_added_monitors!(nodes[1], 1);
1811 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1813 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1814 // remove the second HTLC when we send the HTLC back from B to A.
1815 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1816 check_added_monitors!(nodes[1], 1);
1817 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1819 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1820 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1821 check_added_monitors!(nodes[0], 1);
1822 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1823 expect_payment_sent!(nodes[0], payment_preimage_1);
1825 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1826 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1827 check_added_monitors!(nodes[1], 1);
1828 // B is already AwaitingRAA, so cant generate a CS here
1829 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1831 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1832 check_added_monitors!(nodes[1], 1);
1833 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1835 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1836 check_added_monitors!(nodes[0], 1);
1837 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1839 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1840 check_added_monitors!(nodes[1], 1);
1841 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1843 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1844 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1845 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1846 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1847 // on-chain as necessary).
1848 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1849 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1850 check_added_monitors!(nodes[0], 1);
1851 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1852 expect_payment_sent!(nodes[0], payment_preimage_2);
1854 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1855 check_added_monitors!(nodes[1], 1);
1856 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1858 expect_pending_htlcs_forwardable!(nodes[1]);
1859 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1861 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1862 // resolve the second HTLC from A's point of view.
1863 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1864 check_added_monitors!(nodes[0], 1);
1865 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1867 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1868 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1869 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1871 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1872 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1873 check_added_monitors!(nodes[1], 1);
1874 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1875 assert_eq!(events.len(), 1);
1876 SendEvent::from_event(events.remove(0))
1879 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1880 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1881 check_added_monitors!(nodes[0], 1);
1882 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1884 // Now just resolve all the outstanding messages/HTLCs for completeness...
1886 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1887 check_added_monitors!(nodes[1], 1);
1888 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1890 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1891 check_added_monitors!(nodes[1], 1);
1893 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1894 check_added_monitors!(nodes[0], 1);
1895 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1897 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1898 check_added_monitors!(nodes[1], 1);
1899 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1901 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1902 check_added_monitors!(nodes[0], 1);
1904 expect_pending_htlcs_forwardable!(nodes[0]);
1905 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1907 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1908 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1912 fn channel_monitor_network_test() {
1913 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1914 // tests that ChannelMonitor is able to recover from various states.
1915 let chanmon_cfgs = create_chanmon_cfgs(5);
1916 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1917 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1918 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1920 // Create some initial channels
1921 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1922 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1923 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1924 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1926 // Rebalance the network a bit by relaying one payment through all the channels...
1927 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1928 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1929 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1930 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1932 // Simple case with no pending HTLCs:
1933 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1934 check_added_monitors!(nodes[1], 1);
1936 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1937 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1938 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1939 check_added_monitors!(nodes[0], 1);
1940 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1942 get_announce_close_broadcast_events(&nodes, 0, 1);
1943 assert_eq!(nodes[0].node.list_channels().len(), 0);
1944 assert_eq!(nodes[1].node.list_channels().len(), 1);
1946 // One pending HTLC is discarded by the force-close:
1947 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1949 // Simple case of one pending HTLC to HTLC-Timeout
1950 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1951 check_added_monitors!(nodes[1], 1);
1953 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1954 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1955 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1956 check_added_monitors!(nodes[2], 1);
1957 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1959 get_announce_close_broadcast_events(&nodes, 1, 2);
1960 assert_eq!(nodes[1].node.list_channels().len(), 0);
1961 assert_eq!(nodes[2].node.list_channels().len(), 1);
1963 macro_rules! claim_funds {
1964 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1966 assert!($node.node.claim_funds($preimage, &None, $amount));
1967 check_added_monitors!($node, 1);
1969 let events = $node.node.get_and_clear_pending_msg_events();
1970 assert_eq!(events.len(), 1);
1972 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1973 assert!(update_add_htlcs.is_empty());
1974 assert!(update_fail_htlcs.is_empty());
1975 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1977 _ => panic!("Unexpected event"),
1983 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1984 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1985 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1986 check_added_monitors!(nodes[2], 1);
1987 let node2_commitment_txid;
1989 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1990 node2_commitment_txid = node_txn[0].txid();
1992 // Claim the payment on nodes[3], giving it knowledge of the preimage
1993 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
1995 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1996 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1997 check_added_monitors!(nodes[3], 1);
1999 check_preimage_claim(&nodes[3], &node_txn);
2001 get_announce_close_broadcast_events(&nodes, 2, 3);
2002 assert_eq!(nodes[2].node.list_channels().len(), 0);
2003 assert_eq!(nodes[3].node.list_channels().len(), 1);
2005 { // Cheat and reset nodes[4]'s height to 1
2006 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2007 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2010 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2011 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2012 // One pending HTLC to time out:
2013 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2014 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2018 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2019 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2020 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2021 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2022 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2024 check_added_monitors!(nodes[3], 1);
2026 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2028 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2029 node_txn.retain(|tx| {
2030 if tx.input[0].previous_output.txid == node2_commitment_txid {
2036 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2038 // Claim the payment on nodes[4], giving it knowledge of the preimage
2039 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2041 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2043 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2044 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2045 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2046 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2049 check_added_monitors!(nodes[4], 1);
2050 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2052 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2053 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2055 check_preimage_claim(&nodes[4], &node_txn);
2057 get_announce_close_broadcast_events(&nodes, 3, 4);
2058 assert_eq!(nodes[3].node.list_channels().len(), 0);
2059 assert_eq!(nodes[4].node.list_channels().len(), 0);
2063 fn test_justice_tx() {
2064 // Test justice txn built on revoked HTLC-Success tx, against both sides
2065 let mut alice_config = UserConfig::default();
2066 alice_config.channel_options.announced_channel = true;
2067 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2068 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2069 let mut bob_config = UserConfig::default();
2070 bob_config.channel_options.announced_channel = true;
2071 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2072 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2073 let user_cfgs = [Some(alice_config), Some(bob_config)];
2074 let chanmon_cfgs = create_chanmon_cfgs(2);
2075 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2076 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2077 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2078 // Create some new channels:
2079 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2081 // A pending HTLC which will be revoked:
2082 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2083 // Get the will-be-revoked local txn from nodes[0]
2084 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2085 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2086 assert_eq!(revoked_local_txn[0].input.len(), 1);
2087 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2088 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2089 assert_eq!(revoked_local_txn[1].input.len(), 1);
2090 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2091 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2092 // Revoke the old state
2093 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2096 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2097 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2099 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2100 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2101 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2103 check_spends!(node_txn[0], revoked_local_txn[0]);
2104 node_txn.swap_remove(0);
2105 node_txn.truncate(1);
2107 check_added_monitors!(nodes[1], 1);
2108 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2110 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2111 // Verify broadcast of revoked HTLC-timeout
2112 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2113 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2114 check_added_monitors!(nodes[0], 1);
2115 // Broadcast revoked HTLC-timeout on node 1
2116 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2117 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2119 get_announce_close_broadcast_events(&nodes, 0, 1);
2121 assert_eq!(nodes[0].node.list_channels().len(), 0);
2122 assert_eq!(nodes[1].node.list_channels().len(), 0);
2124 // We test justice_tx build by A on B's revoked HTLC-Success tx
2125 // Create some new channels:
2126 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2128 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2132 // A pending HTLC which will be revoked:
2133 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2134 // Get the will-be-revoked local txn from B
2135 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2136 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2137 assert_eq!(revoked_local_txn[0].input.len(), 1);
2138 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2139 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2140 // Revoke the old state
2141 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2143 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2144 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2146 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2147 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2148 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2150 check_spends!(node_txn[0], revoked_local_txn[0]);
2151 node_txn.swap_remove(0);
2153 check_added_monitors!(nodes[0], 1);
2154 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2156 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2157 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2158 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2159 check_added_monitors!(nodes[1], 1);
2160 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2161 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2163 get_announce_close_broadcast_events(&nodes, 0, 1);
2164 assert_eq!(nodes[0].node.list_channels().len(), 0);
2165 assert_eq!(nodes[1].node.list_channels().len(), 0);
2169 fn revoked_output_claim() {
2170 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2171 // transaction is broadcast by its counterparty
2172 let chanmon_cfgs = create_chanmon_cfgs(2);
2173 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2174 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2175 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2176 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2177 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2178 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2179 assert_eq!(revoked_local_txn.len(), 1);
2180 // Only output is the full channel value back to nodes[0]:
2181 assert_eq!(revoked_local_txn[0].output.len(), 1);
2182 // Send a payment through, updating everyone's latest commitment txn
2183 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2185 // Inform nodes[1] that nodes[0] broadcast a stale tx
2186 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2187 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2188 check_added_monitors!(nodes[1], 1);
2189 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2190 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2192 check_spends!(node_txn[0], revoked_local_txn[0]);
2193 check_spends!(node_txn[1], chan_1.3);
2195 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2196 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2197 get_announce_close_broadcast_events(&nodes, 0, 1);
2198 check_added_monitors!(nodes[0], 1)
2202 fn claim_htlc_outputs_shared_tx() {
2203 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2204 let chanmon_cfgs = create_chanmon_cfgs(2);
2205 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2206 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2207 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2209 // Create some new channel:
2210 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2212 // Rebalance the network to generate htlc in the two directions
2213 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2214 // 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
2215 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2216 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2218 // Get the will-be-revoked local txn from node[0]
2219 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2220 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2221 assert_eq!(revoked_local_txn[0].input.len(), 1);
2222 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2223 assert_eq!(revoked_local_txn[1].input.len(), 1);
2224 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2225 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2226 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2228 //Revoke the old state
2229 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2232 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2233 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2234 check_added_monitors!(nodes[0], 1);
2235 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2236 check_added_monitors!(nodes[1], 1);
2237 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2238 expect_payment_failed!(nodes[1], payment_hash_2, true);
2240 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2241 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2243 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2244 check_spends!(node_txn[0], revoked_local_txn[0]);
2246 let mut witness_lens = BTreeSet::new();
2247 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2248 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2249 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2250 assert_eq!(witness_lens.len(), 3);
2251 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2252 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2253 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2255 // Next nodes[1] broadcasts its current local tx state:
2256 assert_eq!(node_txn[1].input.len(), 1);
2257 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2259 assert_eq!(node_txn[2].input.len(), 1);
2260 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2261 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2262 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2263 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2264 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2266 get_announce_close_broadcast_events(&nodes, 0, 1);
2267 assert_eq!(nodes[0].node.list_channels().len(), 0);
2268 assert_eq!(nodes[1].node.list_channels().len(), 0);
2272 fn claim_htlc_outputs_single_tx() {
2273 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2274 let chanmon_cfgs = create_chanmon_cfgs(2);
2275 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2276 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2277 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2279 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2281 // Rebalance the network to generate htlc in the two directions
2282 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2283 // 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
2284 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2285 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2286 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2288 // Get the will-be-revoked local txn from node[0]
2289 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2291 //Revoke the old state
2292 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2295 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2296 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2297 check_added_monitors!(nodes[0], 1);
2298 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2299 check_added_monitors!(nodes[1], 1);
2300 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2302 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2303 expect_payment_failed!(nodes[1], payment_hash_2, true);
2305 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2306 assert_eq!(node_txn.len(), 9);
2307 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2308 // ChannelManager: local commmitment + local HTLC-timeout (2)
2309 // 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)
2310 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2312 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2313 assert_eq!(node_txn[2].input.len(), 1);
2314 check_spends!(node_txn[2], chan_1.3);
2315 assert_eq!(node_txn[3].input.len(), 1);
2316 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2317 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2318 check_spends!(node_txn[3], node_txn[2]);
2320 // Justice transactions are indices 1-2-4
2321 assert_eq!(node_txn[0].input.len(), 1);
2322 assert_eq!(node_txn[1].input.len(), 1);
2323 assert_eq!(node_txn[4].input.len(), 1);
2325 check_spends!(node_txn[0], revoked_local_txn[0]);
2326 check_spends!(node_txn[1], revoked_local_txn[0]);
2327 check_spends!(node_txn[4], revoked_local_txn[0]);
2329 let mut witness_lens = BTreeSet::new();
2330 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2331 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2332 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2333 assert_eq!(witness_lens.len(), 3);
2334 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2335 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2336 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2338 get_announce_close_broadcast_events(&nodes, 0, 1);
2339 assert_eq!(nodes[0].node.list_channels().len(), 0);
2340 assert_eq!(nodes[1].node.list_channels().len(), 0);
2344 fn test_htlc_on_chain_success() {
2345 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2346 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2347 // broadcasting the right event to other nodes in payment path.
2348 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2349 // A --------------------> B ----------------------> C (preimage)
2350 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2351 // commitment transaction was broadcast.
2352 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2354 // B should be able to claim via preimage if A then broadcasts its local tx.
2355 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2356 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2357 // PaymentSent event).
2359 let chanmon_cfgs = create_chanmon_cfgs(3);
2360 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2361 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2362 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2364 // Create some initial channels
2365 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2366 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2368 // Rebalance the network a bit by relaying one payment through all the channels...
2369 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2370 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2372 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2373 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2374 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2376 // Broadcast legit commitment tx from C on B's chain
2377 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2378 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2379 assert_eq!(commitment_tx.len(), 1);
2380 check_spends!(commitment_tx[0], chan_2.3);
2381 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2382 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2383 check_added_monitors!(nodes[2], 2);
2384 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2385 assert!(updates.update_add_htlcs.is_empty());
2386 assert!(updates.update_fail_htlcs.is_empty());
2387 assert!(updates.update_fail_malformed_htlcs.is_empty());
2388 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2390 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2391 check_closed_broadcast!(nodes[2], false);
2392 check_added_monitors!(nodes[2], 1);
2393 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)
2394 assert_eq!(node_txn.len(), 5);
2395 assert_eq!(node_txn[0], node_txn[3]);
2396 assert_eq!(node_txn[1], node_txn[4]);
2397 assert_eq!(node_txn[2], commitment_tx[0]);
2398 check_spends!(node_txn[0], commitment_tx[0]);
2399 check_spends!(node_txn[1], commitment_tx[0]);
2400 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2401 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2402 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2403 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2404 assert_eq!(node_txn[0].lock_time, 0);
2405 assert_eq!(node_txn[1].lock_time, 0);
2407 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2408 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2410 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2411 assert_eq!(added_monitors.len(), 1);
2412 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2413 added_monitors.clear();
2415 let events = nodes[1].node.get_and_clear_pending_msg_events();
2417 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2418 assert_eq!(added_monitors.len(), 2);
2419 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2420 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2421 added_monitors.clear();
2423 assert_eq!(events.len(), 2);
2425 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2426 _ => panic!("Unexpected event"),
2429 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, .. } } => {
2430 assert!(update_add_htlcs.is_empty());
2431 assert!(update_fail_htlcs.is_empty());
2432 assert_eq!(update_fulfill_htlcs.len(), 1);
2433 assert!(update_fail_malformed_htlcs.is_empty());
2434 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2436 _ => panic!("Unexpected event"),
2438 macro_rules! check_tx_local_broadcast {
2439 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2440 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2441 assert_eq!(node_txn.len(), 5);
2442 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2443 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2444 check_spends!(node_txn[0], $commitment_tx);
2445 check_spends!(node_txn[1], $commitment_tx);
2446 assert_ne!(node_txn[0].lock_time, 0);
2447 assert_ne!(node_txn[1].lock_time, 0);
2449 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2450 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2451 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2452 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2454 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2455 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2456 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2457 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2459 check_spends!(node_txn[2], $chan_tx);
2460 check_spends!(node_txn[3], node_txn[2]);
2461 check_spends!(node_txn[4], node_txn[2]);
2462 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2463 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2464 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2465 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2466 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2467 assert_ne!(node_txn[3].lock_time, 0);
2468 assert_ne!(node_txn[4].lock_time, 0);
2472 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2473 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2474 // timeout-claim of the output that nodes[2] just claimed via success.
2475 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2477 // Broadcast legit commitment tx from A on B's chain
2478 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2479 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2480 check_spends!(commitment_tx[0], chan_1.3);
2481 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2482 check_closed_broadcast!(nodes[1], false);
2483 check_added_monitors!(nodes[1], 1);
2484 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2485 assert_eq!(node_txn.len(), 4);
2486 check_spends!(node_txn[0], commitment_tx[0]);
2487 assert_eq!(node_txn[0].input.len(), 2);
2488 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2489 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2490 assert_eq!(node_txn[0].lock_time, 0);
2491 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2492 check_spends!(node_txn[1], chan_1.3);
2493 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2494 check_spends!(node_txn[2], node_txn[1]);
2495 check_spends!(node_txn[3], node_txn[1]);
2496 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2497 // we already checked the same situation with A.
2499 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2500 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2501 check_closed_broadcast!(nodes[0], false);
2502 check_added_monitors!(nodes[0], 1);
2503 let events = nodes[0].node.get_and_clear_pending_events();
2504 assert_eq!(events.len(), 2);
2505 let mut first_claimed = false;
2506 for event in events {
2508 Event::PaymentSent { payment_preimage } => {
2509 if payment_preimage == our_payment_preimage {
2510 assert!(!first_claimed);
2511 first_claimed = true;
2513 assert_eq!(payment_preimage, our_payment_preimage_2);
2516 _ => panic!("Unexpected event"),
2519 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2523 fn test_htlc_on_chain_timeout() {
2524 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2525 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2526 // broadcasting the right event to other nodes in payment path.
2527 // A ------------------> B ----------------------> C (timeout)
2528 // B's commitment tx C's commitment tx
2530 // B's HTLC timeout tx B's timeout tx
2532 let chanmon_cfgs = create_chanmon_cfgs(3);
2533 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2534 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2535 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2537 // Create some intial channels
2538 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2539 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2541 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2542 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2543 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2545 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2546 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2548 // Broadcast legit commitment tx from C on B's chain
2549 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2550 check_spends!(commitment_tx[0], chan_2.3);
2551 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2552 check_added_monitors!(nodes[2], 0);
2553 expect_pending_htlcs_forwardable!(nodes[2]);
2554 check_added_monitors!(nodes[2], 1);
2556 let events = nodes[2].node.get_and_clear_pending_msg_events();
2557 assert_eq!(events.len(), 1);
2559 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, .. } } => {
2560 assert!(update_add_htlcs.is_empty());
2561 assert!(!update_fail_htlcs.is_empty());
2562 assert!(update_fulfill_htlcs.is_empty());
2563 assert!(update_fail_malformed_htlcs.is_empty());
2564 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2566 _ => panic!("Unexpected event"),
2568 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2569 check_closed_broadcast!(nodes[2], false);
2570 check_added_monitors!(nodes[2], 1);
2571 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2572 assert_eq!(node_txn.len(), 1);
2573 check_spends!(node_txn[0], chan_2.3);
2574 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2576 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2577 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2578 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2581 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2582 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2583 assert_eq!(node_txn[1], node_txn[3]);
2584 assert_eq!(node_txn[2], node_txn[4]);
2586 check_spends!(node_txn[0], commitment_tx[0]);
2587 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2589 check_spends!(node_txn[1], chan_2.3);
2590 check_spends!(node_txn[2], node_txn[1]);
2591 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2592 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2594 timeout_tx = node_txn[0].clone();
2598 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2599 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2600 check_added_monitors!(nodes[1], 1);
2601 check_closed_broadcast!(nodes[1], false);
2603 expect_pending_htlcs_forwardable!(nodes[1]);
2604 check_added_monitors!(nodes[1], 1);
2605 let events = nodes[1].node.get_and_clear_pending_msg_events();
2606 assert_eq!(events.len(), 1);
2608 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, .. } } => {
2609 assert!(update_add_htlcs.is_empty());
2610 assert!(!update_fail_htlcs.is_empty());
2611 assert!(update_fulfill_htlcs.is_empty());
2612 assert!(update_fail_malformed_htlcs.is_empty());
2613 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2615 _ => panic!("Unexpected event"),
2617 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
2618 assert_eq!(node_txn.len(), 0);
2620 // Broadcast legit commitment tx from B on A's chain
2621 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2622 check_spends!(commitment_tx[0], chan_1.3);
2624 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2625 check_closed_broadcast!(nodes[0], false);
2626 check_added_monitors!(nodes[0], 1);
2627 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2628 assert_eq!(node_txn.len(), 3);
2629 check_spends!(node_txn[0], commitment_tx[0]);
2630 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2631 check_spends!(node_txn[1], chan_1.3);
2632 check_spends!(node_txn[2], node_txn[1]);
2633 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2634 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2638 fn test_simple_commitment_revoked_fail_backward() {
2639 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2640 // and fail backward accordingly.
2642 let chanmon_cfgs = create_chanmon_cfgs(3);
2643 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2644 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2645 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2647 // Create some initial channels
2648 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2649 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2651 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2652 // Get the will-be-revoked local txn from nodes[2]
2653 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2654 // Revoke the old state
2655 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2657 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2659 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2660 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2661 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2662 check_added_monitors!(nodes[1], 1);
2663 check_closed_broadcast!(nodes[1], false);
2665 expect_pending_htlcs_forwardable!(nodes[1]);
2666 check_added_monitors!(nodes[1], 1);
2667 let events = nodes[1].node.get_and_clear_pending_msg_events();
2668 assert_eq!(events.len(), 1);
2670 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, .. } } => {
2671 assert!(update_add_htlcs.is_empty());
2672 assert_eq!(update_fail_htlcs.len(), 1);
2673 assert!(update_fulfill_htlcs.is_empty());
2674 assert!(update_fail_malformed_htlcs.is_empty());
2675 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2677 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2678 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2680 let events = nodes[0].node.get_and_clear_pending_msg_events();
2681 assert_eq!(events.len(), 1);
2683 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2684 _ => panic!("Unexpected event"),
2686 expect_payment_failed!(nodes[0], payment_hash, false);
2688 _ => panic!("Unexpected event"),
2692 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2693 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2694 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2695 // commitment transaction anymore.
2696 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2697 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2698 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2699 // technically disallowed and we should probably handle it reasonably.
2700 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2701 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2703 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2704 // commitment_signed (implying it will be in the latest remote commitment transaction).
2705 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2706 // and once they revoke the previous commitment transaction (allowing us to send a new
2707 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2708 let chanmon_cfgs = create_chanmon_cfgs(3);
2709 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2710 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2711 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2713 // Create some initial channels
2714 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2715 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2717 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2718 // Get the will-be-revoked local txn from nodes[2]
2719 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2720 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2721 // Revoke the old state
2722 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2724 let value = if use_dust {
2725 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2726 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2727 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2730 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2731 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2732 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2734 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2735 expect_pending_htlcs_forwardable!(nodes[2]);
2736 check_added_monitors!(nodes[2], 1);
2737 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2738 assert!(updates.update_add_htlcs.is_empty());
2739 assert!(updates.update_fulfill_htlcs.is_empty());
2740 assert!(updates.update_fail_malformed_htlcs.is_empty());
2741 assert_eq!(updates.update_fail_htlcs.len(), 1);
2742 assert!(updates.update_fee.is_none());
2743 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2744 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2745 // Drop the last RAA from 3 -> 2
2747 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2748 expect_pending_htlcs_forwardable!(nodes[2]);
2749 check_added_monitors!(nodes[2], 1);
2750 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2751 assert!(updates.update_add_htlcs.is_empty());
2752 assert!(updates.update_fulfill_htlcs.is_empty());
2753 assert!(updates.update_fail_malformed_htlcs.is_empty());
2754 assert_eq!(updates.update_fail_htlcs.len(), 1);
2755 assert!(updates.update_fee.is_none());
2756 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2757 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2758 check_added_monitors!(nodes[1], 1);
2759 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2760 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2761 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2762 check_added_monitors!(nodes[2], 1);
2764 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2765 expect_pending_htlcs_forwardable!(nodes[2]);
2766 check_added_monitors!(nodes[2], 1);
2767 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2768 assert!(updates.update_add_htlcs.is_empty());
2769 assert!(updates.update_fulfill_htlcs.is_empty());
2770 assert!(updates.update_fail_malformed_htlcs.is_empty());
2771 assert_eq!(updates.update_fail_htlcs.len(), 1);
2772 assert!(updates.update_fee.is_none());
2773 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2774 // At this point first_payment_hash has dropped out of the latest two commitment
2775 // transactions that nodes[1] is tracking...
2776 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2777 check_added_monitors!(nodes[1], 1);
2778 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2779 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2780 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2781 check_added_monitors!(nodes[2], 1);
2783 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2784 // on nodes[2]'s RAA.
2785 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2786 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2787 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2788 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2789 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2790 check_added_monitors!(nodes[1], 0);
2793 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2794 // One monitor for the new revocation preimage, no second on as we won't generate a new
2795 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2796 check_added_monitors!(nodes[1], 1);
2797 let events = nodes[1].node.get_and_clear_pending_events();
2798 assert_eq!(events.len(), 1);
2800 Event::PendingHTLCsForwardable { .. } => { },
2801 _ => panic!("Unexpected event"),
2803 // Deliberately don't process the pending fail-back so they all fail back at once after
2804 // block connection just like the !deliver_bs_raa case
2807 let mut failed_htlcs = HashSet::new();
2808 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2810 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2811 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2812 check_added_monitors!(nodes[1], 1);
2813 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2815 let events = nodes[1].node.get_and_clear_pending_events();
2816 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2818 Event::PaymentFailed { ref payment_hash, .. } => {
2819 assert_eq!(*payment_hash, fourth_payment_hash);
2821 _ => panic!("Unexpected event"),
2823 if !deliver_bs_raa {
2825 Event::PendingHTLCsForwardable { .. } => { },
2826 _ => panic!("Unexpected event"),
2829 nodes[1].node.process_pending_htlc_forwards();
2830 check_added_monitors!(nodes[1], 1);
2832 let events = nodes[1].node.get_and_clear_pending_msg_events();
2833 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2834 match events[if deliver_bs_raa { 1 } else { 0 }] {
2835 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2836 _ => panic!("Unexpected event"),
2840 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, .. } } => {
2841 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2842 assert_eq!(update_add_htlcs.len(), 1);
2843 assert!(update_fulfill_htlcs.is_empty());
2844 assert!(update_fail_htlcs.is_empty());
2845 assert!(update_fail_malformed_htlcs.is_empty());
2847 _ => panic!("Unexpected event"),
2850 match events[if deliver_bs_raa { 2 } else { 1 }] {
2851 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
2852 assert!(update_add_htlcs.is_empty());
2853 assert_eq!(update_fail_htlcs.len(), 3);
2854 assert!(update_fulfill_htlcs.is_empty());
2855 assert!(update_fail_malformed_htlcs.is_empty());
2856 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2858 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2859 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2860 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2862 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2864 let events = nodes[0].node.get_and_clear_pending_msg_events();
2865 // If we delivered B's RAA we got an unknown preimage error, not something
2866 // that we should update our routing table for.
2867 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2868 for event in events {
2870 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2871 _ => panic!("Unexpected event"),
2874 let events = nodes[0].node.get_and_clear_pending_events();
2875 assert_eq!(events.len(), 3);
2877 Event::PaymentFailed { ref payment_hash, .. } => {
2878 assert!(failed_htlcs.insert(payment_hash.0));
2880 _ => panic!("Unexpected event"),
2883 Event::PaymentFailed { ref payment_hash, .. } => {
2884 assert!(failed_htlcs.insert(payment_hash.0));
2886 _ => panic!("Unexpected event"),
2889 Event::PaymentFailed { ref payment_hash, .. } => {
2890 assert!(failed_htlcs.insert(payment_hash.0));
2892 _ => panic!("Unexpected event"),
2895 _ => panic!("Unexpected event"),
2898 assert!(failed_htlcs.contains(&first_payment_hash.0));
2899 assert!(failed_htlcs.contains(&second_payment_hash.0));
2900 assert!(failed_htlcs.contains(&third_payment_hash.0));
2904 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2905 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2906 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2907 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2908 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2912 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2913 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2914 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2915 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2916 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2920 fn fail_backward_pending_htlc_upon_channel_failure() {
2921 let chanmon_cfgs = create_chanmon_cfgs(2);
2922 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2923 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2924 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2925 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
2927 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2929 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2930 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV).unwrap();
2931 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2932 check_added_monitors!(nodes[0], 1);
2934 let payment_event = {
2935 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2936 assert_eq!(events.len(), 1);
2937 SendEvent::from_event(events.remove(0))
2939 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2940 assert_eq!(payment_event.msgs.len(), 1);
2943 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2944 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2946 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV).unwrap();
2947 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2948 check_added_monitors!(nodes[0], 0);
2950 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2953 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
2955 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV).unwrap();
2956 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
2958 let secp_ctx = Secp256k1::new();
2959 let session_priv = {
2960 let mut session_key = [0; 32];
2961 let mut rng = thread_rng();
2962 rng.fill_bytes(&mut session_key);
2963 SecretKey::from_slice(&session_key).expect("RNG is bad!")
2966 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2967 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
2968 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
2969 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
2971 // Send a 0-msat update_add_htlc to fail the channel.
2972 let update_add_htlc = msgs::UpdateAddHTLC {
2978 onion_routing_packet,
2980 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
2983 // Check that Alice fails backward the pending HTLC from the second payment.
2984 expect_payment_failed!(nodes[0], failed_payment_hash, true);
2985 check_closed_broadcast!(nodes[0], true);
2986 check_added_monitors!(nodes[0], 1);
2990 fn test_htlc_ignore_latest_remote_commitment() {
2991 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2992 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2993 let chanmon_cfgs = create_chanmon_cfgs(2);
2994 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2995 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2996 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2997 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2999 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3000 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3001 check_closed_broadcast!(nodes[0], false);
3002 check_added_monitors!(nodes[0], 1);
3004 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3005 assert_eq!(node_txn.len(), 2);
3007 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3008 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3009 check_closed_broadcast!(nodes[1], false);
3010 check_added_monitors!(nodes[1], 1);
3012 // Duplicate the block_connected call since this may happen due to other listeners
3013 // registering new transactions
3014 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3018 fn test_force_close_fail_back() {
3019 // Check which HTLCs are failed-backwards on channel force-closure
3020 let chanmon_cfgs = create_chanmon_cfgs(3);
3021 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3022 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3023 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3024 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3025 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3027 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3029 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3031 let mut payment_event = {
3032 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3033 check_added_monitors!(nodes[0], 1);
3035 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3036 assert_eq!(events.len(), 1);
3037 SendEvent::from_event(events.remove(0))
3040 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3041 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3043 expect_pending_htlcs_forwardable!(nodes[1]);
3045 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3046 assert_eq!(events_2.len(), 1);
3047 payment_event = SendEvent::from_event(events_2.remove(0));
3048 assert_eq!(payment_event.msgs.len(), 1);
3050 check_added_monitors!(nodes[1], 1);
3051 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3052 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3053 check_added_monitors!(nodes[2], 1);
3054 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3056 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3057 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3058 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3060 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3061 check_closed_broadcast!(nodes[2], false);
3062 check_added_monitors!(nodes[2], 1);
3064 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3065 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3066 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3067 // back to nodes[1] upon timeout otherwise.
3068 assert_eq!(node_txn.len(), 1);
3072 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3073 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3075 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3076 check_closed_broadcast!(nodes[1], false);
3077 check_added_monitors!(nodes[1], 1);
3079 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3081 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3082 monitors.get_mut(&OutPoint::new(Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3083 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3085 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3086 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3087 assert_eq!(node_txn.len(), 1);
3088 assert_eq!(node_txn[0].input.len(), 1);
3089 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3090 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3091 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3093 check_spends!(node_txn[0], tx);
3097 fn test_unconf_chan() {
3098 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3099 let chanmon_cfgs = create_chanmon_cfgs(2);
3100 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3101 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3102 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3103 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3105 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3106 assert_eq!(channel_state.by_id.len(), 1);
3107 assert_eq!(channel_state.short_to_id.len(), 1);
3108 mem::drop(channel_state);
3110 let mut headers = Vec::new();
3111 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3112 headers.push(header.clone());
3114 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3115 headers.push(header.clone());
3117 let mut height = 99;
3118 while !headers.is_empty() {
3119 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3122 check_closed_broadcast!(nodes[0], false);
3123 check_added_monitors!(nodes[0], 1);
3124 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3125 assert_eq!(channel_state.by_id.len(), 0);
3126 assert_eq!(channel_state.short_to_id.len(), 0);
3130 fn test_simple_peer_disconnect() {
3131 // Test that we can reconnect when there are no lost messages
3132 let chanmon_cfgs = create_chanmon_cfgs(3);
3133 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3134 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3135 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3136 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3137 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3139 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3140 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3141 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3143 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3144 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3145 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3146 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3148 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3149 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3150 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3152 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3153 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3154 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3155 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3157 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3158 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3160 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3161 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3163 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3165 let events = nodes[0].node.get_and_clear_pending_events();
3166 assert_eq!(events.len(), 2);
3168 Event::PaymentSent { payment_preimage } => {
3169 assert_eq!(payment_preimage, payment_preimage_3);
3171 _ => panic!("Unexpected event"),
3174 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3175 assert_eq!(payment_hash, payment_hash_5);
3176 assert!(rejected_by_dest);
3178 _ => panic!("Unexpected event"),
3182 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3183 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3186 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3187 // Test that we can reconnect when in-flight HTLC updates get dropped
3188 let chanmon_cfgs = create_chanmon_cfgs(2);
3189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3190 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3191 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3192 if messages_delivered == 0 {
3193 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3194 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3196 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3199 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3200 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3202 let payment_event = {
3203 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3204 check_added_monitors!(nodes[0], 1);
3206 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3207 assert_eq!(events.len(), 1);
3208 SendEvent::from_event(events.remove(0))
3210 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3212 if messages_delivered < 2 {
3213 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3215 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3216 if messages_delivered >= 3 {
3217 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3218 check_added_monitors!(nodes[1], 1);
3219 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3221 if messages_delivered >= 4 {
3222 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3223 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3224 check_added_monitors!(nodes[0], 1);
3226 if messages_delivered >= 5 {
3227 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3228 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3229 // No commitment_signed so get_event_msg's assert(len == 1) passes
3230 check_added_monitors!(nodes[0], 1);
3232 if messages_delivered >= 6 {
3233 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3234 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3235 check_added_monitors!(nodes[1], 1);
3242 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3243 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3244 if messages_delivered < 3 {
3245 // Even if the funding_locked messages get exchanged, as long as nothing further was
3246 // received on either side, both sides will need to resend them.
3247 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3248 } else if messages_delivered == 3 {
3249 // nodes[0] still wants its RAA + commitment_signed
3250 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3251 } else if messages_delivered == 4 {
3252 // nodes[0] still wants its commitment_signed
3253 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3254 } else if messages_delivered == 5 {
3255 // nodes[1] still wants its final RAA
3256 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3257 } else if messages_delivered == 6 {
3258 // Everything was delivered...
3259 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3262 let events_1 = nodes[1].node.get_and_clear_pending_events();
3263 assert_eq!(events_1.len(), 1);
3265 Event::PendingHTLCsForwardable { .. } => { },
3266 _ => panic!("Unexpected event"),
3269 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3270 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3271 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3273 nodes[1].node.process_pending_htlc_forwards();
3275 let events_2 = nodes[1].node.get_and_clear_pending_events();
3276 assert_eq!(events_2.len(), 1);
3278 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3279 assert_eq!(payment_hash_1, *payment_hash);
3280 assert_eq!(*payment_secret, None);
3281 assert_eq!(amt, 1000000);
3283 _ => panic!("Unexpected event"),
3286 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3287 check_added_monitors!(nodes[1], 1);
3289 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3290 assert_eq!(events_3.len(), 1);
3291 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3292 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3293 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3294 assert!(updates.update_add_htlcs.is_empty());
3295 assert!(updates.update_fail_htlcs.is_empty());
3296 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3297 assert!(updates.update_fail_malformed_htlcs.is_empty());
3298 assert!(updates.update_fee.is_none());
3299 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3301 _ => panic!("Unexpected event"),
3304 if messages_delivered >= 1 {
3305 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3307 let events_4 = nodes[0].node.get_and_clear_pending_events();
3308 assert_eq!(events_4.len(), 1);
3310 Event::PaymentSent { ref payment_preimage } => {
3311 assert_eq!(payment_preimage_1, *payment_preimage);
3313 _ => panic!("Unexpected event"),
3316 if messages_delivered >= 2 {
3317 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3318 check_added_monitors!(nodes[0], 1);
3319 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3321 if messages_delivered >= 3 {
3322 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3323 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3324 check_added_monitors!(nodes[1], 1);
3326 if messages_delivered >= 4 {
3327 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3328 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3329 // No commitment_signed so get_event_msg's assert(len == 1) passes
3330 check_added_monitors!(nodes[1], 1);
3332 if messages_delivered >= 5 {
3333 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3334 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3335 check_added_monitors!(nodes[0], 1);
3342 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3343 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3344 if messages_delivered < 2 {
3345 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3346 //TODO: Deduplicate PaymentSent events, then enable this if:
3347 //if messages_delivered < 1 {
3348 let events_4 = nodes[0].node.get_and_clear_pending_events();
3349 assert_eq!(events_4.len(), 1);
3351 Event::PaymentSent { ref payment_preimage } => {
3352 assert_eq!(payment_preimage_1, *payment_preimage);
3354 _ => panic!("Unexpected event"),
3357 } else if messages_delivered == 2 {
3358 // nodes[0] still wants its RAA + commitment_signed
3359 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3360 } else if messages_delivered == 3 {
3361 // nodes[0] still wants its commitment_signed
3362 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3363 } else if messages_delivered == 4 {
3364 // nodes[1] still wants its final RAA
3365 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3366 } else if messages_delivered == 5 {
3367 // Everything was delivered...
3368 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3371 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3372 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3373 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3375 // Channel should still work fine...
3376 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3377 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3381 fn test_drop_messages_peer_disconnect_a() {
3382 do_test_drop_messages_peer_disconnect(0);
3383 do_test_drop_messages_peer_disconnect(1);
3384 do_test_drop_messages_peer_disconnect(2);
3385 do_test_drop_messages_peer_disconnect(3);
3389 fn test_drop_messages_peer_disconnect_b() {
3390 do_test_drop_messages_peer_disconnect(4);
3391 do_test_drop_messages_peer_disconnect(5);
3392 do_test_drop_messages_peer_disconnect(6);
3396 fn test_funding_peer_disconnect() {
3397 // Test that we can lock in our funding tx while disconnected
3398 let chanmon_cfgs = create_chanmon_cfgs(2);
3399 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3400 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3401 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3402 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3404 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3405 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3407 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3408 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3409 assert_eq!(events_1.len(), 1);
3411 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3412 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3414 _ => panic!("Unexpected event"),
3417 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3419 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3420 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3422 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3423 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3424 assert_eq!(events_2.len(), 2);
3425 let funding_locked = match events_2[0] {
3426 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3427 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3430 _ => panic!("Unexpected event"),
3432 let bs_announcement_sigs = match events_2[1] {
3433 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3434 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3437 _ => panic!("Unexpected event"),
3440 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3442 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3443 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3444 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3445 assert_eq!(events_3.len(), 2);
3446 let as_announcement_sigs = match events_3[0] {
3447 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3448 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3451 _ => panic!("Unexpected event"),
3453 let (as_announcement, as_update) = match events_3[1] {
3454 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3455 (msg.clone(), update_msg.clone())
3457 _ => panic!("Unexpected event"),
3460 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3461 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3462 assert_eq!(events_4.len(), 1);
3463 let (_, bs_update) = match events_4[0] {
3464 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3465 (msg.clone(), update_msg.clone())
3467 _ => panic!("Unexpected event"),
3470 nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3471 nodes[0].router.handle_channel_update(&bs_update).unwrap();
3472 nodes[0].router.handle_channel_update(&as_update).unwrap();
3474 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3475 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3476 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3480 fn test_drop_messages_peer_disconnect_dual_htlc() {
3481 // Test that we can handle reconnecting when both sides of a channel have pending
3482 // commitment_updates when we disconnect.
3483 let chanmon_cfgs = create_chanmon_cfgs(2);
3484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3486 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3487 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3489 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3491 // Now try to send a second payment which will fail to send
3492 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3493 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3495 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3496 check_added_monitors!(nodes[0], 1);
3498 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3499 assert_eq!(events_1.len(), 1);
3501 MessageSendEvent::UpdateHTLCs { .. } => {},
3502 _ => panic!("Unexpected event"),
3505 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3506 check_added_monitors!(nodes[1], 1);
3508 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3509 assert_eq!(events_2.len(), 1);
3511 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 } } => {
3512 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3513 assert!(update_add_htlcs.is_empty());
3514 assert_eq!(update_fulfill_htlcs.len(), 1);
3515 assert!(update_fail_htlcs.is_empty());
3516 assert!(update_fail_malformed_htlcs.is_empty());
3517 assert!(update_fee.is_none());
3519 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3520 let events_3 = nodes[0].node.get_and_clear_pending_events();
3521 assert_eq!(events_3.len(), 1);
3523 Event::PaymentSent { ref payment_preimage } => {
3524 assert_eq!(*payment_preimage, payment_preimage_1);
3526 _ => panic!("Unexpected event"),
3529 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3530 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3531 // No commitment_signed so get_event_msg's assert(len == 1) passes
3532 check_added_monitors!(nodes[0], 1);
3534 _ => panic!("Unexpected event"),
3537 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3538 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3540 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3541 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3542 assert_eq!(reestablish_1.len(), 1);
3543 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3544 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3545 assert_eq!(reestablish_2.len(), 1);
3547 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3548 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3549 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3550 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3552 assert!(as_resp.0.is_none());
3553 assert!(bs_resp.0.is_none());
3555 assert!(bs_resp.1.is_none());
3556 assert!(bs_resp.2.is_none());
3558 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3560 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3561 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3562 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3563 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3564 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3565 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3566 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3567 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3568 // No commitment_signed so get_event_msg's assert(len == 1) passes
3569 check_added_monitors!(nodes[1], 1);
3571 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3572 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3573 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3574 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3575 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3576 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3577 assert!(bs_second_commitment_signed.update_fee.is_none());
3578 check_added_monitors!(nodes[1], 1);
3580 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3581 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3582 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3583 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3584 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3585 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3586 assert!(as_commitment_signed.update_fee.is_none());
3587 check_added_monitors!(nodes[0], 1);
3589 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3590 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3591 // No commitment_signed so get_event_msg's assert(len == 1) passes
3592 check_added_monitors!(nodes[0], 1);
3594 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3595 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3596 // No commitment_signed so get_event_msg's assert(len == 1) passes
3597 check_added_monitors!(nodes[1], 1);
3599 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3600 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3601 check_added_monitors!(nodes[1], 1);
3603 expect_pending_htlcs_forwardable!(nodes[1]);
3605 let events_5 = nodes[1].node.get_and_clear_pending_events();
3606 assert_eq!(events_5.len(), 1);
3608 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3609 assert_eq!(payment_hash_2, *payment_hash);
3610 assert_eq!(*payment_secret, None);
3612 _ => panic!("Unexpected event"),
3615 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3616 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3617 check_added_monitors!(nodes[0], 1);
3619 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3622 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3623 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3624 // to avoid our counterparty failing the channel.
3625 let chanmon_cfgs = create_chanmon_cfgs(2);
3626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3632 let our_payment_hash = if send_partial_mpp {
3633 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
3634 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3635 let payment_secret = PaymentSecret([0xdb; 32]);
3636 // Use the utility function send_payment_along_path to send the payment with MPP data which
3637 // indicates there are more HTLCs coming.
3638 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3639 check_added_monitors!(nodes[0], 1);
3640 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3641 assert_eq!(events.len(), 1);
3642 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3643 // hop should *not* yet generate any PaymentReceived event(s).
3644 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3647 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3650 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3651 nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3652 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3653 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3654 header.prev_blockhash = header.bitcoin_hash();
3655 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3656 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3659 expect_pending_htlcs_forwardable!(nodes[1]);
3661 check_added_monitors!(nodes[1], 1);
3662 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3663 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3664 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3665 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3666 assert!(htlc_timeout_updates.update_fee.is_none());
3668 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3669 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3670 // 100_000 msat as u64, followed by a height of 123 as u32
3671 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3672 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3673 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3677 fn test_htlc_timeout() {
3678 do_test_htlc_timeout(true);
3679 do_test_htlc_timeout(false);
3682 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3683 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3684 let chanmon_cfgs = create_chanmon_cfgs(3);
3685 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3686 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3687 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3688 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3689 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3691 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3692 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
3693 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3694 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
3695 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3696 check_added_monitors!(nodes[1], 1);
3698 // Now attempt to route a second payment, which should be placed in the holding cell
3699 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3701 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
3702 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
3703 check_added_monitors!(nodes[0], 1);
3704 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3705 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3706 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3707 expect_pending_htlcs_forwardable!(nodes[1]);
3708 check_added_monitors!(nodes[1], 0);
3710 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
3711 check_added_monitors!(nodes[1], 0);
3714 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3715 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3716 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3717 header.prev_blockhash = header.bitcoin_hash();
3718 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3721 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3722 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3724 header.prev_blockhash = header.bitcoin_hash();
3725 nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
3728 expect_pending_htlcs_forwardable!(nodes[1]);
3729 check_added_monitors!(nodes[1], 1);
3730 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3731 assert_eq!(fail_commit.len(), 1);
3732 match fail_commit[0] {
3733 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3734 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3735 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3737 _ => unreachable!(),
3739 expect_payment_failed!(nodes[0], second_payment_hash, false);
3740 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
3742 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
3743 _ => panic!("Unexpected event"),
3746 panic!("Unexpected event");
3749 expect_payment_failed!(nodes[1], second_payment_hash, true);
3754 fn test_holding_cell_htlc_add_timeouts() {
3755 do_test_holding_cell_htlc_add_timeouts(false);
3756 do_test_holding_cell_htlc_add_timeouts(true);
3760 fn test_invalid_channel_announcement() {
3761 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3762 let secp_ctx = Secp256k1::new();
3763 let chanmon_cfgs = create_chanmon_cfgs(2);
3764 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3765 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3766 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3768 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
3770 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3771 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3772 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3773 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3775 nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3777 let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3778 let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3780 let as_network_key = nodes[0].node.get_our_node_id();
3781 let bs_network_key = nodes[1].node.get_our_node_id();
3783 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3785 let mut chan_announcement;
3787 macro_rules! dummy_unsigned_msg {
3789 msgs::UnsignedChannelAnnouncement {
3790 features: ChannelFeatures::known(),
3791 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3792 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3793 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3794 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3795 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3796 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3797 excess_data: Vec::new(),
3802 macro_rules! sign_msg {
3803 ($unsigned_msg: expr) => {
3804 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3805 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3806 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3807 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3808 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3809 chan_announcement = msgs::ChannelAnnouncement {
3810 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3811 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3812 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3813 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3814 contents: $unsigned_msg
3819 let unsigned_msg = dummy_unsigned_msg!();
3820 sign_msg!(unsigned_msg);
3821 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3822 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3824 // Configured with Network::Testnet
3825 let mut unsigned_msg = dummy_unsigned_msg!();
3826 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3827 sign_msg!(unsigned_msg);
3828 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3830 let mut unsigned_msg = dummy_unsigned_msg!();
3831 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
3832 sign_msg!(unsigned_msg);
3833 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3837 fn test_no_txn_manager_serialize_deserialize() {
3838 let chanmon_cfgs = create_chanmon_cfgs(2);
3839 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3840 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3841 let fee_estimator: test_utils::TestFeeEstimator;
3842 let new_chan_monitor: test_utils::TestChannelMonitor;
3843 let keys_manager: test_utils::TestKeysInterface;
3844 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3845 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3847 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3849 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3851 let nodes_0_serialized = nodes[0].node.encode();
3852 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3853 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3855 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3856 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3857 nodes[0].chan_monitor = &new_chan_monitor;
3858 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3859 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3860 assert!(chan_0_monitor_read.is_empty());
3862 let mut nodes_0_read = &nodes_0_serialized[..];
3863 let config = UserConfig::default();
3864 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3865 let (_, nodes_0_deserialized_tmp) = {
3866 let mut channel_monitors = HashMap::new();
3867 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3868 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3869 default_config: config,
3870 keys_manager: &keys_manager,
3871 fee_estimator: &fee_estimator,
3872 monitor: nodes[0].chan_monitor,
3873 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3874 logger: Arc::new(test_utils::TestLogger::new()),
3875 channel_monitors: &mut channel_monitors,
3878 nodes_0_deserialized = nodes_0_deserialized_tmp;
3879 assert!(nodes_0_read.is_empty());
3881 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3882 nodes[0].node = &nodes_0_deserialized;
3883 nodes[0].block_notifier.register_listener(nodes[0].node);
3884 assert_eq!(nodes[0].node.list_channels().len(), 1);
3885 check_added_monitors!(nodes[0], 1);
3887 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3888 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3889 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3890 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3892 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3893 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3894 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3895 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3897 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3898 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3899 for node in nodes.iter() {
3900 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3901 node.router.handle_channel_update(&as_update).unwrap();
3902 node.router.handle_channel_update(&bs_update).unwrap();
3905 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3909 fn test_simple_manager_serialize_deserialize() {
3910 let chanmon_cfgs = create_chanmon_cfgs(2);
3911 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3912 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3913 let fee_estimator: test_utils::TestFeeEstimator;
3914 let new_chan_monitor: test_utils::TestChannelMonitor;
3915 let keys_manager: test_utils::TestKeysInterface;
3916 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3917 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3918 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3920 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3921 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3923 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3925 let nodes_0_serialized = nodes[0].node.encode();
3926 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3927 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3929 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3930 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3931 nodes[0].chan_monitor = &new_chan_monitor;
3932 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3933 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3934 assert!(chan_0_monitor_read.is_empty());
3936 let mut nodes_0_read = &nodes_0_serialized[..];
3937 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3938 let (_, nodes_0_deserialized_tmp) = {
3939 let mut channel_monitors = HashMap::new();
3940 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3941 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3942 default_config: UserConfig::default(),
3943 keys_manager: &keys_manager,
3944 fee_estimator: &fee_estimator,
3945 monitor: nodes[0].chan_monitor,
3946 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3947 logger: Arc::new(test_utils::TestLogger::new()),
3948 channel_monitors: &mut channel_monitors,
3951 nodes_0_deserialized = nodes_0_deserialized_tmp;
3952 assert!(nodes_0_read.is_empty());
3954 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3955 nodes[0].node = &nodes_0_deserialized;
3956 check_added_monitors!(nodes[0], 1);
3958 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3960 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3961 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3965 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3966 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3967 let chanmon_cfgs = create_chanmon_cfgs(4);
3968 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3969 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3970 let fee_estimator: test_utils::TestFeeEstimator;
3971 let new_chan_monitor: test_utils::TestChannelMonitor;
3972 let keys_manager: test_utils::TestKeysInterface;
3973 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3974 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3975 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3976 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
3977 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
3979 let mut node_0_stale_monitors_serialized = Vec::new();
3980 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3981 let mut writer = test_utils::TestVecWriter(Vec::new());
3982 monitor.1.write_for_disk(&mut writer).unwrap();
3983 node_0_stale_monitors_serialized.push(writer.0);
3986 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3988 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3989 let nodes_0_serialized = nodes[0].node.encode();
3991 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3992 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3993 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3994 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3996 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3998 let mut node_0_monitors_serialized = Vec::new();
3999 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4000 let mut writer = test_utils::TestVecWriter(Vec::new());
4001 monitor.1.write_for_disk(&mut writer).unwrap();
4002 node_0_monitors_serialized.push(writer.0);
4005 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4006 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
4007 nodes[0].chan_monitor = &new_chan_monitor;
4009 let mut node_0_stale_monitors = Vec::new();
4010 for serialized in node_0_stale_monitors_serialized.iter() {
4011 let mut read = &serialized[..];
4012 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
4013 assert!(read.is_empty());
4014 node_0_stale_monitors.push(monitor);
4017 let mut node_0_monitors = Vec::new();
4018 for serialized in node_0_monitors_serialized.iter() {
4019 let mut read = &serialized[..];
4020 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
4021 assert!(read.is_empty());
4022 node_0_monitors.push(monitor);
4025 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
4027 let mut nodes_0_read = &nodes_0_serialized[..];
4028 if let Err(msgs::DecodeError::InvalidValue) =
4029 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4030 default_config: UserConfig::default(),
4031 keys_manager: &keys_manager,
4032 fee_estimator: &fee_estimator,
4033 monitor: nodes[0].chan_monitor,
4034 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4035 logger: Arc::new(test_utils::TestLogger::new()),
4036 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4038 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4041 let mut nodes_0_read = &nodes_0_serialized[..];
4042 let (_, nodes_0_deserialized_tmp) =
4043 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4044 default_config: UserConfig::default(),
4045 keys_manager: &keys_manager,
4046 fee_estimator: &fee_estimator,
4047 monitor: nodes[0].chan_monitor,
4048 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4049 logger: Arc::new(test_utils::TestLogger::new()),
4050 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4052 nodes_0_deserialized = nodes_0_deserialized_tmp;
4053 assert!(nodes_0_read.is_empty());
4055 { // Channel close should result in a commitment tx and an HTLC tx
4056 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4057 assert_eq!(txn.len(), 2);
4058 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4059 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4062 for monitor in node_0_monitors.drain(..) {
4063 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
4064 check_added_monitors!(nodes[0], 1);
4066 nodes[0].node = &nodes_0_deserialized;
4068 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4069 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4070 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4071 //... and we can even still claim the payment!
4072 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4074 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4075 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4076 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4077 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4078 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4079 assert_eq!(msg_events.len(), 1);
4080 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4082 &ErrorAction::SendErrorMessage { ref msg } => {
4083 assert_eq!(msg.channel_id, channel_id);
4085 _ => panic!("Unexpected event!"),
4090 macro_rules! check_spendable_outputs {
4091 ($node: expr, $der_idx: expr) => {
4093 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4094 let mut txn = Vec::new();
4095 for event in events {
4097 Event::SpendableOutputs { ref outputs } => {
4098 for outp in outputs {
4100 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4102 previous_output: outpoint.clone(),
4103 script_sig: Script::new(),
4105 witness: Vec::new(),
4108 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4109 value: output.value,
4111 let mut spend_tx = Transaction {
4117 let secp_ctx = Secp256k1::new();
4118 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4119 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4120 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4121 let remotesig = secp_ctx.sign(&sighash, key);
4122 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4123 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4124 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4127 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
4129 previous_output: outpoint.clone(),
4130 script_sig: Script::new(),
4131 sequence: *to_self_delay as u32,
4132 witness: Vec::new(),
4135 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4136 value: output.value,
4138 let mut spend_tx = Transaction {
4144 let secp_ctx = Secp256k1::new();
4145 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
4146 let local_delaysig = secp_ctx.sign(&sighash, key);
4147 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
4148 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4149 spend_tx.input[0].witness.push(vec!());
4150 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4153 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4154 let secp_ctx = Secp256k1::new();
4156 previous_output: outpoint.clone(),
4157 script_sig: Script::new(),
4159 witness: Vec::new(),
4162 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4163 value: output.value,
4165 let mut spend_tx = Transaction {
4169 output: vec![outp.clone()],
4172 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4174 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4176 Err(_) => panic!("Your RNG is busted"),
4179 Err(_) => panic!("Your rng is busted"),
4182 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4183 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4184 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4185 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4186 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4187 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4188 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4194 _ => panic!("Unexpected event"),
4203 fn test_claim_sizeable_push_msat() {
4204 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4205 let chanmon_cfgs = create_chanmon_cfgs(2);
4206 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4207 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4208 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4210 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4211 nodes[1].node.force_close_channel(&chan.2);
4212 check_closed_broadcast!(nodes[1], false);
4213 check_added_monitors!(nodes[1], 1);
4214 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4215 assert_eq!(node_txn.len(), 1);
4216 check_spends!(node_txn[0], chan.3);
4217 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
4219 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4220 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4221 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4223 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4224 assert_eq!(spend_txn.len(), 1);
4225 check_spends!(spend_txn[0], node_txn[0]);
4229 fn test_claim_on_remote_sizeable_push_msat() {
4230 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4231 // to_remote output is encumbered by a P2WPKH
4232 let chanmon_cfgs = create_chanmon_cfgs(2);
4233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4237 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4238 nodes[0].node.force_close_channel(&chan.2);
4239 check_closed_broadcast!(nodes[0], false);
4240 check_added_monitors!(nodes[0], 1);
4242 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4243 assert_eq!(node_txn.len(), 1);
4244 check_spends!(node_txn[0], chan.3);
4245 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
4247 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4248 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4249 check_closed_broadcast!(nodes[1], false);
4250 check_added_monitors!(nodes[1], 1);
4251 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4253 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4254 assert_eq!(spend_txn.len(), 2);
4255 assert_eq!(spend_txn[0], spend_txn[1]);
4256 check_spends!(spend_txn[0], node_txn[0]);
4260 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4261 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4262 // to_remote output is encumbered by a P2WPKH
4264 let chanmon_cfgs = create_chanmon_cfgs(2);
4265 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4266 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4267 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4269 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4270 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4271 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4272 assert_eq!(revoked_local_txn[0].input.len(), 1);
4273 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4275 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4276 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4277 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4278 check_closed_broadcast!(nodes[1], false);
4279 check_added_monitors!(nodes[1], 1);
4281 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4282 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4283 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4284 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4286 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4287 assert_eq!(spend_txn.len(), 3);
4288 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4289 check_spends!(spend_txn[0], revoked_local_txn[0]);
4290 check_spends!(spend_txn[2], node_txn[0]);
4294 fn test_static_spendable_outputs_preimage_tx() {
4295 let chanmon_cfgs = create_chanmon_cfgs(2);
4296 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4297 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4298 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4300 // Create some initial channels
4301 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4303 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4305 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4306 assert_eq!(commitment_tx[0].input.len(), 1);
4307 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4309 // Settle A's commitment tx on B's chain
4310 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4311 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4312 check_added_monitors!(nodes[1], 1);
4313 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4314 check_added_monitors!(nodes[1], 1);
4315 let events = nodes[1].node.get_and_clear_pending_msg_events();
4317 MessageSendEvent::UpdateHTLCs { .. } => {},
4318 _ => panic!("Unexpected event"),
4321 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4322 _ => panic!("Unexepected event"),
4325 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4326 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4327 assert_eq!(node_txn.len(), 3);
4328 check_spends!(node_txn[0], commitment_tx[0]);
4329 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4330 check_spends!(node_txn[1], chan_1.3);
4331 check_spends!(node_txn[2], node_txn[1]);
4333 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4334 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4335 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4337 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4338 assert_eq!(spend_txn.len(), 1);
4339 check_spends!(spend_txn[0], node_txn[0]);
4343 fn test_static_spendable_outputs_timeout_tx() {
4344 let chanmon_cfgs = create_chanmon_cfgs(2);
4345 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4346 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4347 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4349 // Create some initial channels
4350 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4352 // Rebalance the network a bit by relaying one payment through all the channels ...
4353 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4355 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4357 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4358 assert_eq!(commitment_tx[0].input.len(), 1);
4359 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4361 // Settle A's commitment tx on B' chain
4362 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4363 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4364 check_added_monitors!(nodes[1], 1);
4365 let events = nodes[1].node.get_and_clear_pending_msg_events();
4367 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4368 _ => panic!("Unexpected event"),
4371 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4372 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4373 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4374 check_spends!(node_txn[0], commitment_tx[0].clone());
4375 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4376 check_spends!(node_txn[1], chan_1.3.clone());
4377 check_spends!(node_txn[2], node_txn[1]);
4379 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4380 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4381 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4382 expect_payment_failed!(nodes[1], our_payment_hash, true);
4384 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4385 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4386 check_spends!(spend_txn[2], node_txn[0].clone());
4390 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4391 let chanmon_cfgs = create_chanmon_cfgs(2);
4392 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4393 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4394 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4396 // Create some initial channels
4397 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4399 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4400 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4401 assert_eq!(revoked_local_txn[0].input.len(), 1);
4402 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4404 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4406 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4407 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4408 check_closed_broadcast!(nodes[1], false);
4409 check_added_monitors!(nodes[1], 1);
4411 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4412 assert_eq!(node_txn.len(), 2);
4413 assert_eq!(node_txn[0].input.len(), 2);
4414 check_spends!(node_txn[0], revoked_local_txn[0]);
4416 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4417 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4418 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4420 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4421 assert_eq!(spend_txn.len(), 1);
4422 check_spends!(spend_txn[0], node_txn[0]);
4426 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4427 let chanmon_cfgs = create_chanmon_cfgs(2);
4428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4432 // Create some initial channels
4433 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4435 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4436 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4437 assert_eq!(revoked_local_txn[0].input.len(), 1);
4438 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4440 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4442 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4443 // A will generate HTLC-Timeout from revoked commitment tx
4444 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4445 check_closed_broadcast!(nodes[0], false);
4446 check_added_monitors!(nodes[0], 1);
4448 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4449 assert_eq!(revoked_htlc_txn.len(), 2);
4450 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4451 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4452 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4453 check_spends!(revoked_htlc_txn[1], chan_1.3);
4455 // B will generate justice tx from A's revoked commitment/HTLC tx
4456 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4457 check_closed_broadcast!(nodes[1], false);
4458 check_added_monitors!(nodes[1], 1);
4460 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4461 assert_eq!(node_txn.len(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
4462 assert_eq!(node_txn[0].input.len(), 2);
4463 check_spends!(node_txn[0], revoked_local_txn[0]);
4464 check_spends!(node_txn[1], chan_1.3);
4465 assert_eq!(node_txn[2].input.len(), 1);
4466 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4467 assert_eq!(node_txn[3].input.len(), 1);
4468 check_spends!(node_txn[3], revoked_local_txn[0]);
4470 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4471 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4472 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4474 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4475 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4476 assert_eq!(spend_txn.len(), 2);
4477 check_spends!(spend_txn[0], node_txn[0]);
4478 check_spends!(spend_txn[1], node_txn[2]);
4482 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4483 let chanmon_cfgs = create_chanmon_cfgs(2);
4484 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4485 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4486 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4488 // Create some initial channels
4489 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4491 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4492 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4493 assert_eq!(revoked_local_txn[0].input.len(), 1);
4494 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4496 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4498 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4499 // B will generate HTLC-Success from revoked commitment tx
4500 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4501 check_closed_broadcast!(nodes[1], false);
4502 check_added_monitors!(nodes[1], 1);
4503 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4505 assert_eq!(revoked_htlc_txn.len(), 2);
4506 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4507 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4508 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4510 // A will generate justice tx from B's revoked commitment/HTLC tx
4511 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4512 check_closed_broadcast!(nodes[0], false);
4513 check_added_monitors!(nodes[0], 1);
4515 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4516 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4517 assert_eq!(node_txn[2].input.len(), 1);
4518 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4520 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4521 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4522 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4524 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4525 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4526 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4527 assert_eq!(spend_txn[0], spend_txn[1]);
4528 assert_eq!(spend_txn[0], spend_txn[2]);
4529 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4530 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4531 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4535 fn test_onchain_to_onchain_claim() {
4536 // Test that in case of channel closure, we detect the state of output thanks to
4537 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4538 // First, have C claim an HTLC against its own latest commitment transaction.
4539 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4541 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4544 let chanmon_cfgs = create_chanmon_cfgs(3);
4545 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4546 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4547 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4549 // Create some initial channels
4550 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4551 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4553 // Rebalance the network a bit by relaying one payment through all the channels ...
4554 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4555 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4557 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4558 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4559 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4560 check_spends!(commitment_tx[0], chan_2.3);
4561 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4562 check_added_monitors!(nodes[2], 1);
4563 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4564 assert!(updates.update_add_htlcs.is_empty());
4565 assert!(updates.update_fail_htlcs.is_empty());
4566 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4567 assert!(updates.update_fail_malformed_htlcs.is_empty());
4569 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4570 check_closed_broadcast!(nodes[2], false);
4571 check_added_monitors!(nodes[2], 1);
4573 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4574 assert_eq!(c_txn.len(), 3);
4575 assert_eq!(c_txn[0], c_txn[2]);
4576 assert_eq!(commitment_tx[0], c_txn[1]);
4577 check_spends!(c_txn[1], chan_2.3);
4578 check_spends!(c_txn[2], c_txn[1]);
4579 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4580 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4581 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4582 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4584 // 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
4585 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4587 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4588 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4589 assert_eq!(b_txn.len(), 3);
4590 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4591 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4592 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4593 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4594 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4595 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4596 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4597 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4598 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4601 check_added_monitors!(nodes[1], 1);
4602 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4603 check_added_monitors!(nodes[1], 1);
4604 match msg_events[0] {
4605 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4606 _ => panic!("Unexpected event"),
4608 match msg_events[1] {
4609 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, .. } } => {
4610 assert!(update_add_htlcs.is_empty());
4611 assert!(update_fail_htlcs.is_empty());
4612 assert_eq!(update_fulfill_htlcs.len(), 1);
4613 assert!(update_fail_malformed_htlcs.is_empty());
4614 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4616 _ => panic!("Unexpected event"),
4618 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4619 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4620 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4621 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4622 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4623 assert_eq!(b_txn.len(), 3);
4624 check_spends!(b_txn[1], chan_1.3);
4625 check_spends!(b_txn[2], b_txn[1]);
4626 check_spends!(b_txn[0], commitment_tx[0]);
4627 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4628 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4629 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4631 check_closed_broadcast!(nodes[1], false);
4632 check_added_monitors!(nodes[1], 1);
4636 fn test_duplicate_payment_hash_one_failure_one_success() {
4637 // Topology : A --> B --> C
4638 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4639 let chanmon_cfgs = create_chanmon_cfgs(3);
4640 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4641 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4642 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4644 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4645 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4647 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4648 *nodes[0].network_payment_count.borrow_mut() -= 1;
4649 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4651 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4652 assert_eq!(commitment_txn[0].input.len(), 1);
4653 check_spends!(commitment_txn[0], chan_2.3);
4655 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4656 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4657 check_closed_broadcast!(nodes[1], false);
4658 check_added_monitors!(nodes[1], 1);
4660 let htlc_timeout_tx;
4661 { // Extract one of the two HTLC-Timeout transaction
4662 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4663 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4664 assert_eq!(node_txn.len(), 5);
4665 check_spends!(node_txn[0], commitment_txn[0]);
4666 assert_eq!(node_txn[0].input.len(), 1);
4667 check_spends!(node_txn[1], commitment_txn[0]);
4668 assert_eq!(node_txn[1].input.len(), 1);
4669 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4670 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4671 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4672 check_spends!(node_txn[2], chan_2.3);
4673 check_spends!(node_txn[3], node_txn[2]);
4674 check_spends!(node_txn[4], node_txn[2]);
4675 htlc_timeout_tx = node_txn[1].clone();
4678 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4679 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4680 check_added_monitors!(nodes[2], 3);
4681 let events = nodes[2].node.get_and_clear_pending_msg_events();
4683 MessageSendEvent::UpdateHTLCs { .. } => {},
4684 _ => panic!("Unexpected event"),
4687 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4688 _ => panic!("Unexepected event"),
4690 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4691 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)
4692 check_spends!(htlc_success_txn[2], chan_2.3);
4693 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4694 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4695 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4696 assert_eq!(htlc_success_txn[0].input.len(), 1);
4697 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4698 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4699 assert_eq!(htlc_success_txn[1].input.len(), 1);
4700 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4701 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4702 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4703 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4705 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4706 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4707 expect_pending_htlcs_forwardable!(nodes[1]);
4708 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4709 assert!(htlc_updates.update_add_htlcs.is_empty());
4710 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4711 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4712 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4713 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4714 check_added_monitors!(nodes[1], 1);
4716 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4717 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4719 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4720 let events = nodes[0].node.get_and_clear_pending_msg_events();
4721 assert_eq!(events.len(), 1);
4723 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4725 _ => { panic!("Unexpected event"); }
4728 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4730 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4731 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4732 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4733 assert!(updates.update_add_htlcs.is_empty());
4734 assert!(updates.update_fail_htlcs.is_empty());
4735 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4736 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4737 assert!(updates.update_fail_malformed_htlcs.is_empty());
4738 check_added_monitors!(nodes[1], 1);
4740 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4741 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4743 let events = nodes[0].node.get_and_clear_pending_events();
4745 Event::PaymentSent { ref payment_preimage } => {
4746 assert_eq!(*payment_preimage, our_payment_preimage);
4748 _ => panic!("Unexpected event"),
4753 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4754 let chanmon_cfgs = create_chanmon_cfgs(2);
4755 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4756 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4757 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4759 // Create some initial channels
4760 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4762 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4763 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4764 assert_eq!(local_txn[0].input.len(), 1);
4765 check_spends!(local_txn[0], chan_1.3);
4767 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4768 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4769 check_added_monitors!(nodes[1], 1);
4770 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4771 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4772 check_added_monitors!(nodes[1], 1);
4773 let events = nodes[1].node.get_and_clear_pending_msg_events();
4775 MessageSendEvent::UpdateHTLCs { .. } => {},
4776 _ => panic!("Unexpected event"),
4779 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4780 _ => panic!("Unexepected event"),
4783 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4784 assert_eq!(node_txn[0].input.len(), 1);
4785 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4786 check_spends!(node_txn[0], local_txn[0]);
4787 vec![node_txn[0].clone(), node_txn[2].clone()]
4790 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4791 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4792 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4794 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4795 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4796 assert_eq!(spend_txn.len(), 2);
4797 check_spends!(spend_txn[0], node_txn[0]);
4798 check_spends!(spend_txn[1], node_txn[1]);
4801 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4802 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4803 // unrevoked commitment transaction.
4804 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4805 // a remote RAA before they could be failed backwards (and combinations thereof).
4806 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4807 // use the same payment hashes.
4808 // Thus, we use a six-node network:
4813 // And test where C fails back to A/B when D announces its latest commitment transaction
4814 let chanmon_cfgs = create_chanmon_cfgs(6);
4815 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4816 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4817 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4819 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
4820 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4821 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
4822 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
4823 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
4825 // Rebalance and check output sanity...
4826 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4827 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4828 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4830 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4832 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
4834 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
4835 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4837 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
4839 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
4841 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4843 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4844 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4846 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4848 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4851 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4853 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4854 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
4857 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
4859 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4860 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4862 // Double-check that six of the new HTLC were added
4863 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4864 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4865 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4866 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4868 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4869 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4870 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
4871 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
4872 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
4873 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
4874 check_added_monitors!(nodes[4], 0);
4875 expect_pending_htlcs_forwardable!(nodes[4]);
4876 check_added_monitors!(nodes[4], 1);
4878 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4879 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4880 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4881 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4882 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4883 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4885 // Fail 3rd below-dust and 7th above-dust HTLCs
4886 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
4887 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
4888 check_added_monitors!(nodes[5], 0);
4889 expect_pending_htlcs_forwardable!(nodes[5]);
4890 check_added_monitors!(nodes[5], 1);
4892 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4893 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4894 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4895 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4897 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4899 expect_pending_htlcs_forwardable!(nodes[3]);
4900 check_added_monitors!(nodes[3], 1);
4901 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4902 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4903 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4904 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4905 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4906 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4907 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4908 if deliver_last_raa {
4909 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4911 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4914 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4915 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4916 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4917 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4919 // We now broadcast the latest commitment transaction, which *should* result in failures for
4920 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4921 // the non-broadcast above-dust HTLCs.
4923 // Alternatively, we may broadcast the previous commitment transaction, which should only
4924 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4925 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4927 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4928 if announce_latest {
4929 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4931 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4933 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4934 check_closed_broadcast!(nodes[2], false);
4935 expect_pending_htlcs_forwardable!(nodes[2]);
4936 check_added_monitors!(nodes[2], 3);
4938 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4939 assert_eq!(cs_msgs.len(), 2);
4940 let mut a_done = false;
4941 for msg in cs_msgs {
4943 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4944 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4945 // should be failed-backwards here.
4946 let target = if *node_id == nodes[0].node.get_our_node_id() {
4947 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4948 for htlc in &updates.update_fail_htlcs {
4949 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 });
4951 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4956 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4957 for htlc in &updates.update_fail_htlcs {
4958 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4960 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4961 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4964 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4965 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4966 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4967 if announce_latest {
4968 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4969 if *node_id == nodes[0].node.get_our_node_id() {
4970 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4973 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4975 _ => panic!("Unexpected event"),
4979 let as_events = nodes[0].node.get_and_clear_pending_events();
4980 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4981 let mut as_failds = HashSet::new();
4982 for event in as_events.iter() {
4983 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4984 assert!(as_failds.insert(*payment_hash));
4985 if *payment_hash != payment_hash_2 {
4986 assert_eq!(*rejected_by_dest, deliver_last_raa);
4988 assert!(!rejected_by_dest);
4990 } else { panic!("Unexpected event"); }
4992 assert!(as_failds.contains(&payment_hash_1));
4993 assert!(as_failds.contains(&payment_hash_2));
4994 if announce_latest {
4995 assert!(as_failds.contains(&payment_hash_3));
4996 assert!(as_failds.contains(&payment_hash_5));
4998 assert!(as_failds.contains(&payment_hash_6));
5000 let bs_events = nodes[1].node.get_and_clear_pending_events();
5001 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5002 let mut bs_failds = HashSet::new();
5003 for event in bs_events.iter() {
5004 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5005 assert!(bs_failds.insert(*payment_hash));
5006 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5007 assert_eq!(*rejected_by_dest, deliver_last_raa);
5009 assert!(!rejected_by_dest);
5011 } else { panic!("Unexpected event"); }
5013 assert!(bs_failds.contains(&payment_hash_1));
5014 assert!(bs_failds.contains(&payment_hash_2));
5015 if announce_latest {
5016 assert!(bs_failds.contains(&payment_hash_4));
5018 assert!(bs_failds.contains(&payment_hash_5));
5020 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5021 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5022 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5023 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5024 // PaymentFailureNetworkUpdates.
5025 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5026 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5027 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5028 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5029 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5031 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5032 _ => panic!("Unexpected event"),
5038 fn test_fail_backwards_latest_remote_announce_a() {
5039 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5043 fn test_fail_backwards_latest_remote_announce_b() {
5044 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5048 fn test_fail_backwards_previous_remote_announce() {
5049 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5050 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5051 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5055 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5056 let chanmon_cfgs = create_chanmon_cfgs(2);
5057 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5058 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5059 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5061 // Create some initial channels
5062 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5064 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5065 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5066 assert_eq!(local_txn[0].input.len(), 1);
5067 check_spends!(local_txn[0], chan_1.3);
5069 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5070 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5071 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5072 check_closed_broadcast!(nodes[0], false);
5073 check_added_monitors!(nodes[0], 1);
5075 let htlc_timeout = {
5076 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5077 assert_eq!(node_txn[0].input.len(), 1);
5078 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5079 check_spends!(node_txn[0], local_txn[0]);
5083 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5084 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5085 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5086 expect_payment_failed!(nodes[0], our_payment_hash, true);
5088 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5089 let spend_txn = check_spendable_outputs!(nodes[0], 1);
5090 assert_eq!(spend_txn.len(), 3);
5091 assert_eq!(spend_txn[0], spend_txn[1]);
5092 check_spends!(spend_txn[0], local_txn[0]);
5093 check_spends!(spend_txn[2], htlc_timeout);
5097 fn test_static_output_closing_tx() {
5098 let chanmon_cfgs = create_chanmon_cfgs(2);
5099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5101 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5103 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5105 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5106 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5108 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5109 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5110 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5112 let spend_txn = check_spendable_outputs!(nodes[0], 2);
5113 assert_eq!(spend_txn.len(), 1);
5114 check_spends!(spend_txn[0], closing_tx);
5116 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5117 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5119 let spend_txn = check_spendable_outputs!(nodes[1], 2);
5120 assert_eq!(spend_txn.len(), 1);
5121 check_spends!(spend_txn[0], closing_tx);
5124 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5125 let chanmon_cfgs = create_chanmon_cfgs(2);
5126 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5128 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5129 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5131 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5133 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5134 // present in B's local commitment transaction, but none of A's commitment transactions.
5135 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5136 check_added_monitors!(nodes[1], 1);
5138 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5139 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5140 let events = nodes[0].node.get_and_clear_pending_events();
5141 assert_eq!(events.len(), 1);
5143 Event::PaymentSent { payment_preimage } => {
5144 assert_eq!(payment_preimage, our_payment_preimage);
5146 _ => panic!("Unexpected event"),
5149 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5150 check_added_monitors!(nodes[0], 1);
5151 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5152 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5153 check_added_monitors!(nodes[1], 1);
5155 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5156 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5157 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5158 header.prev_blockhash = header.bitcoin_hash();
5160 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5161 check_closed_broadcast!(nodes[1], false);
5162 check_added_monitors!(nodes[1], 1);
5165 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5166 let chanmon_cfgs = create_chanmon_cfgs(2);
5167 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5168 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5169 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5170 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5172 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
5173 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5174 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5175 check_added_monitors!(nodes[0], 1);
5177 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5179 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5180 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5181 // to "time out" the HTLC.
5183 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5185 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5186 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5187 header.prev_blockhash = header.bitcoin_hash();
5189 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5190 check_closed_broadcast!(nodes[0], false);
5191 check_added_monitors!(nodes[0], 1);
5194 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5195 let chanmon_cfgs = create_chanmon_cfgs(3);
5196 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5197 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5198 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5199 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5201 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5202 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5203 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5204 // actually revoked.
5205 let htlc_value = if use_dust { 50000 } else { 3000000 };
5206 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5207 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5208 expect_pending_htlcs_forwardable!(nodes[1]);
5209 check_added_monitors!(nodes[1], 1);
5211 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5212 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5213 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5214 check_added_monitors!(nodes[0], 1);
5215 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5216 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5217 check_added_monitors!(nodes[1], 1);
5218 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5219 check_added_monitors!(nodes[1], 1);
5220 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5222 if check_revoke_no_close {
5223 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5224 check_added_monitors!(nodes[0], 1);
5227 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5228 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5229 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5230 header.prev_blockhash = header.bitcoin_hash();
5232 if !check_revoke_no_close {
5233 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5234 check_closed_broadcast!(nodes[0], false);
5235 check_added_monitors!(nodes[0], 1);
5237 expect_payment_failed!(nodes[0], our_payment_hash, true);
5241 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5242 // There are only a few cases to test here:
5243 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5244 // broadcastable commitment transactions result in channel closure,
5245 // * its included in an unrevoked-but-previous remote commitment transaction,
5246 // * its included in the latest remote or local commitment transactions.
5247 // We test each of the three possible commitment transactions individually and use both dust and
5249 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5250 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5251 // tested for at least one of the cases in other tests.
5253 fn htlc_claim_single_commitment_only_a() {
5254 do_htlc_claim_local_commitment_only(true);
5255 do_htlc_claim_local_commitment_only(false);
5257 do_htlc_claim_current_remote_commitment_only(true);
5258 do_htlc_claim_current_remote_commitment_only(false);
5262 fn htlc_claim_single_commitment_only_b() {
5263 do_htlc_claim_previous_remote_commitment_only(true, false);
5264 do_htlc_claim_previous_remote_commitment_only(false, false);
5265 do_htlc_claim_previous_remote_commitment_only(true, true);
5266 do_htlc_claim_previous_remote_commitment_only(false, true);
5269 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
5270 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5273 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
5277 // 0: node1 fails backward
5278 // 1: final node fails backward
5279 // 2: payment completed but the user rejects the payment
5280 // 3: final node fails backward (but tamper onion payloads from node0)
5281 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5282 // 200: trigger error in the final node and tamper returning fail_htlc
5283 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
5284 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5285 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5289 // reset block height
5290 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5291 for ix in 0..nodes.len() {
5292 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5295 macro_rules! expect_event {
5296 ($node: expr, $event_type: path) => {{
5297 let events = $node.node.get_and_clear_pending_events();
5298 assert_eq!(events.len(), 1);
5300 $event_type { .. } => {},
5301 _ => panic!("Unexpected event"),
5306 macro_rules! expect_htlc_forward {
5308 expect_event!($node, Event::PendingHTLCsForwardable);
5309 $node.node.process_pending_htlc_forwards();
5313 // 0 ~~> 2 send payment
5314 nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5315 check_added_monitors!(nodes[0], 1);
5316 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5317 // temper update_add (0 => 1)
5318 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5319 if test_case == 0 || test_case == 3 || test_case == 100 {
5320 callback_msg(&mut update_add_0);
5323 // 0 => 1 update_add & CS
5324 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5325 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5327 let update_1_0 = match test_case {
5328 0|100 => { // intermediate node failure; fail backward to 0
5329 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5330 assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
5333 1|2|3|200 => { // final node failure; forwarding to 2
5334 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5336 if test_case != 200 {
5339 expect_htlc_forward!(&nodes[1]);
5341 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5342 check_added_monitors!(&nodes[1], 1);
5343 assert_eq!(update_1.update_add_htlcs.len(), 1);
5344 // tamper update_add (1 => 2)
5345 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5346 if test_case != 3 && test_case != 200 {
5347 callback_msg(&mut update_add_1);
5351 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5352 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5354 if test_case == 2 || test_case == 200 {
5355 expect_htlc_forward!(&nodes[2]);
5356 expect_event!(&nodes[2], Event::PaymentReceived);
5358 expect_pending_htlcs_forwardable!(nodes[2]);
5361 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5362 if test_case == 2 || test_case == 200 {
5363 check_added_monitors!(&nodes[2], 1);
5365 assert!(update_2_1.update_fail_htlcs.len() == 1);
5367 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5368 if test_case == 200 {
5369 callback_fail(&mut fail_msg);
5373 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5374 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5376 // backward fail on 1
5377 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5378 assert!(update_1_0.update_fail_htlcs.len() == 1);
5381 _ => unreachable!(),
5384 // 1 => 0 commitment_signed_dance
5385 if update_1_0.update_fail_htlcs.len() > 0 {
5386 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5387 if test_case == 100 {
5388 callback_fail(&mut fail_msg);
5390 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5392 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5395 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5397 let events = nodes[0].node.get_and_clear_pending_events();
5398 assert_eq!(events.len(), 1);
5399 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5400 assert_eq!(*rejected_by_dest, !expected_retryable);
5401 assert_eq!(*error_code, expected_error_code);
5403 panic!("Uexpected event");
5406 let events = nodes[0].node.get_and_clear_pending_msg_events();
5407 if expected_channel_update.is_some() {
5408 assert_eq!(events.len(), 1);
5410 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5412 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5413 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5414 panic!("channel_update not found!");
5417 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5418 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5419 assert!(*short_channel_id == *expected_short_channel_id);
5420 assert!(*is_permanent == *expected_is_permanent);
5422 panic!("Unexpected message event");
5425 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5426 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5427 assert!(*node_id == *expected_node_id);
5428 assert!(*is_permanent == *expected_is_permanent);
5430 panic!("Unexpected message event");
5435 _ => panic!("Unexpected message event"),
5438 assert_eq!(events.len(), 0);
5442 impl msgs::ChannelUpdate {
5443 fn dummy() -> msgs::ChannelUpdate {
5444 use bitcoin::secp256k1::ffi::Signature as FFISignature;
5445 use bitcoin::secp256k1::Signature;
5446 msgs::ChannelUpdate {
5447 signature: Signature::from(FFISignature::new()),
5448 contents: msgs::UnsignedChannelUpdate {
5449 chain_hash: BlockHash::hash(&vec![0u8][..]),
5450 short_channel_id: 0,
5453 cltv_expiry_delta: 0,
5454 htlc_minimum_msat: 0,
5456 fee_proportional_millionths: 0,
5457 excess_data: vec![],
5463 struct BogusOnionHopData {
5466 impl BogusOnionHopData {
5467 fn new(orig: msgs::OnionHopData) -> Self {
5468 Self { data: orig.encode() }
5471 impl Writeable for BogusOnionHopData {
5472 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5473 writer.write_all(&self.data[..])
5478 fn test_onion_failure() {
5479 use ln::msgs::ChannelUpdate;
5480 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5481 use bitcoin::secp256k1;
5483 const BADONION: u16 = 0x8000;
5484 const PERM: u16 = 0x4000;
5485 const NODE: u16 = 0x2000;
5486 const UPDATE: u16 = 0x1000;
5488 let chanmon_cfgs = create_chanmon_cfgs(3);
5489 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5490 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5491 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5492 for node in nodes.iter() {
5493 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5495 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
5496 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5497 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5499 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5501 // intermediate node failure
5502 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5503 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5504 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5505 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5506 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5507 let mut new_payloads = Vec::new();
5508 for payload in onion_payloads.drain(..) {
5509 new_payloads.push(BogusOnionHopData::new(payload));
5511 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5512 // describing a length-1 TLV payload, which is obviously bogus.
5513 new_payloads[0].data[0] = 1;
5514 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5515 }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
5517 // final node failure
5518 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5519 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5520 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5521 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5522 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5523 let mut new_payloads = Vec::new();
5524 for payload in onion_payloads.drain(..) {
5525 new_payloads.push(BogusOnionHopData::new(payload));
5527 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5528 // length-1 TLV payload, which is obviously bogus.
5529 new_payloads[1].data[0] = 1;
5530 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5531 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5533 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5534 // receiving simulated fail messages
5535 // intermediate node failure
5536 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5538 msg.amount_msat -= 1;
5540 // and tamper returning error message
5541 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5542 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5543 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5544 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5546 // final node failure
5547 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5548 // and tamper returning error message
5549 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5550 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5551 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5553 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5554 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5556 // intermediate node failure
5557 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5558 msg.amount_msat -= 1;
5560 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5561 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5562 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5563 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5565 // final node failure
5566 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5567 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5568 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5569 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5571 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5572 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5574 // intermediate node failure
5575 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5576 msg.amount_msat -= 1;
5578 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5579 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5580 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5582 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5583 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5585 // final node failure
5586 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5587 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5588 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5589 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5591 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5592 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5594 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5595 Some(BADONION|PERM|4), None);
5597 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5598 Some(BADONION|PERM|5), None);
5600 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5601 Some(BADONION|PERM|6), None);
5603 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5604 msg.amount_msat -= 1;
5606 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5607 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5608 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5609 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5611 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5612 msg.amount_msat -= 1;
5614 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5615 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5616 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5617 // short_channel_id from the processing node
5618 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5620 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5621 msg.amount_msat -= 1;
5623 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5624 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5625 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5626 // short_channel_id from the processing node
5627 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5629 let mut bogus_route = route.clone();
5630 bogus_route.paths[0][1].short_channel_id -= 1;
5631 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5632 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5634 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5635 let mut bogus_route = route.clone();
5636 let route_len = bogus_route.paths[0].len();
5637 bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5638 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5640 //TODO: with new config API, we will be able to generate both valid and
5641 //invalid channel_update cases.
5642 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5643 msg.amount_msat -= 1;
5644 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5646 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5647 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5648 msg.cltv_expiry -= 1;
5649 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5651 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5652 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5653 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5655 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5656 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5658 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5659 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5660 }, false, Some(PERM|15), None);
5662 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5663 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5664 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5666 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5667 }, || {}, true, Some(17), None);
5669 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5670 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5671 for f in pending_forwards.iter_mut() {
5673 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5674 forward_info.outgoing_cltv_value += 1,
5679 }, true, Some(18), None);
5681 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5682 // violate amt_to_forward > msg.amount_msat
5683 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5684 for f in pending_forwards.iter_mut() {
5686 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5687 forward_info.amt_to_forward -= 1,
5692 }, true, Some(19), None);
5694 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5695 // disconnect event to the channel between nodes[1] ~ nodes[2]
5696 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5697 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5698 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5699 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5701 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5702 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5703 let mut route = route.clone();
5705 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5706 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5707 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5708 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5709 msg.cltv_expiry = htlc_cltv;
5710 msg.onion_routing_packet = onion_packet;
5711 }, ||{}, true, Some(21), None);
5716 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5717 let chanmon_cfgs = create_chanmon_cfgs(2);
5718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5720 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5721 //Force duplicate channel ids
5722 for node in nodes.iter() {
5723 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5726 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5727 let channel_value_satoshis=10000;
5728 let push_msat=10001;
5729 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5730 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5731 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5733 //Create a second channel with a channel_id collision
5734 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5738 fn bolt2_open_channel_sending_node_checks_part2() {
5739 let chanmon_cfgs = create_chanmon_cfgs(2);
5740 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5741 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5742 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5744 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5745 let channel_value_satoshis=2^24;
5746 let push_msat=10001;
5747 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5749 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5750 let channel_value_satoshis=10000;
5751 // Test when push_msat is equal to 1000 * funding_satoshis.
5752 let push_msat=1000*channel_value_satoshis+1;
5753 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5755 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5756 let channel_value_satoshis=10000;
5757 let push_msat=10001;
5758 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
5759 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5760 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5762 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5763 // 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
5764 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5766 // 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.
5767 assert!(BREAKDOWN_TIMEOUT>0);
5768 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5770 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5771 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5772 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5774 // 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.
5775 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5776 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5777 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5778 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5779 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5782 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5783 // 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.
5784 //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.
5787 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5788 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5789 let chanmon_cfgs = create_chanmon_cfgs(2);
5790 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5791 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5792 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5793 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5794 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5795 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5797 route.paths[0][0].fee_msat = 100;
5799 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5800 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
5801 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5802 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5806 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5807 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5808 let chanmon_cfgs = create_chanmon_cfgs(2);
5809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5811 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5812 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5813 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5814 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5816 route.paths[0][0].fee_msat = 0;
5818 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5819 assert_eq!(err, "Cannot send 0-msat HTLC"));
5820 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5821 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5825 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5826 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5827 let chanmon_cfgs = create_chanmon_cfgs(2);
5828 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5829 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5830 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5831 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5832 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5833 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5835 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5836 check_added_monitors!(nodes[0], 1);
5837 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5838 updates.update_add_htlcs[0].amount_msat = 0;
5840 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5841 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5842 check_closed_broadcast!(nodes[1], true).unwrap();
5843 check_added_monitors!(nodes[1], 1);
5847 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5848 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5849 //It is enforced when constructing a route.
5850 let chanmon_cfgs = create_chanmon_cfgs(2);
5851 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5852 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5853 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5854 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
5855 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5856 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5858 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
5859 assert_eq!(err, "Channel CLTV overflowed?!"));
5863 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5864 //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.
5865 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5866 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5867 let chanmon_cfgs = create_chanmon_cfgs(2);
5868 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5869 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5870 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5871 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
5872 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5874 for i in 0..max_accepted_htlcs {
5875 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5876 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5877 let payment_event = {
5878 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5879 check_added_monitors!(nodes[0], 1);
5881 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5882 assert_eq!(events.len(), 1);
5883 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5884 assert_eq!(htlcs[0].htlc_id, i);
5888 SendEvent::from_event(events.remove(0))
5890 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5891 check_added_monitors!(nodes[1], 0);
5892 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5894 expect_pending_htlcs_forwardable!(nodes[1]);
5895 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5897 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5898 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5899 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5900 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
5902 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5903 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5907 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5908 //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.
5909 let chanmon_cfgs = create_chanmon_cfgs(2);
5910 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5911 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5912 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5913 let channel_value = 100000;
5914 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
5915 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5917 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5919 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5920 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5921 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5922 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
5924 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5925 nodes[0].logger.assert_log("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);
5927 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5930 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5932 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5933 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5934 let chanmon_cfgs = create_chanmon_cfgs(2);
5935 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5936 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5937 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5938 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5939 let htlc_minimum_msat: u64;
5941 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5942 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5943 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5945 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5946 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5947 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5948 check_added_monitors!(nodes[0], 1);
5949 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5950 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5951 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5952 assert!(nodes[1].node.list_channels().is_empty());
5953 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5954 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5955 check_added_monitors!(nodes[1], 1);
5959 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5960 //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
5961 let chanmon_cfgs = create_chanmon_cfgs(2);
5962 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5963 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5964 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5965 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5967 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5969 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5970 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5971 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5972 check_added_monitors!(nodes[0], 1);
5973 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5975 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5976 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5978 assert!(nodes[1].node.list_channels().is_empty());
5979 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5980 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5981 check_added_monitors!(nodes[1], 1);
5985 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5986 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5987 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5988 let chanmon_cfgs = create_chanmon_cfgs(2);
5989 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5990 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5991 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5992 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5993 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5994 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5996 let session_priv = SecretKey::from_slice(&{
5997 let mut session_key = [0; 32];
5998 let mut rng = thread_rng();
5999 rng.fill_bytes(&mut session_key);
6001 }).expect("RNG is bad!");
6003 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6004 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6005 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6006 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6008 let mut msg = msgs::UpdateAddHTLC {
6012 payment_hash: our_payment_hash,
6013 cltv_expiry: htlc_cltv,
6014 onion_routing_packet: onion_packet.clone(),
6017 for i in 0..super::channel::OUR_MAX_HTLCS {
6018 msg.htlc_id = i as u64;
6019 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6021 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6022 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6024 assert!(nodes[1].node.list_channels().is_empty());
6025 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6026 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
6027 check_added_monitors!(nodes[1], 1);
6031 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6032 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6033 let chanmon_cfgs = create_chanmon_cfgs(2);
6034 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6035 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6036 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6037 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6038 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6039 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6040 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6041 check_added_monitors!(nodes[0], 1);
6042 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6043 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6044 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6046 assert!(nodes[1].node.list_channels().is_empty());
6047 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6048 assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
6049 check_added_monitors!(nodes[1], 1);
6053 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6054 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6055 let chanmon_cfgs = create_chanmon_cfgs(2);
6056 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6057 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6058 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6059 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6060 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
6061 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6062 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6063 check_added_monitors!(nodes[0], 1);
6064 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6065 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6066 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6068 assert!(nodes[1].node.list_channels().is_empty());
6069 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6070 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6071 check_added_monitors!(nodes[1], 1);
6075 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6076 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6077 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6078 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6079 let chanmon_cfgs = create_chanmon_cfgs(2);
6080 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6081 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6082 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6083 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6084 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6085 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6086 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6087 check_added_monitors!(nodes[0], 1);
6088 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6089 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6091 //Disconnect and Reconnect
6092 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6093 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6094 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6095 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6096 assert_eq!(reestablish_1.len(), 1);
6097 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6098 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6099 assert_eq!(reestablish_2.len(), 1);
6100 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6101 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6102 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6103 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6106 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6107 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6108 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6109 check_added_monitors!(nodes[1], 1);
6110 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6112 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6114 assert!(nodes[1].node.list_channels().is_empty());
6115 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6116 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6117 check_added_monitors!(nodes[1], 1);
6121 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6122 //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.
6124 let chanmon_cfgs = create_chanmon_cfgs(2);
6125 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6126 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6127 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6128 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6130 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6131 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6132 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6133 check_added_monitors!(nodes[0], 1);
6134 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6135 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6137 let update_msg = msgs::UpdateFulfillHTLC{
6140 payment_preimage: our_payment_preimage,
6143 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6145 assert!(nodes[0].node.list_channels().is_empty());
6146 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6147 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6148 check_added_monitors!(nodes[0], 1);
6152 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6153 //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.
6155 let chanmon_cfgs = create_chanmon_cfgs(2);
6156 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6157 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6158 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6159 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6161 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6162 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6163 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6164 check_added_monitors!(nodes[0], 1);
6165 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6166 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6168 let update_msg = msgs::UpdateFailHTLC{
6171 reason: msgs::OnionErrorPacket { data: Vec::new()},
6174 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6176 assert!(nodes[0].node.list_channels().is_empty());
6177 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6178 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6179 check_added_monitors!(nodes[0], 1);
6183 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6184 //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.
6186 let chanmon_cfgs = create_chanmon_cfgs(2);
6187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6189 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6190 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6192 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6193 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6194 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6195 check_added_monitors!(nodes[0], 1);
6196 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6197 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6199 let update_msg = msgs::UpdateFailMalformedHTLC{
6202 sha256_of_onion: [1; 32],
6203 failure_code: 0x8000,
6206 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6208 assert!(nodes[0].node.list_channels().is_empty());
6209 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6210 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6211 check_added_monitors!(nodes[0], 1);
6215 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6216 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6218 let chanmon_cfgs = create_chanmon_cfgs(2);
6219 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6220 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6221 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6222 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6224 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6226 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6227 check_added_monitors!(nodes[1], 1);
6229 let events = nodes[1].node.get_and_clear_pending_msg_events();
6230 assert_eq!(events.len(), 1);
6231 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6233 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, .. } } => {
6234 assert!(update_add_htlcs.is_empty());
6235 assert_eq!(update_fulfill_htlcs.len(), 1);
6236 assert!(update_fail_htlcs.is_empty());
6237 assert!(update_fail_malformed_htlcs.is_empty());
6238 assert!(update_fee.is_none());
6239 update_fulfill_htlcs[0].clone()
6241 _ => panic!("Unexpected event"),
6245 update_fulfill_msg.htlc_id = 1;
6247 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6249 assert!(nodes[0].node.list_channels().is_empty());
6250 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6251 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6252 check_added_monitors!(nodes[0], 1);
6256 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6257 //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.
6259 let chanmon_cfgs = create_chanmon_cfgs(2);
6260 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6261 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6262 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6263 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6265 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6267 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6268 check_added_monitors!(nodes[1], 1);
6270 let events = nodes[1].node.get_and_clear_pending_msg_events();
6271 assert_eq!(events.len(), 1);
6272 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6274 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, .. } } => {
6275 assert!(update_add_htlcs.is_empty());
6276 assert_eq!(update_fulfill_htlcs.len(), 1);
6277 assert!(update_fail_htlcs.is_empty());
6278 assert!(update_fail_malformed_htlcs.is_empty());
6279 assert!(update_fee.is_none());
6280 update_fulfill_htlcs[0].clone()
6282 _ => panic!("Unexpected event"),
6286 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6288 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6290 assert!(nodes[0].node.list_channels().is_empty());
6291 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6292 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6293 check_added_monitors!(nodes[0], 1);
6297 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6298 //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.
6300 let chanmon_cfgs = create_chanmon_cfgs(2);
6301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6303 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6304 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6305 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6306 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6307 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6308 check_added_monitors!(nodes[0], 1);
6310 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6311 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6313 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6314 check_added_monitors!(nodes[1], 0);
6315 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6317 let events = nodes[1].node.get_and_clear_pending_msg_events();
6319 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6321 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, .. } } => {
6322 assert!(update_add_htlcs.is_empty());
6323 assert!(update_fulfill_htlcs.is_empty());
6324 assert!(update_fail_htlcs.is_empty());
6325 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6326 assert!(update_fee.is_none());
6327 update_fail_malformed_htlcs[0].clone()
6329 _ => panic!("Unexpected event"),
6332 update_msg.failure_code &= !0x8000;
6333 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6335 assert!(nodes[0].node.list_channels().is_empty());
6336 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6337 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6338 check_added_monitors!(nodes[0], 1);
6342 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6343 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6344 // * 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.
6346 let chanmon_cfgs = create_chanmon_cfgs(3);
6347 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6348 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6349 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6350 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6351 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6353 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6354 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6357 let mut payment_event = {
6358 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6359 check_added_monitors!(nodes[0], 1);
6360 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6361 assert_eq!(events.len(), 1);
6362 SendEvent::from_event(events.remove(0))
6364 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6365 check_added_monitors!(nodes[1], 0);
6366 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6367 expect_pending_htlcs_forwardable!(nodes[1]);
6368 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6369 assert_eq!(events_2.len(), 1);
6370 check_added_monitors!(nodes[1], 1);
6371 payment_event = SendEvent::from_event(events_2.remove(0));
6372 assert_eq!(payment_event.msgs.len(), 1);
6375 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6376 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6377 check_added_monitors!(nodes[2], 0);
6378 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6380 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6381 assert_eq!(events_3.len(), 1);
6382 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6384 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 } } => {
6385 assert!(update_add_htlcs.is_empty());
6386 assert!(update_fulfill_htlcs.is_empty());
6387 assert!(update_fail_htlcs.is_empty());
6388 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6389 assert!(update_fee.is_none());
6390 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6392 _ => panic!("Unexpected event"),
6396 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6398 check_added_monitors!(nodes[1], 0);
6399 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6400 expect_pending_htlcs_forwardable!(nodes[1]);
6401 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6402 assert_eq!(events_4.len(), 1);
6404 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6406 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, .. } } => {
6407 assert!(update_add_htlcs.is_empty());
6408 assert!(update_fulfill_htlcs.is_empty());
6409 assert_eq!(update_fail_htlcs.len(), 1);
6410 assert!(update_fail_malformed_htlcs.is_empty());
6411 assert!(update_fee.is_none());
6413 _ => panic!("Unexpected event"),
6416 check_added_monitors!(nodes[1], 1);
6419 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6420 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6421 // 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
6422 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6424 let chanmon_cfgs = create_chanmon_cfgs(2);
6425 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6426 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6427 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6428 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6430 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6432 // We route 2 dust-HTLCs between A and B
6433 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6434 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6435 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6437 // Cache one local commitment tx as previous
6438 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6440 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6441 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6442 check_added_monitors!(nodes[1], 0);
6443 expect_pending_htlcs_forwardable!(nodes[1]);
6444 check_added_monitors!(nodes[1], 1);
6446 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6447 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6448 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6449 check_added_monitors!(nodes[0], 1);
6451 // Cache one local commitment tx as lastest
6452 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6454 let events = nodes[0].node.get_and_clear_pending_msg_events();
6456 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6457 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6459 _ => panic!("Unexpected event"),
6462 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6463 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6465 _ => panic!("Unexpected event"),
6468 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6469 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6470 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6472 if announce_latest {
6473 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6475 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6478 check_closed_broadcast!(nodes[0], false);
6479 check_added_monitors!(nodes[0], 1);
6481 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6482 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6483 let events = nodes[0].node.get_and_clear_pending_events();
6484 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6485 assert_eq!(events.len(), 2);
6486 let mut first_failed = false;
6487 for event in events {
6489 Event::PaymentFailed { payment_hash, .. } => {
6490 if payment_hash == payment_hash_1 {
6491 assert!(!first_failed);
6492 first_failed = true;
6494 assert_eq!(payment_hash, payment_hash_2);
6497 _ => panic!("Unexpected event"),
6503 fn test_failure_delay_dust_htlc_local_commitment() {
6504 do_test_failure_delay_dust_htlc_local_commitment(true);
6505 do_test_failure_delay_dust_htlc_local_commitment(false);
6509 fn test_no_failure_dust_htlc_local_commitment() {
6510 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6511 // prone to error, we test here that a dummy transaction don't fail them.
6513 let chanmon_cfgs = create_chanmon_cfgs(2);
6514 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6515 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6516 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6517 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6520 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6522 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6523 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6525 // We route 2 dust-HTLCs between A and B
6526 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6527 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6529 // Build a dummy invalid transaction trying to spend a commitment tx
6531 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6532 script_sig: Script::new(),
6534 witness: Vec::new(),
6538 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6542 let dummy_tx = Transaction {
6549 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6550 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6551 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6552 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6553 // We broadcast a few more block to check everything is all right
6554 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6555 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6556 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6558 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6559 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6562 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6563 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6564 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6565 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6566 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6567 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6568 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6570 let chanmon_cfgs = create_chanmon_cfgs(3);
6571 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6572 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6573 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6574 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6576 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6578 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6579 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6581 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6582 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6584 // We revoked bs_commitment_tx
6586 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6587 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6590 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6591 let mut timeout_tx = Vec::new();
6593 // We fail dust-HTLC 1 by broadcast of local commitment tx
6594 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6595 check_closed_broadcast!(nodes[0], false);
6596 check_added_monitors!(nodes[0], 1);
6597 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6598 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6599 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6600 expect_payment_failed!(nodes[0], dust_hash, true);
6601 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6602 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6603 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6604 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6605 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6606 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6607 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6608 expect_payment_failed!(nodes[0], non_dust_hash, true);
6610 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6611 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6612 check_closed_broadcast!(nodes[0], false);
6613 check_added_monitors!(nodes[0], 1);
6614 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6615 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6616 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6617 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6619 expect_payment_failed!(nodes[0], dust_hash, true);
6620 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6621 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6622 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6623 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6624 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6625 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6626 expect_payment_failed!(nodes[0], non_dust_hash, true);
6628 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6630 let events = nodes[0].node.get_and_clear_pending_events();
6631 assert_eq!(events.len(), 2);
6634 Event::PaymentFailed { payment_hash, .. } => {
6635 if payment_hash == dust_hash { first = true; }
6636 else { first = false; }
6638 _ => panic!("Unexpected event"),
6641 Event::PaymentFailed { payment_hash, .. } => {
6642 if first { assert_eq!(payment_hash, non_dust_hash); }
6643 else { assert_eq!(payment_hash, dust_hash); }
6645 _ => panic!("Unexpected event"),
6652 fn test_sweep_outbound_htlc_failure_update() {
6653 do_test_sweep_outbound_htlc_failure_update(false, true);
6654 do_test_sweep_outbound_htlc_failure_update(false, false);
6655 do_test_sweep_outbound_htlc_failure_update(true, false);
6659 fn test_upfront_shutdown_script() {
6660 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6661 // enforce it at shutdown message
6663 let mut config = UserConfig::default();
6664 config.channel_options.announced_channel = true;
6665 config.peer_channel_config_limits.force_announced_channel_preference = false;
6666 config.channel_options.commit_upfront_shutdown_pubkey = false;
6667 let user_cfgs = [None, Some(config), None];
6668 let chanmon_cfgs = create_chanmon_cfgs(3);
6669 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6670 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6671 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6673 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6674 let flags = InitFeatures::known();
6675 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6676 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6677 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6678 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6679 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6680 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6681 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6682 check_added_monitors!(nodes[2], 1);
6684 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6685 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6686 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6687 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6688 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6689 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6690 let events = nodes[2].node.get_and_clear_pending_msg_events();
6691 assert_eq!(events.len(), 1);
6693 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6694 _ => panic!("Unexpected event"),
6697 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6698 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
6699 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6700 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6701 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6702 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6703 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6704 let events = nodes[1].node.get_and_clear_pending_msg_events();
6705 assert_eq!(events.len(), 1);
6707 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6708 _ => panic!("Unexpected event"),
6711 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6712 // channel smoothly, opt-out is from channel initiator here
6713 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6714 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6715 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6716 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6717 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6718 let events = nodes[0].node.get_and_clear_pending_msg_events();
6719 assert_eq!(events.len(), 1);
6721 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6722 _ => panic!("Unexpected event"),
6725 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6726 //// channel smoothly
6727 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6728 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6729 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6730 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6731 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6732 let events = nodes[0].node.get_and_clear_pending_msg_events();
6733 assert_eq!(events.len(), 2);
6735 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6736 _ => panic!("Unexpected event"),
6739 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6740 _ => panic!("Unexpected event"),
6745 fn test_user_configurable_csv_delay() {
6746 // We test our channel constructors yield errors when we pass them absurd csv delay
6748 let mut low_our_to_self_config = UserConfig::default();
6749 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6750 let mut high_their_to_self_config = UserConfig::default();
6751 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6752 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6753 let chanmon_cfgs = create_chanmon_cfgs(2);
6754 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6755 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6756 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6758 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6759 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
6760 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6762 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6763 _ => panic!("Unexpected event"),
6765 } else { assert!(false) }
6767 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6768 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6769 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6770 open_channel.to_self_delay = 200;
6771 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6773 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6774 _ => panic!("Unexpected event"),
6776 } else { assert!(false); }
6778 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6779 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6780 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()));
6781 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6782 accept_channel.to_self_delay = 200;
6783 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
6784 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6786 &ErrorAction::SendErrorMessage { ref msg } => {
6787 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6789 _ => { assert!(false); }
6791 } else { assert!(false); }
6793 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6794 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6795 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6796 open_channel.to_self_delay = 200;
6797 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
6799 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6800 _ => panic!("Unexpected event"),
6802 } else { assert!(false); }
6806 fn test_data_loss_protect() {
6807 // We want to be sure that :
6808 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6809 // * we close channel in case of detecting other being fallen behind
6810 // * we are able to claim our own outputs thanks to to_remote being static
6816 let chanmon_cfgs = create_chanmon_cfgs(2);
6817 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6818 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6819 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6821 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6823 // Cache node A state before any channel update
6824 let previous_node_state = nodes[0].node.encode();
6825 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6826 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6828 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6829 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6831 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6832 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6834 // Restore node A from previous state
6835 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6836 let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6837 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6838 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6839 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6840 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6841 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6843 let mut channel_monitors = HashMap::new();
6844 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6845 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6846 keys_manager: &keys_manager,
6847 fee_estimator: &fee_estimator,
6849 logger: Arc::clone(&logger),
6850 tx_broadcaster: &tx_broadcaster,
6851 default_config: UserConfig::default(),
6852 channel_monitors: &mut channel_monitors,
6855 nodes[0].node = &node_state_0;
6856 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6857 nodes[0].chan_monitor = &monitor;
6858 nodes[0].chain_monitor = chain_monitor;
6860 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6861 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6862 nodes[0].block_notifier.register_listener(nodes[0].node);
6864 check_added_monitors!(nodes[0], 1);
6866 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6867 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6869 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6871 // Check we don't broadcast any transactions following learning of per_commitment_point from B
6872 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6873 check_added_monitors!(nodes[0], 1);
6876 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6877 assert_eq!(node_txn.len(), 0);
6880 let mut reestablish_1 = Vec::with_capacity(1);
6881 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6882 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6883 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6884 reestablish_1.push(msg.clone());
6885 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6886 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6888 &ErrorAction::SendErrorMessage { ref msg } => {
6889 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");
6891 _ => panic!("Unexpected event!"),
6894 panic!("Unexpected event")
6898 // Check we close channel detecting A is fallen-behind
6899 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6900 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6901 check_added_monitors!(nodes[1], 1);
6904 // Check A is able to claim to_remote output
6905 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6906 assert_eq!(node_txn.len(), 1);
6907 check_spends!(node_txn[0], chan.3);
6908 assert_eq!(node_txn[0].output.len(), 2);
6909 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6910 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
6911 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
6912 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6913 assert_eq!(spend_txn.len(), 1);
6914 check_spends!(spend_txn[0], node_txn[0]);
6918 fn test_check_htlc_underpaying() {
6919 // Send payment through A -> B but A is maliciously
6920 // sending a probe payment (i.e less than expected value0
6921 // to B, B should refuse payment.
6923 let chanmon_cfgs = create_chanmon_cfgs(2);
6924 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6925 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6926 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6928 // Create some initial channels
6929 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6931 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6933 // Node 3 is expecting payment of 100_000 but receive 10_000,
6934 // fail htlc like we didn't know the preimage.
6935 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
6936 nodes[1].node.process_pending_htlc_forwards();
6938 let events = nodes[1].node.get_and_clear_pending_msg_events();
6939 assert_eq!(events.len(), 1);
6940 let (update_fail_htlc, commitment_signed) = match events[0] {
6941 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 } } => {
6942 assert!(update_add_htlcs.is_empty());
6943 assert!(update_fulfill_htlcs.is_empty());
6944 assert_eq!(update_fail_htlcs.len(), 1);
6945 assert!(update_fail_malformed_htlcs.is_empty());
6946 assert!(update_fee.is_none());
6947 (update_fail_htlcs[0].clone(), commitment_signed)
6949 _ => panic!("Unexpected event"),
6951 check_added_monitors!(nodes[1], 1);
6953 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6954 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6956 // 10_000 msat as u64, followed by a height of 99 as u32
6957 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
6958 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
6959 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6960 nodes[1].node.get_and_clear_pending_events();
6964 fn test_announce_disable_channels() {
6965 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6966 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6968 let chanmon_cfgs = create_chanmon_cfgs(2);
6969 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6970 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6971 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6973 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
6974 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
6975 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
6978 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6979 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6981 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6982 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6983 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6984 assert_eq!(msg_events.len(), 3);
6985 for e in msg_events {
6987 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6988 let short_id = msg.contents.short_channel_id;
6989 // Check generated channel_update match list in PendingChannelUpdate
6990 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6991 panic!("Generated ChannelUpdate for wrong chan!");
6994 _ => panic!("Unexpected event"),
6998 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6999 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7000 assert_eq!(reestablish_1.len(), 3);
7001 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7002 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7003 assert_eq!(reestablish_2.len(), 3);
7005 // Reestablish chan_1
7006 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7007 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7008 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7009 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7010 // Reestablish chan_2
7011 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7012 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7013 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7014 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7015 // Reestablish chan_3
7016 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7017 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7018 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7019 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7021 nodes[0].node.timer_chan_freshness_every_min();
7022 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7026 fn test_bump_penalty_txn_on_revoked_commitment() {
7027 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7028 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7030 let chanmon_cfgs = create_chanmon_cfgs(2);
7031 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7032 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7033 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7035 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7036 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7037 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
7038 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7040 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7041 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7042 assert_eq!(revoked_txn[0].output.len(), 4);
7043 assert_eq!(revoked_txn[0].input.len(), 1);
7044 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7045 let revoked_txid = revoked_txn[0].txid();
7047 let mut penalty_sum = 0;
7048 for outp in revoked_txn[0].output.iter() {
7049 if outp.script_pubkey.is_v0_p2wsh() {
7050 penalty_sum += outp.value;
7054 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7055 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7057 // Actually revoke tx by claiming a HTLC
7058 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7059 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7060 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7061 check_added_monitors!(nodes[1], 1);
7063 // One or more justice tx should have been broadcast, check it
7067 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7068 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7069 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7070 assert_eq!(node_txn[0].output.len(), 1);
7071 check_spends!(node_txn[0], revoked_txn[0]);
7072 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7073 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7074 penalty_1 = node_txn[0].txid();
7078 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7079 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
7080 let mut penalty_2 = penalty_1;
7081 let mut feerate_2 = 0;
7083 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7084 assert_eq!(node_txn.len(), 1);
7085 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7086 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7087 assert_eq!(node_txn[0].output.len(), 1);
7088 check_spends!(node_txn[0], revoked_txn[0]);
7089 penalty_2 = node_txn[0].txid();
7090 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7091 assert_ne!(penalty_2, penalty_1);
7092 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7093 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7094 // Verify 25% bump heuristic
7095 assert!(feerate_2 * 100 >= feerate_1 * 125);
7099 assert_ne!(feerate_2, 0);
7101 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7102 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7104 let mut feerate_3 = 0;
7106 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7107 assert_eq!(node_txn.len(), 1);
7108 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7109 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7110 assert_eq!(node_txn[0].output.len(), 1);
7111 check_spends!(node_txn[0], revoked_txn[0]);
7112 penalty_3 = node_txn[0].txid();
7113 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7114 assert_ne!(penalty_3, penalty_2);
7115 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7116 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7117 // Verify 25% bump heuristic
7118 assert!(feerate_3 * 100 >= feerate_2 * 125);
7122 assert_ne!(feerate_3, 0);
7124 nodes[1].node.get_and_clear_pending_events();
7125 nodes[1].node.get_and_clear_pending_msg_events();
7129 fn test_bump_penalty_txn_on_revoked_htlcs() {
7130 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7131 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7133 let chanmon_cfgs = create_chanmon_cfgs(2);
7134 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7135 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7136 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7138 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7139 // Lock HTLC in both directions
7140 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7141 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7143 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7144 assert_eq!(revoked_local_txn[0].input.len(), 1);
7145 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7147 // Revoke local commitment tx
7148 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7150 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7151 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7152 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7153 check_closed_broadcast!(nodes[1], false);
7154 check_added_monitors!(nodes[1], 1);
7156 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7157 assert_eq!(revoked_htlc_txn.len(), 4);
7158 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7159 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7160 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7161 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7162 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7163 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7164 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7165 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7166 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7167 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7168 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7169 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7172 // Broadcast set of revoked txn on A
7173 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7174 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7176 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7177 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7182 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7183 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7184 // Verify claim tx are spending revoked HTLC txn
7185 assert_eq!(node_txn[4].input.len(), 2);
7186 assert_eq!(node_txn[4].output.len(), 1);
7187 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7188 first = node_txn[4].txid();
7189 // Store both feerates for later comparison
7190 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7191 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7192 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7196 // Connect three more block to see if bumped penalty are issued for HTLC txn
7197 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7198 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7200 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7201 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7203 check_spends!(node_txn[0], revoked_local_txn[0]);
7204 check_spends!(node_txn[1], revoked_local_txn[0]);
7209 // Few more blocks to confirm penalty txn
7210 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7211 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7212 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7214 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7215 assert_eq!(node_txn.len(), 1);
7217 assert_eq!(node_txn[0].input.len(), 2);
7218 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7219 // Verify bumped tx is different and 25% bump heuristic
7220 assert_ne!(first, node_txn[0].txid());
7221 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7222 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7223 assert!(feerate_2 * 100 > feerate_1 * 125);
7224 let txn = vec![node_txn[0].clone()];
7228 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7229 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7230 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7231 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7233 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7234 // We verify than no new transaction has been broadcast because previously
7235 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7236 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7237 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7238 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7239 // up bumped justice generation.
7240 assert_eq!(node_txn.len(), 0);
7243 check_closed_broadcast!(nodes[0], false);
7244 check_added_monitors!(nodes[0], 1);
7248 fn test_bump_penalty_txn_on_remote_commitment() {
7249 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7250 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7253 // Provide preimage for one
7254 // Check aggregation
7256 let chanmon_cfgs = create_chanmon_cfgs(2);
7257 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7258 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7259 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7261 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7262 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7263 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7265 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7266 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7267 assert_eq!(remote_txn[0].output.len(), 4);
7268 assert_eq!(remote_txn[0].input.len(), 1);
7269 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7271 // Claim a HTLC without revocation (provide B monitor with preimage)
7272 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7273 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7274 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7275 check_added_monitors!(nodes[1], 2);
7277 // One or more claim tx should have been broadcast, check it
7280 let feerate_timeout;
7281 let feerate_preimage;
7283 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7284 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7285 assert_eq!(node_txn[0].input.len(), 1);
7286 assert_eq!(node_txn[1].input.len(), 1);
7287 check_spends!(node_txn[0], remote_txn[0]);
7288 check_spends!(node_txn[1], remote_txn[0]);
7289 check_spends!(node_txn[2], chan.3);
7290 check_spends!(node_txn[3], node_txn[2]);
7291 check_spends!(node_txn[4], node_txn[2]);
7292 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7293 timeout = node_txn[0].txid();
7294 let index = node_txn[0].input[0].previous_output.vout;
7295 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7296 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7298 preimage = node_txn[1].txid();
7299 let index = node_txn[1].input[0].previous_output.vout;
7300 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7301 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7303 timeout = node_txn[1].txid();
7304 let index = node_txn[1].input[0].previous_output.vout;
7305 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7306 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7308 preimage = node_txn[0].txid();
7309 let index = node_txn[0].input[0].previous_output.vout;
7310 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7311 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7315 assert_ne!(feerate_timeout, 0);
7316 assert_ne!(feerate_preimage, 0);
7318 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7319 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7321 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7322 assert_eq!(node_txn.len(), 2);
7323 assert_eq!(node_txn[0].input.len(), 1);
7324 assert_eq!(node_txn[1].input.len(), 1);
7325 check_spends!(node_txn[0], remote_txn[0]);
7326 check_spends!(node_txn[1], remote_txn[0]);
7327 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7328 let index = node_txn[0].input[0].previous_output.vout;
7329 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7330 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7331 assert!(new_feerate * 100 > feerate_timeout * 125);
7332 assert_ne!(timeout, node_txn[0].txid());
7334 let index = node_txn[1].input[0].previous_output.vout;
7335 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7336 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7337 assert!(new_feerate * 100 > feerate_preimage * 125);
7338 assert_ne!(preimage, node_txn[1].txid());
7340 let index = node_txn[1].input[0].previous_output.vout;
7341 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7342 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7343 assert!(new_feerate * 100 > feerate_timeout * 125);
7344 assert_ne!(timeout, node_txn[1].txid());
7346 let index = node_txn[0].input[0].previous_output.vout;
7347 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7348 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7349 assert!(new_feerate * 100 > feerate_preimage * 125);
7350 assert_ne!(preimage, node_txn[0].txid());
7355 nodes[1].node.get_and_clear_pending_events();
7356 nodes[1].node.get_and_clear_pending_msg_events();
7360 fn test_set_outpoints_partial_claiming() {
7361 // - remote party claim tx, new bump tx
7362 // - disconnect remote claiming tx, new bump
7363 // - disconnect tx, see no tx anymore
7364 let chanmon_cfgs = create_chanmon_cfgs(2);
7365 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7366 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7367 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7369 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7370 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7371 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7373 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7374 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7375 assert_eq!(remote_txn.len(), 3);
7376 assert_eq!(remote_txn[0].output.len(), 4);
7377 assert_eq!(remote_txn[0].input.len(), 1);
7378 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7379 check_spends!(remote_txn[1], remote_txn[0]);
7380 check_spends!(remote_txn[2], remote_txn[0]);
7382 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7383 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7384 // Provide node A with both preimage
7385 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7386 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7387 check_added_monitors!(nodes[0], 2);
7388 nodes[0].node.get_and_clear_pending_events();
7389 nodes[0].node.get_and_clear_pending_msg_events();
7391 // Connect blocks on node A commitment transaction
7392 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7393 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7394 check_closed_broadcast!(nodes[0], false);
7395 check_added_monitors!(nodes[0], 1);
7396 // Verify node A broadcast tx claiming both HTLCs
7398 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7399 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7400 assert_eq!(node_txn.len(), 4);
7401 check_spends!(node_txn[0], remote_txn[0]);
7402 check_spends!(node_txn[1], chan.3);
7403 check_spends!(node_txn[2], node_txn[1]);
7404 check_spends!(node_txn[3], node_txn[1]);
7405 assert_eq!(node_txn[0].input.len(), 2);
7409 // Connect blocks on node B
7410 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7411 check_closed_broadcast!(nodes[1], false);
7412 check_added_monitors!(nodes[1], 1);
7413 // Verify node B broadcast 2 HTLC-timeout txn
7414 let partial_claim_tx = {
7415 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7416 assert_eq!(node_txn.len(), 3);
7417 check_spends!(node_txn[1], node_txn[0]);
7418 check_spends!(node_txn[2], node_txn[0]);
7419 assert_eq!(node_txn[1].input.len(), 1);
7420 assert_eq!(node_txn[2].input.len(), 1);
7424 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7425 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7426 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7428 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7429 assert_eq!(node_txn.len(), 1);
7430 check_spends!(node_txn[0], remote_txn[0]);
7431 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7434 nodes[0].node.get_and_clear_pending_msg_events();
7436 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7437 nodes[0].block_notifier.block_disconnected(&header, 102);
7439 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7440 assert_eq!(node_txn.len(), 1);
7441 check_spends!(node_txn[0], remote_txn[0]);
7442 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7446 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7447 nodes[0].block_notifier.block_disconnected(&header, 101);
7448 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7450 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7451 assert_eq!(node_txn.len(), 0);
7457 fn test_counterparty_raa_skip_no_crash() {
7458 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7459 // commitment transaction, we would have happily carried on and provided them the next
7460 // commitment transaction based on one RAA forward. This would probably eventually have led to
7461 // channel closure, but it would not have resulted in funds loss. Still, our
7462 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7463 // check simply that the channel is closed in response to such an RAA, but don't check whether
7464 // we decide to punish our counterparty for revoking their funds (as we don't currently
7466 let chanmon_cfgs = create_chanmon_cfgs(2);
7467 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7468 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7469 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7470 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7472 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7473 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7474 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7475 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7476 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7478 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7479 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7480 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7481 check_added_monitors!(nodes[1], 1);
7485 fn test_bump_txn_sanitize_tracking_maps() {
7486 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7487 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7489 let chanmon_cfgs = create_chanmon_cfgs(2);
7490 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7491 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7492 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7494 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7495 // Lock HTLC in both directions
7496 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7497 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7499 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7500 assert_eq!(revoked_local_txn[0].input.len(), 1);
7501 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7503 // Revoke local commitment tx
7504 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7506 // Broadcast set of revoked txn on A
7507 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7508 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7510 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7511 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7512 check_closed_broadcast!(nodes[0], false);
7513 check_added_monitors!(nodes[0], 1);
7515 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7516 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7517 check_spends!(node_txn[0], revoked_local_txn[0]);
7518 check_spends!(node_txn[1], revoked_local_txn[0]);
7519 check_spends!(node_txn[2], revoked_local_txn[0]);
7520 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7524 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7525 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7526 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7528 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7529 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7530 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7531 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7537 fn test_override_channel_config() {
7538 let chanmon_cfgs = create_chanmon_cfgs(2);
7539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7543 // Node0 initiates a channel to node1 using the override config.
7544 let mut override_config = UserConfig::default();
7545 override_config.own_channel_config.our_to_self_delay = 200;
7547 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7549 // Assert the channel created by node0 is using the override config.
7550 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7551 assert_eq!(res.channel_flags, 0);
7552 assert_eq!(res.to_self_delay, 200);
7556 fn test_override_0msat_htlc_minimum() {
7557 let mut zero_config = UserConfig::default();
7558 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7559 let chanmon_cfgs = create_chanmon_cfgs(2);
7560 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7561 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7562 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7564 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7565 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7566 assert_eq!(res.htlc_minimum_msat, 1);
7568 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7569 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7570 assert_eq!(res.htlc_minimum_msat, 1);
7574 fn test_simple_payment_secret() {
7575 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7576 // features, however.
7577 let chanmon_cfgs = create_chanmon_cfgs(3);
7578 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7579 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7580 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7582 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7583 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
7585 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7586 let payment_secret = PaymentSecret([0xdb; 32]);
7587 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
7588 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7589 // Claiming with all the correct values but the wrong secret should result in nothing...
7590 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7591 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7592 // ...but with the right secret we should be able to claim all the way back
7593 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7597 fn test_simple_mpp() {
7598 // Simple test of sending a multi-path payment.
7599 let chanmon_cfgs = create_chanmon_cfgs(4);
7600 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7601 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7602 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7604 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7605 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7606 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7607 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7609 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7610 let payment_secret = PaymentSecret([0xdb; 32]);
7611 let mut route = nodes[0].router.get_route(&nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
7612 let path = route.paths[0].clone();
7613 route.paths.push(path);
7614 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7615 route.paths[0][0].short_channel_id = chan_1_id;
7616 route.paths[0][1].short_channel_id = chan_3_id;
7617 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7618 route.paths[1][0].short_channel_id = chan_2_id;
7619 route.paths[1][1].short_channel_id = chan_4_id;
7620 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7621 // Claiming with all the correct values but the wrong secret should result in nothing...
7622 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7623 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7624 // ...but with the right secret we should be able to claim all the way back
7625 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7629 fn test_update_err_monitor_lockdown() {
7630 // Our monitor will lock update of local commitment transaction if a broadcastion condition
7631 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7632 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7634 // This scenario may happen in a watchtower setup, where watchtower process a block height
7635 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7636 // commitment at same time.
7638 let chanmon_cfgs = create_chanmon_cfgs(2);
7639 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7640 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7641 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7643 // Create some initial channel
7644 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7645 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7647 // Rebalance the network to generate htlc in the two directions
7648 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7650 // Route a HTLC from node 0 to node 1 (but don't settle)
7651 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7653 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7654 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
7656 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7657 let monitor = monitors.get(&outpoint).unwrap();
7658 let mut w = test_utils::TestVecWriter(Vec::new());
7659 monitor.write_for_disk(&mut w).unwrap();
7660 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7661 &mut ::std::io::Cursor::new(&w.0), Arc::new(test_utils::TestLogger::new())).unwrap().1;
7662 assert!(new_monitor == *monitor);
7663 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
7664 let watchtower = test_utils::TestChannelMonitor::new(chain_monitor, &chanmon_cfgs[0].tx_broadcaster, logger.clone(), &chanmon_cfgs[0].fee_estimator);
7665 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7668 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7669 watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7671 // Try to update ChannelMonitor
7672 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7673 check_added_monitors!(nodes[1], 1);
7674 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7675 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7676 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7677 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7678 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator) {
7679 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7680 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7681 } else { assert!(false); }
7682 } else { assert!(false); };
7683 // Our local monitor is in-sync and hasn't processed yet timeout
7684 check_added_monitors!(nodes[0], 1);
7685 let events = nodes[0].node.get_and_clear_pending_events();
7686 assert_eq!(events.len(), 1);