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::util::bip143;
30 use bitcoin::util::address::Address;
31 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
34 use bitcoin::blockdata::script::{Builder, Script};
35 use bitcoin::blockdata::opcodes;
36 use bitcoin::blockdata::constants::genesis_block;
37 use bitcoin::network::constants::Network;
39 use bitcoin_hashes::sha256::Hash as Sha256;
40 use bitcoin_hashes::Hash;
42 use secp256k1::{Secp256k1, Message};
43 use secp256k1::key::{PublicKey,SecretKey};
45 use std::collections::{BTreeSet, HashMap, HashSet};
46 use std::default::Default;
47 use std::sync::{Arc, Mutex};
48 use std::sync::atomic::Ordering;
51 use rand::{thread_rng, Rng};
53 use ln::functional_test_utils::*;
56 fn test_insane_channel_opens() {
57 // Stand up a network of 2 nodes
58 let chanmon_cfgs = create_chanmon_cfgs(2);
59 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
60 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
61 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
63 // Instantiate channel parameters where we push the maximum msats given our
65 let channel_value_sat = 31337; // same as funding satoshis
66 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_our_channel_reserve_satoshis(channel_value_sat);
67 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
69 // Have node0 initiate a channel to node1 with aforementioned parameters
70 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
72 // Extract the channel open message from node0 to node1
73 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
75 // Test helper that asserts we get the correct error string given a mutator
76 // that supposedly makes the channel open message insane
77 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
78 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &message_mutator(open_channel_message.clone()));
79 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
80 assert_eq!(msg_events.len(), 1);
81 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
83 &ErrorAction::SendErrorMessage { .. } => {
84 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
86 _ => panic!("unexpected event!"),
88 } else { assert!(false); }
91 use ln::channel::MAX_FUNDING_SATOSHIS;
92 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
94 // Test all mutations that would make the channel open message insane
95 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
97 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
99 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
101 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
103 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
105 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 });
107 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 });
109 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
111 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
115 fn test_async_inbound_update_fee() {
116 let chanmon_cfgs = create_chanmon_cfgs(2);
117 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
118 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
119 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
120 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
121 let channel_id = chan.2;
124 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
128 // send (1) commitment_signed -.
129 // <- update_add_htlc/commitment_signed
130 // send (2) RAA (awaiting remote revoke) -.
131 // (1) commitment_signed is delivered ->
132 // .- send (3) RAA (awaiting remote revoke)
133 // (2) RAA is delivered ->
134 // .- send (4) commitment_signed
135 // <- (3) RAA is delivered
136 // send (5) commitment_signed -.
137 // <- (4) commitment_signed is delivered
139 // (5) commitment_signed is delivered ->
141 // (6) RAA is delivered ->
143 // First nodes[0] generates an update_fee
144 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
145 check_added_monitors!(nodes[0], 1);
147 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
148 assert_eq!(events_0.len(), 1);
149 let (update_msg, commitment_signed) = match events_0[0] { // (1)
150 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
151 (update_fee.as_ref(), commitment_signed)
153 _ => panic!("Unexpected event"),
156 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
158 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
159 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
160 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();
161 check_added_monitors!(nodes[1], 1);
163 let payment_event = {
164 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
165 assert_eq!(events_1.len(), 1);
166 SendEvent::from_event(events_1.remove(0))
168 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
169 assert_eq!(payment_event.msgs.len(), 1);
171 // ...now when the messages get delivered everyone should be happy
172 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
173 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
174 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
175 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
176 check_added_monitors!(nodes[0], 1);
178 // deliver(1), generate (3):
179 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
180 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
181 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
182 check_added_monitors!(nodes[1], 1);
184 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
185 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
186 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
187 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
188 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
189 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
190 assert!(bs_update.update_fee.is_none()); // (4)
191 check_added_monitors!(nodes[1], 1);
193 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
194 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
195 assert!(as_update.update_add_htlcs.is_empty()); // (5)
196 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
197 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
198 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
199 assert!(as_update.update_fee.is_none()); // (5)
200 check_added_monitors!(nodes[0], 1);
202 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
203 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
204 // only (6) so get_event_msg's assert(len == 1) passes
205 check_added_monitors!(nodes[0], 1);
207 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
208 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
209 check_added_monitors!(nodes[1], 1);
211 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
212 check_added_monitors!(nodes[0], 1);
214 let events_2 = nodes[0].node.get_and_clear_pending_events();
215 assert_eq!(events_2.len(), 1);
217 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
218 _ => panic!("Unexpected event"),
221 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
222 check_added_monitors!(nodes[1], 1);
226 fn test_update_fee_unordered_raa() {
227 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
228 // crash in an earlier version of the update_fee patch)
229 let chanmon_cfgs = create_chanmon_cfgs(2);
230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
232 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
233 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
234 let channel_id = chan.2;
237 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
239 // First nodes[0] generates an update_fee
240 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
241 check_added_monitors!(nodes[0], 1);
243 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
244 assert_eq!(events_0.len(), 1);
245 let update_msg = match events_0[0] { // (1)
246 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
249 _ => panic!("Unexpected event"),
252 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
254 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
255 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
256 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();
257 check_added_monitors!(nodes[1], 1);
259 let payment_event = {
260 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
261 assert_eq!(events_1.len(), 1);
262 SendEvent::from_event(events_1.remove(0))
264 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
265 assert_eq!(payment_event.msgs.len(), 1);
267 // ...now when the messages get delivered everyone should be happy
268 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
269 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
270 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
271 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
272 check_added_monitors!(nodes[0], 1);
274 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
275 check_added_monitors!(nodes[1], 1);
277 // We can't continue, sadly, because our (1) now has a bogus signature
281 fn test_multi_flight_update_fee() {
282 let chanmon_cfgs = create_chanmon_cfgs(2);
283 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
284 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
285 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
286 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
287 let channel_id = chan.2;
290 // update_fee/commitment_signed ->
291 // .- send (1) RAA and (2) commitment_signed
292 // update_fee (never committed) ->
294 // We have to manually generate the above update_fee, it is allowed by the protocol but we
295 // don't track which updates correspond to which revoke_and_ack responses so we're in
296 // AwaitingRAA mode and will not generate the update_fee yet.
297 // <- (1) RAA delivered
298 // (3) is generated and send (4) CS -.
299 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
300 // know the per_commitment_point to use for it.
301 // <- (2) commitment_signed delivered
303 // B should send no response here
304 // (4) commitment_signed delivered ->
305 // <- RAA/commitment_signed delivered
308 // First nodes[0] generates an update_fee
309 let initial_feerate = get_feerate!(nodes[0], channel_id);
310 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
311 check_added_monitors!(nodes[0], 1);
313 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
314 assert_eq!(events_0.len(), 1);
315 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
316 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
317 (update_fee.as_ref().unwrap(), commitment_signed)
319 _ => panic!("Unexpected event"),
322 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
323 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
324 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
325 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
326 check_added_monitors!(nodes[1], 1);
328 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
330 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
331 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
332 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
334 // Create the (3) update_fee message that nodes[0] will generate before it does...
335 let mut update_msg_2 = msgs::UpdateFee {
336 channel_id: update_msg_1.channel_id.clone(),
337 feerate_per_kw: (initial_feerate + 30) as u32,
340 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
342 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
344 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
346 // Deliver (1), generating (3) and (4)
347 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
348 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
349 check_added_monitors!(nodes[0], 1);
350 assert!(as_second_update.update_add_htlcs.is_empty());
351 assert!(as_second_update.update_fulfill_htlcs.is_empty());
352 assert!(as_second_update.update_fail_htlcs.is_empty());
353 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
354 // Check that the update_fee newly generated matches what we delivered:
355 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
356 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
358 // Deliver (2) commitment_signed
359 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
360 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
361 check_added_monitors!(nodes[0], 1);
362 // No commitment_signed so get_event_msg's assert(len == 1) passes
364 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
365 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
366 check_added_monitors!(nodes[1], 1);
369 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
370 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
371 check_added_monitors!(nodes[1], 1);
373 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
375 check_added_monitors!(nodes[0], 1);
377 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
378 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
379 // No commitment_signed so get_event_msg's assert(len == 1) passes
380 check_added_monitors!(nodes[0], 1);
382 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
383 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
384 check_added_monitors!(nodes[1], 1);
388 fn test_1_conf_open() {
389 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
390 // tests that we properly send one in that case.
391 let mut alice_config = UserConfig::default();
392 alice_config.own_channel_config.minimum_depth = 1;
393 alice_config.channel_options.announced_channel = true;
394 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
395 let mut bob_config = UserConfig::default();
396 bob_config.own_channel_config.minimum_depth = 1;
397 bob_config.channel_options.announced_channel = true;
398 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
399 let chanmon_cfgs = create_chanmon_cfgs(2);
400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
404 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
405 assert!(nodes[0].chain_monitor.does_match_tx(&tx));
406 assert!(nodes[1].chain_monitor.does_match_tx(&tx));
408 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
409 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
410 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()));
412 nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
413 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
414 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
417 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
418 node.router.handle_channel_update(&as_update).unwrap();
419 node.router.handle_channel_update(&bs_update).unwrap();
423 fn do_test_sanity_on_in_flight_opens(steps: u8) {
424 // Previously, we had issues deserializing channels when we hadn't connected the first block
425 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
426 // serialization round-trips and simply do steps towards opening a channel and then drop the
429 let chanmon_cfgs = create_chanmon_cfgs(2);
430 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
431 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
432 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
434 if steps & 0b1000_0000 != 0{
435 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
436 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
437 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
440 if steps & 0x0f == 0 { return; }
441 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
442 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
444 if steps & 0x0f == 1 { return; }
445 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &open_channel);
446 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
448 if steps & 0x0f == 2 { return; }
449 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
451 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
453 if steps & 0x0f == 3 { return; }
454 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
455 check_added_monitors!(nodes[0], 0);
456 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
458 if steps & 0x0f == 4 { return; }
459 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
461 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
462 assert_eq!(added_monitors.len(), 1);
463 assert_eq!(added_monitors[0].0, funding_output);
464 added_monitors.clear();
466 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
468 if steps & 0x0f == 5 { return; }
469 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
471 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
472 assert_eq!(added_monitors.len(), 1);
473 assert_eq!(added_monitors[0].0, funding_output);
474 added_monitors.clear();
477 let events_4 = nodes[0].node.get_and_clear_pending_events();
478 assert_eq!(events_4.len(), 1);
480 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
481 assert_eq!(user_channel_id, 42);
482 assert_eq!(*funding_txo, funding_output);
484 _ => panic!("Unexpected event"),
487 if steps & 0x0f == 6 { return; }
488 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
490 if steps & 0x0f == 7 { return; }
491 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
492 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
496 fn test_sanity_on_in_flight_opens() {
497 do_test_sanity_on_in_flight_opens(0);
498 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
499 do_test_sanity_on_in_flight_opens(1);
500 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
501 do_test_sanity_on_in_flight_opens(2);
502 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
503 do_test_sanity_on_in_flight_opens(3);
504 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
505 do_test_sanity_on_in_flight_opens(4);
506 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
507 do_test_sanity_on_in_flight_opens(5);
508 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
509 do_test_sanity_on_in_flight_opens(6);
510 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
511 do_test_sanity_on_in_flight_opens(7);
512 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
513 do_test_sanity_on_in_flight_opens(8);
514 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
518 fn test_update_fee_vanilla() {
519 let chanmon_cfgs = create_chanmon_cfgs(2);
520 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
521 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
522 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
523 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
524 let channel_id = chan.2;
526 let feerate = get_feerate!(nodes[0], channel_id);
527 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
528 check_added_monitors!(nodes[0], 1);
530 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
531 assert_eq!(events_0.len(), 1);
532 let (update_msg, commitment_signed) = match events_0[0] {
533 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 } } => {
534 (update_fee.as_ref(), commitment_signed)
536 _ => panic!("Unexpected event"),
538 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
540 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
541 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
542 check_added_monitors!(nodes[1], 1);
544 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
545 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
546 check_added_monitors!(nodes[0], 1);
548 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
549 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
550 // No commitment_signed so get_event_msg's assert(len == 1) passes
551 check_added_monitors!(nodes[0], 1);
553 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
554 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
555 check_added_monitors!(nodes[1], 1);
559 fn test_update_fee_that_funder_cannot_afford() {
560 let chanmon_cfgs = create_chanmon_cfgs(2);
561 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
562 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
563 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
564 let channel_value = 1888;
565 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::supported(), InitFeatures::supported());
566 let channel_id = chan.2;
569 nodes[0].node.update_fee(channel_id, feerate).unwrap();
570 check_added_monitors!(nodes[0], 1);
571 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
573 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
575 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
577 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
578 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
580 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
582 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
583 let num_htlcs = commitment_tx.output.len() - 2;
584 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
585 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
586 actual_fee = channel_value - actual_fee;
587 assert_eq!(total_fee, actual_fee);
590 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
591 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
592 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
593 check_added_monitors!(nodes[0], 1);
595 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
597 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
599 //While producing the commitment_signed response after handling a received update_fee request the
600 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
601 //Should produce and error.
602 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
603 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
604 check_added_monitors!(nodes[1], 1);
605 check_closed_broadcast!(nodes[1], true);
609 fn test_update_fee_with_fundee_update_add_htlc() {
610 let chanmon_cfgs = create_chanmon_cfgs(2);
611 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
612 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
613 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
614 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
615 let channel_id = chan.2;
618 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
620 let feerate = get_feerate!(nodes[0], channel_id);
621 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
622 check_added_monitors!(nodes[0], 1);
624 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
625 assert_eq!(events_0.len(), 1);
626 let (update_msg, commitment_signed) = match events_0[0] {
627 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 } } => {
628 (update_fee.as_ref(), commitment_signed)
630 _ => panic!("Unexpected event"),
632 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
633 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
634 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
635 check_added_monitors!(nodes[1], 1);
637 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
639 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
641 // nothing happens since node[1] is in AwaitingRemoteRevoke
642 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
644 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
645 assert_eq!(added_monitors.len(), 0);
646 added_monitors.clear();
648 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
649 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
650 // node[1] has nothing to do
652 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
653 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
654 check_added_monitors!(nodes[0], 1);
656 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
657 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
658 // No commitment_signed so get_event_msg's assert(len == 1) passes
659 check_added_monitors!(nodes[0], 1);
660 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
661 check_added_monitors!(nodes[1], 1);
662 // AwaitingRemoteRevoke ends here
664 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
665 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
666 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
667 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
668 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
669 assert_eq!(commitment_update.update_fee.is_none(), true);
671 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
672 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
673 check_added_monitors!(nodes[0], 1);
674 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
676 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
677 check_added_monitors!(nodes[1], 1);
678 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
680 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
681 check_added_monitors!(nodes[1], 1);
682 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
683 // No commitment_signed so get_event_msg's assert(len == 1) passes
685 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
686 check_added_monitors!(nodes[0], 1);
687 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
689 expect_pending_htlcs_forwardable!(nodes[0]);
691 let events = nodes[0].node.get_and_clear_pending_events();
692 assert_eq!(events.len(), 1);
694 Event::PaymentReceived { .. } => { },
695 _ => panic!("Unexpected event"),
698 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
700 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
701 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
702 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
706 fn test_update_fee() {
707 let chanmon_cfgs = create_chanmon_cfgs(2);
708 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
709 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
710 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
711 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
712 let channel_id = chan.2;
715 // (1) update_fee/commitment_signed ->
716 // <- (2) revoke_and_ack
717 // .- send (3) commitment_signed
718 // (4) update_fee/commitment_signed ->
719 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
720 // <- (3) commitment_signed delivered
721 // send (6) revoke_and_ack -.
722 // <- (5) deliver revoke_and_ack
723 // (6) deliver revoke_and_ack ->
724 // .- send (7) commitment_signed in response to (4)
725 // <- (7) deliver commitment_signed
728 // Create and deliver (1)...
729 let feerate = get_feerate!(nodes[0], channel_id);
730 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
731 check_added_monitors!(nodes[0], 1);
733 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
734 assert_eq!(events_0.len(), 1);
735 let (update_msg, commitment_signed) = match events_0[0] {
736 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 } } => {
737 (update_fee.as_ref(), commitment_signed)
739 _ => panic!("Unexpected event"),
741 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
743 // Generate (2) and (3):
744 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
745 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
746 check_added_monitors!(nodes[1], 1);
749 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
750 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
751 check_added_monitors!(nodes[0], 1);
753 // Create and deliver (4)...
754 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
755 check_added_monitors!(nodes[0], 1);
756 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
757 assert_eq!(events_0.len(), 1);
758 let (update_msg, commitment_signed) = match events_0[0] {
759 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 } } => {
760 (update_fee.as_ref(), commitment_signed)
762 _ => panic!("Unexpected event"),
765 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
766 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
767 check_added_monitors!(nodes[1], 1);
769 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
770 // No commitment_signed so get_event_msg's assert(len == 1) passes
772 // Handle (3), creating (6):
773 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
774 check_added_monitors!(nodes[0], 1);
775 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
776 // No commitment_signed so get_event_msg's assert(len == 1) passes
779 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
780 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
781 check_added_monitors!(nodes[0], 1);
783 // Deliver (6), creating (7):
784 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
785 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
786 assert!(commitment_update.update_add_htlcs.is_empty());
787 assert!(commitment_update.update_fulfill_htlcs.is_empty());
788 assert!(commitment_update.update_fail_htlcs.is_empty());
789 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
790 assert!(commitment_update.update_fee.is_none());
791 check_added_monitors!(nodes[1], 1);
794 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
795 check_added_monitors!(nodes[0], 1);
796 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
797 // No commitment_signed so get_event_msg's assert(len == 1) passes
799 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
800 check_added_monitors!(nodes[1], 1);
801 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
803 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
804 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
805 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
809 fn pre_funding_lock_shutdown_test() {
810 // Test sending a shutdown prior to funding_locked after funding generation
811 let chanmon_cfgs = create_chanmon_cfgs(2);
812 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
813 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
814 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
815 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::supported(), InitFeatures::supported());
816 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
817 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
818 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
820 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
821 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
822 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
823 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
824 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
826 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
827 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
828 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
829 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
830 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
831 assert!(node_0_none.is_none());
833 assert!(nodes[0].node.list_channels().is_empty());
834 assert!(nodes[1].node.list_channels().is_empty());
838 fn updates_shutdown_wait() {
839 // Test sending a shutdown with outstanding updates pending
840 let chanmon_cfgs = create_chanmon_cfgs(3);
841 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
842 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
843 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
844 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
845 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
846 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
847 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
849 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
851 nodes[0].node.close_channel(&chan_1.2).unwrap();
852 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
853 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
854 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
855 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
857 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
858 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
860 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
861 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
862 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
864 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
865 check_added_monitors!(nodes[2], 1);
866 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
867 assert!(updates.update_add_htlcs.is_empty());
868 assert!(updates.update_fail_htlcs.is_empty());
869 assert!(updates.update_fail_malformed_htlcs.is_empty());
870 assert!(updates.update_fee.is_none());
871 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
872 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
873 check_added_monitors!(nodes[1], 1);
874 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
875 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
877 assert!(updates_2.update_add_htlcs.is_empty());
878 assert!(updates_2.update_fail_htlcs.is_empty());
879 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
880 assert!(updates_2.update_fee.is_none());
881 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
882 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
883 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
885 let events = nodes[0].node.get_and_clear_pending_events();
886 assert_eq!(events.len(), 1);
888 Event::PaymentSent { ref payment_preimage } => {
889 assert_eq!(our_payment_preimage, *payment_preimage);
891 _ => panic!("Unexpected event"),
894 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
895 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
896 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
897 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
898 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
899 assert!(node_0_none.is_none());
901 assert!(nodes[0].node.list_channels().is_empty());
903 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
904 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
905 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
906 assert!(nodes[1].node.list_channels().is_empty());
907 assert!(nodes[2].node.list_channels().is_empty());
911 fn htlc_fail_async_shutdown() {
912 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
913 let chanmon_cfgs = create_chanmon_cfgs(3);
914 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
915 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
916 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
917 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
918 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
920 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
921 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
922 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
923 check_added_monitors!(nodes[0], 1);
924 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
925 assert_eq!(updates.update_add_htlcs.len(), 1);
926 assert!(updates.update_fulfill_htlcs.is_empty());
927 assert!(updates.update_fail_htlcs.is_empty());
928 assert!(updates.update_fail_malformed_htlcs.is_empty());
929 assert!(updates.update_fee.is_none());
931 nodes[1].node.close_channel(&chan_1.2).unwrap();
932 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
933 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
934 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
936 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
937 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
938 check_added_monitors!(nodes[1], 1);
939 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
940 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
942 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
943 assert!(updates_2.update_add_htlcs.is_empty());
944 assert!(updates_2.update_fulfill_htlcs.is_empty());
945 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
946 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
947 assert!(updates_2.update_fee.is_none());
949 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
950 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
952 expect_payment_failed!(nodes[0], our_payment_hash, false);
954 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
955 assert_eq!(msg_events.len(), 2);
956 let node_0_closing_signed = match msg_events[0] {
957 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
958 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
961 _ => panic!("Unexpected event"),
963 match msg_events[1] {
964 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
965 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
967 _ => panic!("Unexpected event"),
970 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
971 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
972 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
973 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
974 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
975 assert!(node_0_none.is_none());
977 assert!(nodes[0].node.list_channels().is_empty());
979 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
980 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
981 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
982 assert!(nodes[1].node.list_channels().is_empty());
983 assert!(nodes[2].node.list_channels().is_empty());
986 fn do_test_shutdown_rebroadcast(recv_count: u8) {
987 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
988 // messages delivered prior to disconnect
989 let chanmon_cfgs = create_chanmon_cfgs(3);
990 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
991 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
992 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
993 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
994 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
996 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
998 nodes[1].node.close_channel(&chan_1.2).unwrap();
999 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1001 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1002 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1004 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1008 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1009 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1011 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1012 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1013 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1014 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1016 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1017 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1018 assert!(node_1_shutdown == node_1_2nd_shutdown);
1020 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1021 let node_0_2nd_shutdown = if recv_count > 0 {
1022 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1023 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1026 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1027 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1028 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1030 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1032 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1033 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1035 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1036 check_added_monitors!(nodes[2], 1);
1037 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1038 assert!(updates.update_add_htlcs.is_empty());
1039 assert!(updates.update_fail_htlcs.is_empty());
1040 assert!(updates.update_fail_malformed_htlcs.is_empty());
1041 assert!(updates.update_fee.is_none());
1042 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1043 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1044 check_added_monitors!(nodes[1], 1);
1045 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1046 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1048 assert!(updates_2.update_add_htlcs.is_empty());
1049 assert!(updates_2.update_fail_htlcs.is_empty());
1050 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1051 assert!(updates_2.update_fee.is_none());
1052 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1053 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1054 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1056 let events = nodes[0].node.get_and_clear_pending_events();
1057 assert_eq!(events.len(), 1);
1059 Event::PaymentSent { ref payment_preimage } => {
1060 assert_eq!(our_payment_preimage, *payment_preimage);
1062 _ => panic!("Unexpected event"),
1065 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1067 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1068 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1069 assert!(node_1_closing_signed.is_some());
1072 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1073 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1075 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1076 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1077 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1078 if recv_count == 0 {
1079 // If all closing_signeds weren't delivered we can just resume where we left off...
1080 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1082 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1083 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1084 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1086 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1087 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1088 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1090 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1091 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1093 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1094 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1095 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1097 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1098 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1099 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1100 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1101 assert!(node_0_none.is_none());
1103 // If one node, however, received + responded with an identical closing_signed we end
1104 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1105 // There isn't really anything better we can do simply, but in the future we might
1106 // explore storing a set of recently-closed channels that got disconnected during
1107 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1108 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1110 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1112 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1113 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1114 assert_eq!(msg_events.len(), 1);
1115 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1117 &ErrorAction::SendErrorMessage { ref msg } => {
1118 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1119 assert_eq!(msg.channel_id, chan_1.2);
1121 _ => panic!("Unexpected event!"),
1123 } else { panic!("Needed SendErrorMessage close"); }
1125 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1126 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1127 // closing_signed so we do it ourselves
1128 check_closed_broadcast!(nodes[0], false);
1129 check_added_monitors!(nodes[0], 1);
1132 assert!(nodes[0].node.list_channels().is_empty());
1134 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1135 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1136 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1137 assert!(nodes[1].node.list_channels().is_empty());
1138 assert!(nodes[2].node.list_channels().is_empty());
1142 fn test_shutdown_rebroadcast() {
1143 do_test_shutdown_rebroadcast(0);
1144 do_test_shutdown_rebroadcast(1);
1145 do_test_shutdown_rebroadcast(2);
1149 fn fake_network_test() {
1150 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1151 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1152 let chanmon_cfgs = create_chanmon_cfgs(4);
1153 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1154 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1155 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1157 // Create some initial channels
1158 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1159 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1160 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1162 // Rebalance the network a bit by relaying one payment through all the channels...
1163 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
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);
1168 // Send some more payments
1169 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1170 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1171 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1173 // Test failure packets
1174 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1175 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1177 // Add a new channel that skips 3
1178 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1180 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1181 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1182 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_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);
1188 // Do some rebalance loop payments, simultaneously
1189 let mut hops = Vec::with_capacity(3);
1190 hops.push(RouteHop {
1191 pubkey: nodes[2].node.get_our_node_id(),
1192 node_features: NodeFeatures::empty(),
1193 short_channel_id: chan_2.0.contents.short_channel_id,
1194 channel_features: ChannelFeatures::empty(),
1196 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1198 hops.push(RouteHop {
1199 pubkey: nodes[3].node.get_our_node_id(),
1200 node_features: NodeFeatures::empty(),
1201 short_channel_id: chan_3.0.contents.short_channel_id,
1202 channel_features: ChannelFeatures::empty(),
1204 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1206 hops.push(RouteHop {
1207 pubkey: nodes[1].node.get_our_node_id(),
1208 node_features: NodeFeatures::empty(),
1209 short_channel_id: chan_4.0.contents.short_channel_id,
1210 channel_features: ChannelFeatures::empty(),
1212 cltv_expiry_delta: TEST_FINAL_CLTV,
1214 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;
1215 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;
1216 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1218 let mut hops = Vec::with_capacity(3);
1219 hops.push(RouteHop {
1220 pubkey: nodes[3].node.get_our_node_id(),
1221 node_features: NodeFeatures::empty(),
1222 short_channel_id: chan_4.0.contents.short_channel_id,
1223 channel_features: ChannelFeatures::empty(),
1225 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1227 hops.push(RouteHop {
1228 pubkey: nodes[2].node.get_our_node_id(),
1229 node_features: NodeFeatures::empty(),
1230 short_channel_id: chan_3.0.contents.short_channel_id,
1231 channel_features: ChannelFeatures::empty(),
1233 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1235 hops.push(RouteHop {
1236 pubkey: nodes[1].node.get_our_node_id(),
1237 node_features: NodeFeatures::empty(),
1238 short_channel_id: chan_2.0.contents.short_channel_id,
1239 channel_features: ChannelFeatures::empty(),
1241 cltv_expiry_delta: TEST_FINAL_CLTV,
1243 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;
1244 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;
1245 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1247 // Claim the rebalances...
1248 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1249 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1251 // Add a duplicate new channel from 2 to 4
1252 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1254 // Send some payments across both channels
1255 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1256 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1257 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1260 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1261 let events = nodes[0].node.get_and_clear_pending_msg_events();
1262 assert_eq!(events.len(), 0);
1263 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);
1265 //TODO: Test that routes work again here as we've been notified that the channel is full
1267 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1268 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1269 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1271 // Close down the channels...
1272 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1273 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1274 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1275 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1276 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1280 fn holding_cell_htlc_counting() {
1281 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1282 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1283 // commitment dance rounds.
1284 let chanmon_cfgs = create_chanmon_cfgs(3);
1285 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1286 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1287 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1288 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1289 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1291 let mut payments = Vec::new();
1292 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1293 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1294 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1295 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1296 payments.push((payment_preimage, payment_hash));
1298 check_added_monitors!(nodes[1], 1);
1300 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1301 assert_eq!(events.len(), 1);
1302 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1303 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1305 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1306 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1308 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1309 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1310 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1311 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1312 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1313 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1315 // This should also be true if we try to forward a payment.
1316 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1317 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1318 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1319 check_added_monitors!(nodes[0], 1);
1321 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1322 assert_eq!(events.len(), 1);
1323 let payment_event = SendEvent::from_event(events.pop().unwrap());
1324 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1326 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1327 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1328 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1329 // fails), the second will process the resulting failure and fail the HTLC backward.
1330 expect_pending_htlcs_forwardable!(nodes[1]);
1331 expect_pending_htlcs_forwardable!(nodes[1]);
1332 check_added_monitors!(nodes[1], 1);
1334 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1335 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1336 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1338 let events = nodes[0].node.get_and_clear_pending_msg_events();
1339 assert_eq!(events.len(), 1);
1341 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1342 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1344 _ => panic!("Unexpected event"),
1347 expect_payment_failed!(nodes[0], payment_hash_2, false);
1349 // Now forward all the pending HTLCs and claim them back
1350 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1351 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1352 check_added_monitors!(nodes[2], 1);
1354 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1355 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1356 check_added_monitors!(nodes[1], 1);
1357 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1359 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1360 check_added_monitors!(nodes[1], 1);
1361 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1363 for ref update in as_updates.update_add_htlcs.iter() {
1364 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1366 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1367 check_added_monitors!(nodes[2], 1);
1368 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1369 check_added_monitors!(nodes[2], 1);
1370 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1372 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1373 check_added_monitors!(nodes[1], 1);
1374 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1375 check_added_monitors!(nodes[1], 1);
1376 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1378 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1379 check_added_monitors!(nodes[2], 1);
1381 expect_pending_htlcs_forwardable!(nodes[2]);
1383 let events = nodes[2].node.get_and_clear_pending_events();
1384 assert_eq!(events.len(), payments.len());
1385 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1387 &Event::PaymentReceived { ref payment_hash, .. } => {
1388 assert_eq!(*payment_hash, *hash);
1390 _ => panic!("Unexpected event"),
1394 for (preimage, _) in payments.drain(..) {
1395 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1398 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1402 fn duplicate_htlc_test() {
1403 // Test that we accept duplicate payment_hash HTLCs across the network and that
1404 // claiming/failing them are all separate and don't affect each other
1405 let chanmon_cfgs = create_chanmon_cfgs(6);
1406 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1407 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1408 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1410 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1411 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
1412 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1413 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1414 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1415 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
1417 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1419 *nodes[0].network_payment_count.borrow_mut() -= 1;
1420 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1422 *nodes[0].network_payment_count.borrow_mut() -= 1;
1423 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1425 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1426 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1427 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1431 fn test_duplicate_htlc_different_direction_onchain() {
1432 // Test that ChannelMonitor doesn't generate 2 preimage txn
1433 // when we have 2 HTLCs with same preimage that go across a node
1434 // in opposite directions.
1435 let chanmon_cfgs = create_chanmon_cfgs(2);
1436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1440 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1443 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1445 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1447 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1448 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1450 // Provide preimage to node 0 by claiming payment
1451 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1452 check_added_monitors!(nodes[0], 1);
1454 // Broadcast node 1 commitment txn
1455 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1457 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1458 let mut has_both_htlcs = 0; // check htlcs match ones committed
1459 for outp in remote_txn[0].output.iter() {
1460 if outp.value == 800_000 / 1000 {
1461 has_both_htlcs += 1;
1462 } else if outp.value == 900_000 / 1000 {
1463 has_both_htlcs += 1;
1466 assert_eq!(has_both_htlcs, 2);
1468 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1469 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1470 check_added_monitors!(nodes[0], 1);
1472 // Check we only broadcast 1 timeout tx
1473 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1474 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()) };
1475 assert_eq!(claim_txn.len(), 5);
1476 check_spends!(claim_txn[2], chan_1.3);
1477 check_spends!(claim_txn[3], claim_txn[2]);
1478 assert_eq!(htlc_pair.0.input.len(), 1);
1479 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1480 check_spends!(htlc_pair.0, remote_txn[0]);
1481 assert_eq!(htlc_pair.1.input.len(), 1);
1482 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1483 check_spends!(htlc_pair.1, remote_txn[0]);
1485 let events = nodes[0].node.get_and_clear_pending_msg_events();
1486 assert_eq!(events.len(), 2);
1489 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1490 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, .. } } => {
1491 assert!(update_add_htlcs.is_empty());
1492 assert!(update_fail_htlcs.is_empty());
1493 assert_eq!(update_fulfill_htlcs.len(), 1);
1494 assert!(update_fail_malformed_htlcs.is_empty());
1495 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1497 _ => panic!("Unexpected event"),
1502 fn do_channel_reserve_test(test_recv: bool) {
1504 let chanmon_cfgs = create_chanmon_cfgs(3);
1505 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1506 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1507 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1508 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
1509 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
1511 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1512 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1514 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1515 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1517 macro_rules! get_route_and_payment_hash {
1518 ($recv_value: expr) => {{
1519 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1520 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1521 (route, payment_hash, payment_preimage)
1525 macro_rules! expect_forward {
1527 let mut events = $node.node.get_and_clear_pending_msg_events();
1528 assert_eq!(events.len(), 1);
1529 check_added_monitors!($node, 1);
1530 let payment_event = SendEvent::from_event(events.remove(0));
1535 let feemsat = 239; // somehow we know?
1536 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1538 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1540 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1542 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1543 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1544 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1545 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1546 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1547 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);
1550 let mut htlc_id = 0;
1551 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1552 // nodes[0]'s wealth
1554 let amt_msat = recv_value_0 + total_fee_msat;
1555 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1558 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1561 let (stat01_, stat11_, stat12_, stat22_) = (
1562 get_channel_value_stat!(nodes[0], chan_1.2),
1563 get_channel_value_stat!(nodes[1], chan_1.2),
1564 get_channel_value_stat!(nodes[1], chan_2.2),
1565 get_channel_value_stat!(nodes[2], chan_2.2),
1568 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1569 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1570 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1571 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1572 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1576 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1577 // attempt to get channel_reserve violation
1578 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1579 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1580 assert_eq!(err, "Cannot send value that would put us over their reserve value"));
1581 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1582 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 1);
1585 // adding pending output
1586 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1587 let amt_msat_1 = recv_value_1 + total_fee_msat;
1589 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1590 let payment_event_1 = {
1591 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1592 check_added_monitors!(nodes[0], 1);
1594 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1595 assert_eq!(events.len(), 1);
1596 SendEvent::from_event(events.remove(0))
1598 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1600 // channel reserve test with htlc pending output > 0
1601 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1603 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1604 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1605 assert_eq!(err, "Cannot send value that would put us over their reserve value"));
1606 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1607 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 2);
1611 // test channel_reserve test on nodes[1] side
1612 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1614 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1615 let secp_ctx = Secp256k1::new();
1616 let session_priv = SecretKey::from_slice(&{
1617 let mut session_key = [0; 32];
1618 let mut rng = thread_rng();
1619 rng.fill_bytes(&mut session_key);
1621 }).expect("RNG is bad!");
1623 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1624 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1625 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1626 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1627 let msg = msgs::UpdateAddHTLC {
1628 channel_id: chan_1.2,
1630 amount_msat: htlc_msat,
1631 payment_hash: our_payment_hash,
1632 cltv_expiry: htlc_cltv,
1633 onion_routing_packet: onion_packet,
1637 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1638 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1639 assert_eq!(nodes[1].node.list_channels().len(), 1);
1640 assert_eq!(nodes[1].node.list_channels().len(), 1);
1641 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1642 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
1643 check_added_monitors!(nodes[1], 1);
1648 // split the rest to test holding cell
1649 let recv_value_21 = recv_value_2/2;
1650 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1652 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1653 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);
1656 // now see if they go through on both sides
1657 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1658 // but this will stuck in the holding cell
1659 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1660 check_added_monitors!(nodes[0], 0);
1661 let events = nodes[0].node.get_and_clear_pending_events();
1662 assert_eq!(events.len(), 0);
1664 // test with outbound holding cell amount > 0
1666 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1667 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1668 assert_eq!(err, "Cannot send value that would put us over their reserve value"));
1669 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1670 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 3);
1673 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1674 // this will also stuck in the holding cell
1675 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1676 check_added_monitors!(nodes[0], 0);
1677 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1678 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1680 // flush the pending htlc
1681 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1682 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1683 check_added_monitors!(nodes[1], 1);
1685 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1686 check_added_monitors!(nodes[0], 1);
1687 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1689 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1690 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1691 // No commitment_signed so get_event_msg's assert(len == 1) passes
1692 check_added_monitors!(nodes[0], 1);
1694 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1695 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1696 check_added_monitors!(nodes[1], 1);
1698 expect_pending_htlcs_forwardable!(nodes[1]);
1700 let ref payment_event_11 = expect_forward!(nodes[1]);
1701 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1702 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1704 expect_pending_htlcs_forwardable!(nodes[2]);
1705 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1707 // flush the htlcs in the holding cell
1708 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1709 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1710 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1711 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1712 expect_pending_htlcs_forwardable!(nodes[1]);
1714 let ref payment_event_3 = expect_forward!(nodes[1]);
1715 assert_eq!(payment_event_3.msgs.len(), 2);
1716 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1717 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1719 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1720 expect_pending_htlcs_forwardable!(nodes[2]);
1722 let events = nodes[2].node.get_and_clear_pending_events();
1723 assert_eq!(events.len(), 2);
1725 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1726 assert_eq!(our_payment_hash_21, *payment_hash);
1727 assert_eq!(*payment_secret, None);
1728 assert_eq!(recv_value_21, amt);
1730 _ => panic!("Unexpected event"),
1733 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1734 assert_eq!(our_payment_hash_22, *payment_hash);
1735 assert_eq!(None, *payment_secret);
1736 assert_eq!(recv_value_22, amt);
1738 _ => panic!("Unexpected event"),
1741 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1742 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1743 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1745 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);
1746 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1747 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1748 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1750 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1751 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1755 fn channel_reserve_test() {
1756 do_channel_reserve_test(false);
1757 do_channel_reserve_test(true);
1761 fn channel_reserve_in_flight_removes() {
1762 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1763 // can send to its counterparty, but due to update ordering, the other side may not yet have
1764 // considered those HTLCs fully removed.
1765 // This tests that we don't count HTLCs which will not be included in the next remote
1766 // commitment transaction towards the reserve value (as it implies no commitment transaction
1767 // will be generated which violates the remote reserve value).
1768 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1770 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1771 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1772 // you only consider the value of the first HTLC, it may not),
1773 // * start routing a third HTLC from A to B,
1774 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1775 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1776 // * deliver the first fulfill from B
1777 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1779 // * deliver A's response CS and RAA.
1780 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1781 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1782 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1783 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1784 let chanmon_cfgs = create_chanmon_cfgs(2);
1785 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1786 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1787 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1788 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1790 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1791 // Route the first two HTLCs.
1792 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1793 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1795 // Start routing the third HTLC (this is just used to get everyone in the right state).
1796 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1798 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1799 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1800 check_added_monitors!(nodes[0], 1);
1801 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1802 assert_eq!(events.len(), 1);
1803 SendEvent::from_event(events.remove(0))
1806 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1807 // initial fulfill/CS.
1808 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1809 check_added_monitors!(nodes[1], 1);
1810 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1812 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1813 // remove the second HTLC when we send the HTLC back from B to A.
1814 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1815 check_added_monitors!(nodes[1], 1);
1816 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1818 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1819 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1820 check_added_monitors!(nodes[0], 1);
1821 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1822 expect_payment_sent!(nodes[0], payment_preimage_1);
1824 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1825 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1826 check_added_monitors!(nodes[1], 1);
1827 // B is already AwaitingRAA, so cant generate a CS here
1828 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1830 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1831 check_added_monitors!(nodes[1], 1);
1832 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1834 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1835 check_added_monitors!(nodes[0], 1);
1836 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1838 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1839 check_added_monitors!(nodes[1], 1);
1840 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1842 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1843 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1844 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1845 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1846 // on-chain as necessary).
1847 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1848 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1849 check_added_monitors!(nodes[0], 1);
1850 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1851 expect_payment_sent!(nodes[0], payment_preimage_2);
1853 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1854 check_added_monitors!(nodes[1], 1);
1855 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1857 expect_pending_htlcs_forwardable!(nodes[1]);
1858 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1860 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1861 // resolve the second HTLC from A's point of view.
1862 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1863 check_added_monitors!(nodes[0], 1);
1864 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1866 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1867 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1868 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1870 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1871 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1872 check_added_monitors!(nodes[1], 1);
1873 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1874 assert_eq!(events.len(), 1);
1875 SendEvent::from_event(events.remove(0))
1878 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1879 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1880 check_added_monitors!(nodes[0], 1);
1881 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1883 // Now just resolve all the outstanding messages/HTLCs for completeness...
1885 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1886 check_added_monitors!(nodes[1], 1);
1887 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1889 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1890 check_added_monitors!(nodes[1], 1);
1892 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1893 check_added_monitors!(nodes[0], 1);
1894 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1896 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1897 check_added_monitors!(nodes[1], 1);
1898 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1900 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1901 check_added_monitors!(nodes[0], 1);
1903 expect_pending_htlcs_forwardable!(nodes[0]);
1904 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1906 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1907 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1911 fn channel_monitor_network_test() {
1912 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1913 // tests that ChannelMonitor is able to recover from various states.
1914 let chanmon_cfgs = create_chanmon_cfgs(5);
1915 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1916 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1917 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1919 // Create some initial channels
1920 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1921 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1922 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1923 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1925 // Rebalance the network a bit by relaying one payment through all the channels...
1926 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
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);
1931 // Simple case with no pending HTLCs:
1932 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1933 check_added_monitors!(nodes[1], 1);
1935 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1936 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1937 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1938 check_added_monitors!(nodes[0], 1);
1939 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1941 get_announce_close_broadcast_events(&nodes, 0, 1);
1942 assert_eq!(nodes[0].node.list_channels().len(), 0);
1943 assert_eq!(nodes[1].node.list_channels().len(), 1);
1945 // One pending HTLC is discarded by the force-close:
1946 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1948 // Simple case of one pending HTLC to HTLC-Timeout
1949 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1950 check_added_monitors!(nodes[1], 1);
1952 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1953 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1954 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1955 check_added_monitors!(nodes[2], 1);
1956 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1958 get_announce_close_broadcast_events(&nodes, 1, 2);
1959 assert_eq!(nodes[1].node.list_channels().len(), 0);
1960 assert_eq!(nodes[2].node.list_channels().len(), 1);
1962 macro_rules! claim_funds {
1963 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1965 assert!($node.node.claim_funds($preimage, &None, $amount));
1966 check_added_monitors!($node, 1);
1968 let events = $node.node.get_and_clear_pending_msg_events();
1969 assert_eq!(events.len(), 1);
1971 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1972 assert!(update_add_htlcs.is_empty());
1973 assert!(update_fail_htlcs.is_empty());
1974 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1976 _ => panic!("Unexpected event"),
1982 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1983 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1984 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1985 check_added_monitors!(nodes[2], 1);
1986 let node2_commitment_txid;
1988 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1989 node2_commitment_txid = node_txn[0].txid();
1991 // Claim the payment on nodes[3], giving it knowledge of the preimage
1992 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
1994 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1995 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1996 check_added_monitors!(nodes[3], 1);
1998 check_preimage_claim(&nodes[3], &node_txn);
2000 get_announce_close_broadcast_events(&nodes, 2, 3);
2001 assert_eq!(nodes[2].node.list_channels().len(), 0);
2002 assert_eq!(nodes[3].node.list_channels().len(), 1);
2004 { // Cheat and reset nodes[4]'s height to 1
2005 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2006 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2009 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2010 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2011 // One pending HTLC to time out:
2012 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2013 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2017 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2018 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2019 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2020 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2021 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2023 check_added_monitors!(nodes[3], 1);
2025 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2027 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2028 node_txn.retain(|tx| {
2029 if tx.input[0].previous_output.txid == node2_commitment_txid {
2035 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2037 // Claim the payment on nodes[4], giving it knowledge of the preimage
2038 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2040 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2042 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2043 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2044 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2045 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2048 check_added_monitors!(nodes[4], 1);
2049 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2051 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2052 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2054 check_preimage_claim(&nodes[4], &node_txn);
2056 get_announce_close_broadcast_events(&nodes, 3, 4);
2057 assert_eq!(nodes[3].node.list_channels().len(), 0);
2058 assert_eq!(nodes[4].node.list_channels().len(), 0);
2062 fn test_justice_tx() {
2063 // Test justice txn built on revoked HTLC-Success tx, against both sides
2064 let mut alice_config = UserConfig::default();
2065 alice_config.channel_options.announced_channel = true;
2066 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2067 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2068 let mut bob_config = UserConfig::default();
2069 bob_config.channel_options.announced_channel = true;
2070 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2071 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2072 let user_cfgs = [Some(alice_config), Some(bob_config)];
2073 let chanmon_cfgs = create_chanmon_cfgs(2);
2074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2077 // Create some new channels:
2078 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2080 // A pending HTLC which will be revoked:
2081 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2082 // Get the will-be-revoked local txn from nodes[0]
2083 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2084 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2085 assert_eq!(revoked_local_txn[0].input.len(), 1);
2086 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2087 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2088 assert_eq!(revoked_local_txn[1].input.len(), 1);
2089 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2090 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2091 // Revoke the old state
2092 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2095 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2096 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2098 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2099 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2100 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2102 check_spends!(node_txn[0], revoked_local_txn[0]);
2103 node_txn.swap_remove(0);
2104 node_txn.truncate(1);
2106 check_added_monitors!(nodes[1], 1);
2107 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2109 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2110 // Verify broadcast of revoked HTLC-timeout
2111 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2112 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2113 check_added_monitors!(nodes[0], 1);
2114 // Broadcast revoked HTLC-timeout on node 1
2115 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2116 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2118 get_announce_close_broadcast_events(&nodes, 0, 1);
2120 assert_eq!(nodes[0].node.list_channels().len(), 0);
2121 assert_eq!(nodes[1].node.list_channels().len(), 0);
2123 // We test justice_tx build by A on B's revoked HTLC-Success tx
2124 // Create some new channels:
2125 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2127 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2131 // A pending HTLC which will be revoked:
2132 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2133 // Get the will-be-revoked local txn from B
2134 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2135 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2136 assert_eq!(revoked_local_txn[0].input.len(), 1);
2137 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2138 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2139 // Revoke the old state
2140 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2142 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2143 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2145 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2146 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2147 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2149 check_spends!(node_txn[0], revoked_local_txn[0]);
2150 node_txn.swap_remove(0);
2152 check_added_monitors!(nodes[0], 1);
2153 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2155 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2156 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2157 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2158 check_added_monitors!(nodes[1], 1);
2159 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2160 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2162 get_announce_close_broadcast_events(&nodes, 0, 1);
2163 assert_eq!(nodes[0].node.list_channels().len(), 0);
2164 assert_eq!(nodes[1].node.list_channels().len(), 0);
2168 fn revoked_output_claim() {
2169 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2170 // transaction is broadcast by its counterparty
2171 let chanmon_cfgs = create_chanmon_cfgs(2);
2172 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2173 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2174 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2175 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2176 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2177 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2178 assert_eq!(revoked_local_txn.len(), 1);
2179 // Only output is the full channel value back to nodes[0]:
2180 assert_eq!(revoked_local_txn[0].output.len(), 1);
2181 // Send a payment through, updating everyone's latest commitment txn
2182 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2184 // Inform nodes[1] that nodes[0] broadcast a stale tx
2185 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2186 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2187 check_added_monitors!(nodes[1], 1);
2188 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2189 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2191 check_spends!(node_txn[0], revoked_local_txn[0]);
2192 check_spends!(node_txn[1], chan_1.3);
2194 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2195 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2196 get_announce_close_broadcast_events(&nodes, 0, 1);
2197 check_added_monitors!(nodes[0], 1)
2201 fn claim_htlc_outputs_shared_tx() {
2202 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2203 let chanmon_cfgs = create_chanmon_cfgs(2);
2204 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2205 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2206 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2208 // Create some new channel:
2209 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2211 // Rebalance the network to generate htlc in the two directions
2212 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2213 // 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
2214 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2215 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2217 // Get the will-be-revoked local txn from node[0]
2218 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2219 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2220 assert_eq!(revoked_local_txn[0].input.len(), 1);
2221 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2222 assert_eq!(revoked_local_txn[1].input.len(), 1);
2223 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2224 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2225 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2227 //Revoke the old state
2228 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2231 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2232 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2233 check_added_monitors!(nodes[0], 1);
2234 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2235 check_added_monitors!(nodes[1], 1);
2236 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2237 expect_payment_failed!(nodes[1], payment_hash_2, true);
2239 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2240 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2242 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2243 check_spends!(node_txn[0], revoked_local_txn[0]);
2245 let mut witness_lens = BTreeSet::new();
2246 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2247 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2248 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2249 assert_eq!(witness_lens.len(), 3);
2250 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2251 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2252 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2254 // Next nodes[1] broadcasts its current local tx state:
2255 assert_eq!(node_txn[1].input.len(), 1);
2256 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2258 assert_eq!(node_txn[2].input.len(), 1);
2259 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2260 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2261 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2262 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2263 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2265 get_announce_close_broadcast_events(&nodes, 0, 1);
2266 assert_eq!(nodes[0].node.list_channels().len(), 0);
2267 assert_eq!(nodes[1].node.list_channels().len(), 0);
2271 fn claim_htlc_outputs_single_tx() {
2272 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2273 let chanmon_cfgs = create_chanmon_cfgs(2);
2274 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2275 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2276 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2278 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2280 // Rebalance the network to generate htlc in the two directions
2281 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2282 // 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
2283 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2284 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2285 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2287 // Get the will-be-revoked local txn from node[0]
2288 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2290 //Revoke the old state
2291 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2294 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2295 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2296 check_added_monitors!(nodes[0], 1);
2297 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2298 check_added_monitors!(nodes[1], 1);
2299 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2301 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2302 expect_payment_failed!(nodes[1], payment_hash_2, true);
2304 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2305 assert_eq!(node_txn.len(), 9);
2306 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2307 // ChannelManager: local commmitment + local HTLC-timeout (2)
2308 // 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)
2309 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2311 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2312 assert_eq!(node_txn[2].input.len(), 1);
2313 check_spends!(node_txn[2], chan_1.3);
2314 assert_eq!(node_txn[3].input.len(), 1);
2315 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2316 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2317 check_spends!(node_txn[3], node_txn[2]);
2319 // Justice transactions are indices 1-2-4
2320 assert_eq!(node_txn[0].input.len(), 1);
2321 assert_eq!(node_txn[1].input.len(), 1);
2322 assert_eq!(node_txn[4].input.len(), 1);
2324 check_spends!(node_txn[0], revoked_local_txn[0]);
2325 check_spends!(node_txn[1], revoked_local_txn[0]);
2326 check_spends!(node_txn[4], revoked_local_txn[0]);
2328 let mut witness_lens = BTreeSet::new();
2329 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2330 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2331 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2332 assert_eq!(witness_lens.len(), 3);
2333 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2334 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2335 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2337 get_announce_close_broadcast_events(&nodes, 0, 1);
2338 assert_eq!(nodes[0].node.list_channels().len(), 0);
2339 assert_eq!(nodes[1].node.list_channels().len(), 0);
2343 fn test_htlc_on_chain_success() {
2344 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2345 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2346 // broadcasting the right event to other nodes in payment path.
2347 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2348 // A --------------------> B ----------------------> C (preimage)
2349 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2350 // commitment transaction was broadcast.
2351 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2353 // B should be able to claim via preimage if A then broadcasts its local tx.
2354 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2355 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2356 // PaymentSent event).
2358 let chanmon_cfgs = create_chanmon_cfgs(3);
2359 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2360 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2361 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2363 // Create some initial channels
2364 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2365 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2367 // Rebalance the network a bit by relaying one payment through all the channels...
2368 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2369 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2371 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2372 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2373 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2375 // Broadcast legit commitment tx from C on B's chain
2376 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2377 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2378 assert_eq!(commitment_tx.len(), 1);
2379 check_spends!(commitment_tx[0], chan_2.3);
2380 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2381 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2382 check_added_monitors!(nodes[2], 2);
2383 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2384 assert!(updates.update_add_htlcs.is_empty());
2385 assert!(updates.update_fail_htlcs.is_empty());
2386 assert!(updates.update_fail_malformed_htlcs.is_empty());
2387 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2389 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2390 check_closed_broadcast!(nodes[2], false);
2391 check_added_monitors!(nodes[2], 1);
2392 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)
2393 assert_eq!(node_txn.len(), 5);
2394 assert_eq!(node_txn[0], node_txn[3]);
2395 assert_eq!(node_txn[1], node_txn[4]);
2396 assert_eq!(node_txn[2], commitment_tx[0]);
2397 check_spends!(node_txn[0], commitment_tx[0]);
2398 check_spends!(node_txn[1], commitment_tx[0]);
2399 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2400 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2401 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2402 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2403 assert_eq!(node_txn[0].lock_time, 0);
2404 assert_eq!(node_txn[1].lock_time, 0);
2406 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2407 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2409 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2410 assert_eq!(added_monitors.len(), 1);
2411 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2412 added_monitors.clear();
2414 let events = nodes[1].node.get_and_clear_pending_msg_events();
2416 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2417 assert_eq!(added_monitors.len(), 2);
2418 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2419 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2420 added_monitors.clear();
2422 assert_eq!(events.len(), 2);
2424 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2425 _ => panic!("Unexpected event"),
2428 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, .. } } => {
2429 assert!(update_add_htlcs.is_empty());
2430 assert!(update_fail_htlcs.is_empty());
2431 assert_eq!(update_fulfill_htlcs.len(), 1);
2432 assert!(update_fail_malformed_htlcs.is_empty());
2433 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2435 _ => panic!("Unexpected event"),
2437 macro_rules! check_tx_local_broadcast {
2438 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2439 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2440 assert_eq!(node_txn.len(), 5);
2441 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2442 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2443 check_spends!(node_txn[0], $commitment_tx);
2444 check_spends!(node_txn[1], $commitment_tx);
2445 assert_ne!(node_txn[0].lock_time, 0);
2446 assert_ne!(node_txn[1].lock_time, 0);
2448 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2449 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2450 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2451 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2453 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2454 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2455 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2456 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2458 check_spends!(node_txn[2], $chan_tx);
2459 check_spends!(node_txn[3], node_txn[2]);
2460 check_spends!(node_txn[4], node_txn[2]);
2461 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2462 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2463 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2464 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2465 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2466 assert_ne!(node_txn[3].lock_time, 0);
2467 assert_ne!(node_txn[4].lock_time, 0);
2471 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2472 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2473 // timeout-claim of the output that nodes[2] just claimed via success.
2474 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2476 // Broadcast legit commitment tx from A on B's chain
2477 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2478 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2479 check_spends!(commitment_tx[0], chan_1.3);
2480 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2481 check_closed_broadcast!(nodes[1], false);
2482 check_added_monitors!(nodes[1], 1);
2483 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2484 assert_eq!(node_txn.len(), 4);
2485 check_spends!(node_txn[0], commitment_tx[0]);
2486 assert_eq!(node_txn[0].input.len(), 2);
2487 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2488 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2489 assert_eq!(node_txn[0].lock_time, 0);
2490 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2491 check_spends!(node_txn[1], chan_1.3);
2492 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2493 check_spends!(node_txn[2], node_txn[1]);
2494 check_spends!(node_txn[3], node_txn[1]);
2495 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2496 // we already checked the same situation with A.
2498 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2499 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2500 check_closed_broadcast!(nodes[0], false);
2501 check_added_monitors!(nodes[0], 1);
2502 let events = nodes[0].node.get_and_clear_pending_events();
2503 assert_eq!(events.len(), 2);
2504 let mut first_claimed = false;
2505 for event in events {
2507 Event::PaymentSent { payment_preimage } => {
2508 if payment_preimage == our_payment_preimage {
2509 assert!(!first_claimed);
2510 first_claimed = true;
2512 assert_eq!(payment_preimage, our_payment_preimage_2);
2515 _ => panic!("Unexpected event"),
2518 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2522 fn test_htlc_on_chain_timeout() {
2523 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2524 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2525 // broadcasting the right event to other nodes in payment path.
2526 // A ------------------> B ----------------------> C (timeout)
2527 // B's commitment tx C's commitment tx
2529 // B's HTLC timeout tx B's timeout tx
2531 let chanmon_cfgs = create_chanmon_cfgs(3);
2532 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2533 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2534 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2536 // Create some intial channels
2537 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2538 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2540 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2541 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2542 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2544 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2545 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2547 // Broadcast legit commitment tx from C on B's chain
2548 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2549 check_spends!(commitment_tx[0], chan_2.3);
2550 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2551 check_added_monitors!(nodes[2], 0);
2552 expect_pending_htlcs_forwardable!(nodes[2]);
2553 check_added_monitors!(nodes[2], 1);
2555 let events = nodes[2].node.get_and_clear_pending_msg_events();
2556 assert_eq!(events.len(), 1);
2558 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, .. } } => {
2559 assert!(update_add_htlcs.is_empty());
2560 assert!(!update_fail_htlcs.is_empty());
2561 assert!(update_fulfill_htlcs.is_empty());
2562 assert!(update_fail_malformed_htlcs.is_empty());
2563 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2565 _ => panic!("Unexpected event"),
2567 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2568 check_closed_broadcast!(nodes[2], false);
2569 check_added_monitors!(nodes[2], 1);
2570 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2571 assert_eq!(node_txn.len(), 1);
2572 check_spends!(node_txn[0], chan_2.3);
2573 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2575 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2576 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2577 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2580 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2581 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2582 assert_eq!(node_txn[1], node_txn[3]);
2583 assert_eq!(node_txn[2], node_txn[4]);
2585 check_spends!(node_txn[0], commitment_tx[0]);
2586 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2588 check_spends!(node_txn[1], chan_2.3);
2589 check_spends!(node_txn[2], node_txn[1]);
2590 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2591 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2593 timeout_tx = node_txn[0].clone();
2597 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2598 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2599 check_added_monitors!(nodes[1], 1);
2600 check_closed_broadcast!(nodes[1], false);
2602 expect_pending_htlcs_forwardable!(nodes[1]);
2603 check_added_monitors!(nodes[1], 1);
2604 let events = nodes[1].node.get_and_clear_pending_msg_events();
2605 assert_eq!(events.len(), 1);
2607 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, .. } } => {
2608 assert!(update_add_htlcs.is_empty());
2609 assert!(!update_fail_htlcs.is_empty());
2610 assert!(update_fulfill_htlcs.is_empty());
2611 assert!(update_fail_malformed_htlcs.is_empty());
2612 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2614 _ => panic!("Unexpected event"),
2616 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
2617 assert_eq!(node_txn.len(), 0);
2619 // Broadcast legit commitment tx from B on A's chain
2620 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2621 check_spends!(commitment_tx[0], chan_1.3);
2623 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2624 check_closed_broadcast!(nodes[0], false);
2625 check_added_monitors!(nodes[0], 1);
2626 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2627 assert_eq!(node_txn.len(), 3);
2628 check_spends!(node_txn[0], commitment_tx[0]);
2629 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2630 check_spends!(node_txn[1], chan_1.3);
2631 check_spends!(node_txn[2], node_txn[1]);
2632 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2633 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2637 fn test_simple_commitment_revoked_fail_backward() {
2638 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2639 // and fail backward accordingly.
2641 let chanmon_cfgs = create_chanmon_cfgs(3);
2642 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2643 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2644 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2646 // Create some initial channels
2647 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2648 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2650 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2651 // Get the will-be-revoked local txn from nodes[2]
2652 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2653 // Revoke the old state
2654 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2656 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2658 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2659 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2660 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2661 check_added_monitors!(nodes[1], 1);
2662 check_closed_broadcast!(nodes[1], false);
2664 expect_pending_htlcs_forwardable!(nodes[1]);
2665 check_added_monitors!(nodes[1], 1);
2666 let events = nodes[1].node.get_and_clear_pending_msg_events();
2667 assert_eq!(events.len(), 1);
2669 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, .. } } => {
2670 assert!(update_add_htlcs.is_empty());
2671 assert_eq!(update_fail_htlcs.len(), 1);
2672 assert!(update_fulfill_htlcs.is_empty());
2673 assert!(update_fail_malformed_htlcs.is_empty());
2674 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2676 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2677 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2679 let events = nodes[0].node.get_and_clear_pending_msg_events();
2680 assert_eq!(events.len(), 1);
2682 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2683 _ => panic!("Unexpected event"),
2685 expect_payment_failed!(nodes[0], payment_hash, false);
2687 _ => panic!("Unexpected event"),
2691 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2692 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2693 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2694 // commitment transaction anymore.
2695 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2696 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2697 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2698 // technically disallowed and we should probably handle it reasonably.
2699 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2700 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2702 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2703 // commitment_signed (implying it will be in the latest remote commitment transaction).
2704 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2705 // and once they revoke the previous commitment transaction (allowing us to send a new
2706 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2707 let chanmon_cfgs = create_chanmon_cfgs(3);
2708 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2709 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2710 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2712 // Create some initial channels
2713 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2714 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2716 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2717 // Get the will-be-revoked local txn from nodes[2]
2718 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2719 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2720 // Revoke the old state
2721 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2723 let value = if use_dust {
2724 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2725 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2726 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2729 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2730 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2731 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2733 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2734 expect_pending_htlcs_forwardable!(nodes[2]);
2735 check_added_monitors!(nodes[2], 1);
2736 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2737 assert!(updates.update_add_htlcs.is_empty());
2738 assert!(updates.update_fulfill_htlcs.is_empty());
2739 assert!(updates.update_fail_malformed_htlcs.is_empty());
2740 assert_eq!(updates.update_fail_htlcs.len(), 1);
2741 assert!(updates.update_fee.is_none());
2742 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2743 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2744 // Drop the last RAA from 3 -> 2
2746 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2747 expect_pending_htlcs_forwardable!(nodes[2]);
2748 check_added_monitors!(nodes[2], 1);
2749 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2750 assert!(updates.update_add_htlcs.is_empty());
2751 assert!(updates.update_fulfill_htlcs.is_empty());
2752 assert!(updates.update_fail_malformed_htlcs.is_empty());
2753 assert_eq!(updates.update_fail_htlcs.len(), 1);
2754 assert!(updates.update_fee.is_none());
2755 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2756 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2757 check_added_monitors!(nodes[1], 1);
2758 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2759 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2760 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2761 check_added_monitors!(nodes[2], 1);
2763 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2764 expect_pending_htlcs_forwardable!(nodes[2]);
2765 check_added_monitors!(nodes[2], 1);
2766 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2767 assert!(updates.update_add_htlcs.is_empty());
2768 assert!(updates.update_fulfill_htlcs.is_empty());
2769 assert!(updates.update_fail_malformed_htlcs.is_empty());
2770 assert_eq!(updates.update_fail_htlcs.len(), 1);
2771 assert!(updates.update_fee.is_none());
2772 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2773 // At this point first_payment_hash has dropped out of the latest two commitment
2774 // transactions that nodes[1] is tracking...
2775 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2776 check_added_monitors!(nodes[1], 1);
2777 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2778 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2779 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2780 check_added_monitors!(nodes[2], 1);
2782 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2783 // on nodes[2]'s RAA.
2784 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2785 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2786 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2787 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2788 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2789 check_added_monitors!(nodes[1], 0);
2792 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2793 // One monitor for the new revocation preimage, no second on as we won't generate a new
2794 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2795 check_added_monitors!(nodes[1], 1);
2796 let events = nodes[1].node.get_and_clear_pending_events();
2797 assert_eq!(events.len(), 1);
2799 Event::PendingHTLCsForwardable { .. } => { },
2800 _ => panic!("Unexpected event"),
2802 // Deliberately don't process the pending fail-back so they all fail back at once after
2803 // block connection just like the !deliver_bs_raa case
2806 let mut failed_htlcs = HashSet::new();
2807 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2809 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2810 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2811 check_added_monitors!(nodes[1], 1);
2812 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2814 let events = nodes[1].node.get_and_clear_pending_events();
2815 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2817 Event::PaymentFailed { ref payment_hash, .. } => {
2818 assert_eq!(*payment_hash, fourth_payment_hash);
2820 _ => panic!("Unexpected event"),
2822 if !deliver_bs_raa {
2824 Event::PendingHTLCsForwardable { .. } => { },
2825 _ => panic!("Unexpected event"),
2828 nodes[1].node.process_pending_htlc_forwards();
2829 check_added_monitors!(nodes[1], 1);
2831 let events = nodes[1].node.get_and_clear_pending_msg_events();
2832 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2833 match events[if deliver_bs_raa { 1 } else { 0 }] {
2834 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2835 _ => panic!("Unexpected event"),
2839 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, .. } } => {
2840 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2841 assert_eq!(update_add_htlcs.len(), 1);
2842 assert!(update_fulfill_htlcs.is_empty());
2843 assert!(update_fail_htlcs.is_empty());
2844 assert!(update_fail_malformed_htlcs.is_empty());
2846 _ => panic!("Unexpected event"),
2849 match events[if deliver_bs_raa { 2 } else { 1 }] {
2850 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, .. } } => {
2851 assert!(update_add_htlcs.is_empty());
2852 assert_eq!(update_fail_htlcs.len(), 3);
2853 assert!(update_fulfill_htlcs.is_empty());
2854 assert!(update_fail_malformed_htlcs.is_empty());
2855 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2857 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2858 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2859 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2861 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2863 let events = nodes[0].node.get_and_clear_pending_msg_events();
2864 // If we delivered B's RAA we got an unknown preimage error, not something
2865 // that we should update our routing table for.
2866 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2867 for event in events {
2869 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2870 _ => panic!("Unexpected event"),
2873 let events = nodes[0].node.get_and_clear_pending_events();
2874 assert_eq!(events.len(), 3);
2876 Event::PaymentFailed { ref payment_hash, .. } => {
2877 assert!(failed_htlcs.insert(payment_hash.0));
2879 _ => panic!("Unexpected event"),
2882 Event::PaymentFailed { ref payment_hash, .. } => {
2883 assert!(failed_htlcs.insert(payment_hash.0));
2885 _ => panic!("Unexpected event"),
2888 Event::PaymentFailed { ref payment_hash, .. } => {
2889 assert!(failed_htlcs.insert(payment_hash.0));
2891 _ => panic!("Unexpected event"),
2894 _ => panic!("Unexpected event"),
2897 assert!(failed_htlcs.contains(&first_payment_hash.0));
2898 assert!(failed_htlcs.contains(&second_payment_hash.0));
2899 assert!(failed_htlcs.contains(&third_payment_hash.0));
2903 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2904 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2905 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2906 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2907 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2911 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2912 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2913 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2914 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2915 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2919 fn fail_backward_pending_htlc_upon_channel_failure() {
2920 let chanmon_cfgs = create_chanmon_cfgs(2);
2921 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2922 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2923 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2924 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::supported(), InitFeatures::supported());
2926 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2928 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2929 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV).unwrap();
2930 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2931 check_added_monitors!(nodes[0], 1);
2933 let payment_event = {
2934 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2935 assert_eq!(events.len(), 1);
2936 SendEvent::from_event(events.remove(0))
2938 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2939 assert_eq!(payment_event.msgs.len(), 1);
2942 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2943 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2945 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV).unwrap();
2946 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2947 check_added_monitors!(nodes[0], 0);
2949 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2952 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
2954 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV).unwrap();
2955 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
2957 let secp_ctx = Secp256k1::new();
2958 let session_priv = {
2959 let mut session_key = [0; 32];
2960 let mut rng = thread_rng();
2961 rng.fill_bytes(&mut session_key);
2962 SecretKey::from_slice(&session_key).expect("RNG is bad!")
2965 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2966 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
2967 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
2968 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
2970 // Send a 0-msat update_add_htlc to fail the channel.
2971 let update_add_htlc = msgs::UpdateAddHTLC {
2977 onion_routing_packet,
2979 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
2982 // Check that Alice fails backward the pending HTLC from the second payment.
2983 expect_payment_failed!(nodes[0], failed_payment_hash, true);
2984 check_closed_broadcast!(nodes[0], true);
2985 check_added_monitors!(nodes[0], 1);
2989 fn test_htlc_ignore_latest_remote_commitment() {
2990 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2991 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2992 let chanmon_cfgs = create_chanmon_cfgs(2);
2993 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2994 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2995 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2996 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2998 route_payment(&nodes[0], &[&nodes[1]], 10000000);
2999 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3000 check_closed_broadcast!(nodes[0], false);
3001 check_added_monitors!(nodes[0], 1);
3003 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3004 assert_eq!(node_txn.len(), 2);
3006 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3007 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3008 check_closed_broadcast!(nodes[1], false);
3009 check_added_monitors!(nodes[1], 1);
3011 // Duplicate the block_connected call since this may happen due to other listeners
3012 // registering new transactions
3013 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3017 fn test_force_close_fail_back() {
3018 // Check which HTLCs are failed-backwards on channel force-closure
3019 let chanmon_cfgs = create_chanmon_cfgs(3);
3020 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3021 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3022 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3023 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3024 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3026 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3028 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3030 let mut payment_event = {
3031 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3032 check_added_monitors!(nodes[0], 1);
3034 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3035 assert_eq!(events.len(), 1);
3036 SendEvent::from_event(events.remove(0))
3039 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3040 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3042 expect_pending_htlcs_forwardable!(nodes[1]);
3044 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3045 assert_eq!(events_2.len(), 1);
3046 payment_event = SendEvent::from_event(events_2.remove(0));
3047 assert_eq!(payment_event.msgs.len(), 1);
3049 check_added_monitors!(nodes[1], 1);
3050 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3051 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3052 check_added_monitors!(nodes[2], 1);
3053 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3055 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3056 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3057 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3059 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3060 check_closed_broadcast!(nodes[2], false);
3061 check_added_monitors!(nodes[2], 1);
3063 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3064 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3065 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3066 // back to nodes[1] upon timeout otherwise.
3067 assert_eq!(node_txn.len(), 1);
3071 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3072 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3074 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3075 check_closed_broadcast!(nodes[1], false);
3076 check_added_monitors!(nodes[1], 1);
3078 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3080 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3081 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3082 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3084 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3085 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3086 assert_eq!(node_txn.len(), 1);
3087 assert_eq!(node_txn[0].input.len(), 1);
3088 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3089 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3090 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3092 check_spends!(node_txn[0], tx);
3096 fn test_unconf_chan() {
3097 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3098 let chanmon_cfgs = create_chanmon_cfgs(2);
3099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3101 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3102 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3104 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3105 assert_eq!(channel_state.by_id.len(), 1);
3106 assert_eq!(channel_state.short_to_id.len(), 1);
3107 mem::drop(channel_state);
3109 let mut headers = Vec::new();
3110 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3111 headers.push(header.clone());
3113 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3114 headers.push(header.clone());
3116 let mut height = 99;
3117 while !headers.is_empty() {
3118 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3121 check_closed_broadcast!(nodes[0], false);
3122 check_added_monitors!(nodes[0], 1);
3123 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3124 assert_eq!(channel_state.by_id.len(), 0);
3125 assert_eq!(channel_state.short_to_id.len(), 0);
3129 fn test_simple_peer_disconnect() {
3130 // Test that we can reconnect when there are no lost messages
3131 let chanmon_cfgs = create_chanmon_cfgs(3);
3132 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3133 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3134 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3135 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3136 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3138 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3139 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3140 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3142 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3143 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3144 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3145 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3147 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3148 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3149 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3151 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3152 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3153 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3154 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3156 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3157 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3159 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3160 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3162 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3164 let events = nodes[0].node.get_and_clear_pending_events();
3165 assert_eq!(events.len(), 2);
3167 Event::PaymentSent { payment_preimage } => {
3168 assert_eq!(payment_preimage, payment_preimage_3);
3170 _ => panic!("Unexpected event"),
3173 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3174 assert_eq!(payment_hash, payment_hash_5);
3175 assert!(rejected_by_dest);
3177 _ => panic!("Unexpected event"),
3181 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3182 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3185 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3186 // Test that we can reconnect when in-flight HTLC updates get dropped
3187 let chanmon_cfgs = create_chanmon_cfgs(2);
3188 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3189 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3190 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3191 if messages_delivered == 0 {
3192 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3193 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3195 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3198 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();
3199 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3201 let payment_event = {
3202 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3203 check_added_monitors!(nodes[0], 1);
3205 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3206 assert_eq!(events.len(), 1);
3207 SendEvent::from_event(events.remove(0))
3209 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3211 if messages_delivered < 2 {
3212 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3214 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3215 if messages_delivered >= 3 {
3216 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3217 check_added_monitors!(nodes[1], 1);
3218 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3220 if messages_delivered >= 4 {
3221 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3222 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3223 check_added_monitors!(nodes[0], 1);
3225 if messages_delivered >= 5 {
3226 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3227 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3228 // No commitment_signed so get_event_msg's assert(len == 1) passes
3229 check_added_monitors!(nodes[0], 1);
3231 if messages_delivered >= 6 {
3232 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3233 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3234 check_added_monitors!(nodes[1], 1);
3241 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3242 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3243 if messages_delivered < 3 {
3244 // Even if the funding_locked messages get exchanged, as long as nothing further was
3245 // received on either side, both sides will need to resend them.
3246 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3247 } else if messages_delivered == 3 {
3248 // nodes[0] still wants its RAA + commitment_signed
3249 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3250 } else if messages_delivered == 4 {
3251 // nodes[0] still wants its commitment_signed
3252 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3253 } else if messages_delivered == 5 {
3254 // nodes[1] still wants its final RAA
3255 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3256 } else if messages_delivered == 6 {
3257 // Everything was delivered...
3258 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3261 let events_1 = nodes[1].node.get_and_clear_pending_events();
3262 assert_eq!(events_1.len(), 1);
3264 Event::PendingHTLCsForwardable { .. } => { },
3265 _ => panic!("Unexpected event"),
3268 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3269 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3270 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3272 nodes[1].node.process_pending_htlc_forwards();
3274 let events_2 = nodes[1].node.get_and_clear_pending_events();
3275 assert_eq!(events_2.len(), 1);
3277 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3278 assert_eq!(payment_hash_1, *payment_hash);
3279 assert_eq!(*payment_secret, None);
3280 assert_eq!(amt, 1000000);
3282 _ => panic!("Unexpected event"),
3285 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3286 check_added_monitors!(nodes[1], 1);
3288 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3289 assert_eq!(events_3.len(), 1);
3290 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3291 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3292 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3293 assert!(updates.update_add_htlcs.is_empty());
3294 assert!(updates.update_fail_htlcs.is_empty());
3295 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3296 assert!(updates.update_fail_malformed_htlcs.is_empty());
3297 assert!(updates.update_fee.is_none());
3298 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3300 _ => panic!("Unexpected event"),
3303 if messages_delivered >= 1 {
3304 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3306 let events_4 = nodes[0].node.get_and_clear_pending_events();
3307 assert_eq!(events_4.len(), 1);
3309 Event::PaymentSent { ref payment_preimage } => {
3310 assert_eq!(payment_preimage_1, *payment_preimage);
3312 _ => panic!("Unexpected event"),
3315 if messages_delivered >= 2 {
3316 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3317 check_added_monitors!(nodes[0], 1);
3318 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3320 if messages_delivered >= 3 {
3321 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3322 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3323 check_added_monitors!(nodes[1], 1);
3325 if messages_delivered >= 4 {
3326 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3327 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3328 // No commitment_signed so get_event_msg's assert(len == 1) passes
3329 check_added_monitors!(nodes[1], 1);
3331 if messages_delivered >= 5 {
3332 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3333 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3334 check_added_monitors!(nodes[0], 1);
3341 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3342 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3343 if messages_delivered < 2 {
3344 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3345 //TODO: Deduplicate PaymentSent events, then enable this if:
3346 //if messages_delivered < 1 {
3347 let events_4 = nodes[0].node.get_and_clear_pending_events();
3348 assert_eq!(events_4.len(), 1);
3350 Event::PaymentSent { ref payment_preimage } => {
3351 assert_eq!(payment_preimage_1, *payment_preimage);
3353 _ => panic!("Unexpected event"),
3356 } else if messages_delivered == 2 {
3357 // nodes[0] still wants its RAA + commitment_signed
3358 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3359 } else if messages_delivered == 3 {
3360 // nodes[0] still wants its commitment_signed
3361 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3362 } else if messages_delivered == 4 {
3363 // nodes[1] still wants its final RAA
3364 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3365 } else if messages_delivered == 5 {
3366 // Everything was delivered...
3367 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3370 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3371 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3372 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3374 // Channel should still work fine...
3375 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3376 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3380 fn test_drop_messages_peer_disconnect_a() {
3381 do_test_drop_messages_peer_disconnect(0);
3382 do_test_drop_messages_peer_disconnect(1);
3383 do_test_drop_messages_peer_disconnect(2);
3384 do_test_drop_messages_peer_disconnect(3);
3388 fn test_drop_messages_peer_disconnect_b() {
3389 do_test_drop_messages_peer_disconnect(4);
3390 do_test_drop_messages_peer_disconnect(5);
3391 do_test_drop_messages_peer_disconnect(6);
3395 fn test_funding_peer_disconnect() {
3396 // Test that we can lock in our funding tx while disconnected
3397 let chanmon_cfgs = create_chanmon_cfgs(2);
3398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3400 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3401 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3403 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3404 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3406 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3407 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3408 assert_eq!(events_1.len(), 1);
3410 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3411 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3413 _ => panic!("Unexpected event"),
3416 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3418 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3419 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3421 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3422 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3423 assert_eq!(events_2.len(), 2);
3424 let funding_locked = match events_2[0] {
3425 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3426 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3429 _ => panic!("Unexpected event"),
3431 let bs_announcement_sigs = match events_2[1] {
3432 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3433 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3436 _ => panic!("Unexpected event"),
3439 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3441 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3442 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3443 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3444 assert_eq!(events_3.len(), 2);
3445 let as_announcement_sigs = match events_3[0] {
3446 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3447 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3450 _ => panic!("Unexpected event"),
3452 let (as_announcement, as_update) = match events_3[1] {
3453 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3454 (msg.clone(), update_msg.clone())
3456 _ => panic!("Unexpected event"),
3459 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3460 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3461 assert_eq!(events_4.len(), 1);
3462 let (_, bs_update) = match events_4[0] {
3463 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3464 (msg.clone(), update_msg.clone())
3466 _ => panic!("Unexpected event"),
3469 nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3470 nodes[0].router.handle_channel_update(&bs_update).unwrap();
3471 nodes[0].router.handle_channel_update(&as_update).unwrap();
3473 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3474 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3475 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3479 fn test_drop_messages_peer_disconnect_dual_htlc() {
3480 // Test that we can handle reconnecting when both sides of a channel have pending
3481 // commitment_updates when we disconnect.
3482 let chanmon_cfgs = create_chanmon_cfgs(2);
3483 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3484 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3485 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3486 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3488 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3490 // Now try to send a second payment which will fail to send
3491 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3492 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3494 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3495 check_added_monitors!(nodes[0], 1);
3497 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3498 assert_eq!(events_1.len(), 1);
3500 MessageSendEvent::UpdateHTLCs { .. } => {},
3501 _ => panic!("Unexpected event"),
3504 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3505 check_added_monitors!(nodes[1], 1);
3507 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3508 assert_eq!(events_2.len(), 1);
3510 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 } } => {
3511 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3512 assert!(update_add_htlcs.is_empty());
3513 assert_eq!(update_fulfill_htlcs.len(), 1);
3514 assert!(update_fail_htlcs.is_empty());
3515 assert!(update_fail_malformed_htlcs.is_empty());
3516 assert!(update_fee.is_none());
3518 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3519 let events_3 = nodes[0].node.get_and_clear_pending_events();
3520 assert_eq!(events_3.len(), 1);
3522 Event::PaymentSent { ref payment_preimage } => {
3523 assert_eq!(*payment_preimage, payment_preimage_1);
3525 _ => panic!("Unexpected event"),
3528 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3529 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3530 // No commitment_signed so get_event_msg's assert(len == 1) passes
3531 check_added_monitors!(nodes[0], 1);
3533 _ => panic!("Unexpected event"),
3536 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3537 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3539 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3540 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3541 assert_eq!(reestablish_1.len(), 1);
3542 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3543 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3544 assert_eq!(reestablish_2.len(), 1);
3546 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3547 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3548 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3549 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3551 assert!(as_resp.0.is_none());
3552 assert!(bs_resp.0.is_none());
3554 assert!(bs_resp.1.is_none());
3555 assert!(bs_resp.2.is_none());
3557 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3559 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3560 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3561 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3562 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3563 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3564 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3565 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3566 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3567 // No commitment_signed so get_event_msg's assert(len == 1) passes
3568 check_added_monitors!(nodes[1], 1);
3570 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3571 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3572 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3573 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3574 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3575 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3576 assert!(bs_second_commitment_signed.update_fee.is_none());
3577 check_added_monitors!(nodes[1], 1);
3579 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3580 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3581 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3582 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3583 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3584 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3585 assert!(as_commitment_signed.update_fee.is_none());
3586 check_added_monitors!(nodes[0], 1);
3588 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3589 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3590 // No commitment_signed so get_event_msg's assert(len == 1) passes
3591 check_added_monitors!(nodes[0], 1);
3593 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3594 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3595 // No commitment_signed so get_event_msg's assert(len == 1) passes
3596 check_added_monitors!(nodes[1], 1);
3598 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3599 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3600 check_added_monitors!(nodes[1], 1);
3602 expect_pending_htlcs_forwardable!(nodes[1]);
3604 let events_5 = nodes[1].node.get_and_clear_pending_events();
3605 assert_eq!(events_5.len(), 1);
3607 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3608 assert_eq!(payment_hash_2, *payment_hash);
3609 assert_eq!(*payment_secret, None);
3611 _ => panic!("Unexpected event"),
3614 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3615 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3616 check_added_monitors!(nodes[0], 1);
3618 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3621 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3622 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3623 // to avoid our counterparty failing the channel.
3624 let chanmon_cfgs = create_chanmon_cfgs(2);
3625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3627 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3629 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3631 let our_payment_hash = if send_partial_mpp {
3632 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
3633 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3634 let payment_secret = PaymentSecret([0xdb; 32]);
3635 // Use the utility function send_payment_along_path to send the payment with MPP data which
3636 // indicates there are more HTLCs coming.
3637 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3638 check_added_monitors!(nodes[0], 1);
3639 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3640 assert_eq!(events.len(), 1);
3641 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3642 // hop should *not* yet generate any PaymentReceived event(s).
3643 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3646 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3649 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3650 nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3651 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3652 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3653 header.prev_blockhash = header.bitcoin_hash();
3654 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3655 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3658 expect_pending_htlcs_forwardable!(nodes[1]);
3660 check_added_monitors!(nodes[1], 1);
3661 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3662 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3663 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3664 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3665 assert!(htlc_timeout_updates.update_fee.is_none());
3667 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3668 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3669 // 100_000 msat as u64, followed by a height of 123 as u32
3670 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3671 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3672 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3676 fn test_htlc_timeout() {
3677 do_test_htlc_timeout(true);
3678 do_test_htlc_timeout(false);
3682 fn test_invalid_channel_announcement() {
3683 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3684 let secp_ctx = Secp256k1::new();
3685 let chanmon_cfgs = create_chanmon_cfgs(2);
3686 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3687 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3688 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3690 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::supported(), InitFeatures::supported());
3692 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3693 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3694 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3695 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3697 nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3699 let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3700 let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3702 let as_network_key = nodes[0].node.get_our_node_id();
3703 let bs_network_key = nodes[1].node.get_our_node_id();
3705 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3707 let mut chan_announcement;
3709 macro_rules! dummy_unsigned_msg {
3711 msgs::UnsignedChannelAnnouncement {
3712 features: ChannelFeatures::supported(),
3713 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3714 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3715 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3716 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3717 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3718 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3719 excess_data: Vec::new(),
3724 macro_rules! sign_msg {
3725 ($unsigned_msg: expr) => {
3726 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3727 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3728 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3729 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3730 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3731 chan_announcement = msgs::ChannelAnnouncement {
3732 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3733 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3734 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3735 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3736 contents: $unsigned_msg
3741 let unsigned_msg = dummy_unsigned_msg!();
3742 sign_msg!(unsigned_msg);
3743 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3744 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 } );
3746 // Configured with Network::Testnet
3747 let mut unsigned_msg = dummy_unsigned_msg!();
3748 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3749 sign_msg!(unsigned_msg);
3750 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3752 let mut unsigned_msg = dummy_unsigned_msg!();
3753 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3754 sign_msg!(unsigned_msg);
3755 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3759 fn test_no_txn_manager_serialize_deserialize() {
3760 let chanmon_cfgs = create_chanmon_cfgs(2);
3761 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3762 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3763 let fee_estimator: test_utils::TestFeeEstimator;
3764 let new_chan_monitor: test_utils::TestChannelMonitor;
3765 let keys_manager: test_utils::TestKeysInterface;
3766 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3767 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3769 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3771 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3773 let nodes_0_serialized = nodes[0].node.encode();
3774 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3775 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3777 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3778 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);
3779 nodes[0].chan_monitor = &new_chan_monitor;
3780 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3781 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3782 assert!(chan_0_monitor_read.is_empty());
3784 let mut nodes_0_read = &nodes_0_serialized[..];
3785 let config = UserConfig::default();
3786 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3787 let (_, nodes_0_deserialized_tmp) = {
3788 let mut channel_monitors = HashMap::new();
3789 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3790 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3791 default_config: config,
3792 keys_manager: &keys_manager,
3793 fee_estimator: &fee_estimator,
3794 monitor: nodes[0].chan_monitor,
3795 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3796 logger: Arc::new(test_utils::TestLogger::new()),
3797 channel_monitors: &mut channel_monitors,
3800 nodes_0_deserialized = nodes_0_deserialized_tmp;
3801 assert!(nodes_0_read.is_empty());
3803 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3804 nodes[0].node = &nodes_0_deserialized;
3805 nodes[0].block_notifier.register_listener(nodes[0].node);
3806 assert_eq!(nodes[0].node.list_channels().len(), 1);
3807 check_added_monitors!(nodes[0], 1);
3809 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3810 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3811 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3812 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3814 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3815 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3816 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3817 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3819 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3820 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3821 for node in nodes.iter() {
3822 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3823 node.router.handle_channel_update(&as_update).unwrap();
3824 node.router.handle_channel_update(&bs_update).unwrap();
3827 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3831 fn test_simple_manager_serialize_deserialize() {
3832 let chanmon_cfgs = create_chanmon_cfgs(2);
3833 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3834 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3835 let fee_estimator: test_utils::TestFeeEstimator;
3836 let new_chan_monitor: test_utils::TestChannelMonitor;
3837 let keys_manager: test_utils::TestKeysInterface;
3838 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3839 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3840 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3842 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3843 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3845 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3847 let nodes_0_serialized = nodes[0].node.encode();
3848 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3849 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3851 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3852 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);
3853 nodes[0].chan_monitor = &new_chan_monitor;
3854 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3855 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3856 assert!(chan_0_monitor_read.is_empty());
3858 let mut nodes_0_read = &nodes_0_serialized[..];
3859 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3860 let (_, nodes_0_deserialized_tmp) = {
3861 let mut channel_monitors = HashMap::new();
3862 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3863 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3864 default_config: UserConfig::default(),
3865 keys_manager: &keys_manager,
3866 fee_estimator: &fee_estimator,
3867 monitor: nodes[0].chan_monitor,
3868 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3869 logger: Arc::new(test_utils::TestLogger::new()),
3870 channel_monitors: &mut channel_monitors,
3873 nodes_0_deserialized = nodes_0_deserialized_tmp;
3874 assert!(nodes_0_read.is_empty());
3876 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3877 nodes[0].node = &nodes_0_deserialized;
3878 check_added_monitors!(nodes[0], 1);
3880 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3882 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3883 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3887 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3888 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3889 let chanmon_cfgs = create_chanmon_cfgs(4);
3890 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3891 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3892 let fee_estimator: test_utils::TestFeeEstimator;
3893 let new_chan_monitor: test_utils::TestChannelMonitor;
3894 let keys_manager: test_utils::TestKeysInterface;
3895 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3896 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3897 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3898 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::supported(), InitFeatures::supported());
3899 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
3901 let mut node_0_stale_monitors_serialized = Vec::new();
3902 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3903 let mut writer = test_utils::TestVecWriter(Vec::new());
3904 monitor.1.write_for_disk(&mut writer).unwrap();
3905 node_0_stale_monitors_serialized.push(writer.0);
3908 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3910 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3911 let nodes_0_serialized = nodes[0].node.encode();
3913 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3914 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3915 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3916 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3918 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3920 let mut node_0_monitors_serialized = Vec::new();
3921 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3922 let mut writer = test_utils::TestVecWriter(Vec::new());
3923 monitor.1.write_for_disk(&mut writer).unwrap();
3924 node_0_monitors_serialized.push(writer.0);
3927 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3928 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);
3929 nodes[0].chan_monitor = &new_chan_monitor;
3931 let mut node_0_stale_monitors = Vec::new();
3932 for serialized in node_0_stale_monitors_serialized.iter() {
3933 let mut read = &serialized[..];
3934 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3935 assert!(read.is_empty());
3936 node_0_stale_monitors.push(monitor);
3939 let mut node_0_monitors = Vec::new();
3940 for serialized in node_0_monitors_serialized.iter() {
3941 let mut read = &serialized[..];
3942 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3943 assert!(read.is_empty());
3944 node_0_monitors.push(monitor);
3947 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3949 let mut nodes_0_read = &nodes_0_serialized[..];
3950 if let Err(msgs::DecodeError::InvalidValue) =
3951 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3952 default_config: UserConfig::default(),
3953 keys_manager: &keys_manager,
3954 fee_estimator: &fee_estimator,
3955 monitor: nodes[0].chan_monitor,
3956 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3957 logger: Arc::new(test_utils::TestLogger::new()),
3958 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
3960 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
3963 let mut nodes_0_read = &nodes_0_serialized[..];
3964 let (_, nodes_0_deserialized_tmp) =
3965 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3966 default_config: UserConfig::default(),
3967 keys_manager: &keys_manager,
3968 fee_estimator: &fee_estimator,
3969 monitor: nodes[0].chan_monitor,
3970 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3971 logger: Arc::new(test_utils::TestLogger::new()),
3972 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
3974 nodes_0_deserialized = nodes_0_deserialized_tmp;
3975 assert!(nodes_0_read.is_empty());
3977 { // Channel close should result in a commitment tx and an HTLC tx
3978 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3979 assert_eq!(txn.len(), 2);
3980 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3981 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3984 for monitor in node_0_monitors.drain(..) {
3985 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
3986 check_added_monitors!(nodes[0], 1);
3988 nodes[0].node = &nodes_0_deserialized;
3990 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3991 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3992 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3993 //... and we can even still claim the payment!
3994 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3996 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3997 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3998 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3999 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4000 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4001 assert_eq!(msg_events.len(), 1);
4002 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4004 &ErrorAction::SendErrorMessage { ref msg } => {
4005 assert_eq!(msg.channel_id, channel_id);
4007 _ => panic!("Unexpected event!"),
4012 macro_rules! check_spendable_outputs {
4013 ($node: expr, $der_idx: expr) => {
4015 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4016 let mut txn = Vec::new();
4017 for event in events {
4019 Event::SpendableOutputs { ref outputs } => {
4020 for outp in outputs {
4022 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4024 previous_output: outpoint.clone(),
4025 script_sig: Script::new(),
4027 witness: Vec::new(),
4030 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4031 value: output.value,
4033 let mut spend_tx = Transaction {
4039 let secp_ctx = Secp256k1::new();
4040 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4041 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4042 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4043 let remotesig = secp_ctx.sign(&sighash, key);
4044 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4045 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4046 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4049 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
4051 previous_output: outpoint.clone(),
4052 script_sig: Script::new(),
4053 sequence: *to_self_delay as u32,
4054 witness: Vec::new(),
4057 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4058 value: output.value,
4060 let mut spend_tx = Transaction {
4066 let secp_ctx = Secp256k1::new();
4067 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
4068 let local_delaysig = secp_ctx.sign(&sighash, key);
4069 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
4070 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4071 spend_tx.input[0].witness.push(vec!());
4072 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4075 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4076 let secp_ctx = Secp256k1::new();
4078 previous_output: outpoint.clone(),
4079 script_sig: Script::new(),
4081 witness: Vec::new(),
4084 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4085 value: output.value,
4087 let mut spend_tx = Transaction {
4091 output: vec![outp.clone()],
4094 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4096 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4098 Err(_) => panic!("Your RNG is busted"),
4101 Err(_) => panic!("Your rng is busted"),
4104 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4105 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4106 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4107 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4108 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4109 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4110 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4116 _ => panic!("Unexpected event"),
4125 fn test_claim_sizeable_push_msat() {
4126 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4127 let chanmon_cfgs = create_chanmon_cfgs(2);
4128 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4129 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4130 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4132 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4133 nodes[1].node.force_close_channel(&chan.2);
4134 check_closed_broadcast!(nodes[1], false);
4135 check_added_monitors!(nodes[1], 1);
4136 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4137 assert_eq!(node_txn.len(), 1);
4138 check_spends!(node_txn[0], chan.3);
4139 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
4141 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4142 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4143 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4145 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4146 assert_eq!(spend_txn.len(), 1);
4147 check_spends!(spend_txn[0], node_txn[0]);
4151 fn test_claim_on_remote_sizeable_push_msat() {
4152 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4153 // to_remote output is encumbered by a P2WPKH
4154 let chanmon_cfgs = create_chanmon_cfgs(2);
4155 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4156 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4157 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4159 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4160 nodes[0].node.force_close_channel(&chan.2);
4161 check_closed_broadcast!(nodes[0], false);
4162 check_added_monitors!(nodes[0], 1);
4164 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4165 assert_eq!(node_txn.len(), 1);
4166 check_spends!(node_txn[0], chan.3);
4167 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
4169 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4170 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4171 check_closed_broadcast!(nodes[1], false);
4172 check_added_monitors!(nodes[1], 1);
4173 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4175 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4176 assert_eq!(spend_txn.len(), 2);
4177 assert_eq!(spend_txn[0], spend_txn[1]);
4178 check_spends!(spend_txn[0], node_txn[0]);
4182 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4183 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4184 // to_remote output is encumbered by a P2WPKH
4186 let chanmon_cfgs = create_chanmon_cfgs(2);
4187 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4188 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4189 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4191 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::supported(), InitFeatures::supported());
4192 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4193 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4194 assert_eq!(revoked_local_txn[0].input.len(), 1);
4195 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4197 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4198 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4199 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4200 check_closed_broadcast!(nodes[1], false);
4201 check_added_monitors!(nodes[1], 1);
4203 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4204 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4205 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4206 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4208 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4209 assert_eq!(spend_txn.len(), 3);
4210 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4211 check_spends!(spend_txn[0], revoked_local_txn[0]);
4212 check_spends!(spend_txn[2], node_txn[0]);
4216 fn test_static_spendable_outputs_preimage_tx() {
4217 let chanmon_cfgs = create_chanmon_cfgs(2);
4218 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4219 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4220 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4222 // Create some initial channels
4223 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4225 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4227 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4228 assert_eq!(commitment_tx[0].input.len(), 1);
4229 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4231 // Settle A's commitment tx on B's chain
4232 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4233 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4234 check_added_monitors!(nodes[1], 1);
4235 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4236 check_added_monitors!(nodes[1], 1);
4237 let events = nodes[1].node.get_and_clear_pending_msg_events();
4239 MessageSendEvent::UpdateHTLCs { .. } => {},
4240 _ => panic!("Unexpected event"),
4243 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4244 _ => panic!("Unexepected event"),
4247 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4248 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4249 assert_eq!(node_txn.len(), 3);
4250 check_spends!(node_txn[0], commitment_tx[0]);
4251 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4252 check_spends!(node_txn[1], chan_1.3);
4253 check_spends!(node_txn[2], node_txn[1]);
4255 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4256 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4257 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4259 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4260 assert_eq!(spend_txn.len(), 1);
4261 check_spends!(spend_txn[0], node_txn[0]);
4265 fn test_static_spendable_outputs_timeout_tx() {
4266 let chanmon_cfgs = create_chanmon_cfgs(2);
4267 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4268 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4269 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4271 // Create some initial channels
4272 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4274 // Rebalance the network a bit by relaying one payment through all the channels ...
4275 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4277 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4279 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4280 assert_eq!(commitment_tx[0].input.len(), 1);
4281 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4283 // Settle A's commitment tx on B' chain
4284 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4285 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4286 check_added_monitors!(nodes[1], 1);
4287 let events = nodes[1].node.get_and_clear_pending_msg_events();
4289 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4290 _ => panic!("Unexpected event"),
4293 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4294 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4295 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4296 check_spends!(node_txn[0], commitment_tx[0].clone());
4297 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4298 check_spends!(node_txn[1], chan_1.3.clone());
4299 check_spends!(node_txn[2], node_txn[1]);
4301 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4302 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4303 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4304 expect_payment_failed!(nodes[1], our_payment_hash, true);
4306 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4307 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4308 check_spends!(spend_txn[2], node_txn[0].clone());
4312 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4313 let chanmon_cfgs = create_chanmon_cfgs(2);
4314 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4315 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4316 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4318 // Create some initial channels
4319 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4321 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4322 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4323 assert_eq!(revoked_local_txn[0].input.len(), 1);
4324 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4326 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4328 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4329 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4330 check_closed_broadcast!(nodes[1], false);
4331 check_added_monitors!(nodes[1], 1);
4333 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4334 assert_eq!(node_txn.len(), 2);
4335 assert_eq!(node_txn[0].input.len(), 2);
4336 check_spends!(node_txn[0], revoked_local_txn[0]);
4338 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4339 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4340 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4342 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4343 assert_eq!(spend_txn.len(), 1);
4344 check_spends!(spend_txn[0], node_txn[0]);
4348 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4349 let chanmon_cfgs = create_chanmon_cfgs(2);
4350 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4351 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4352 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4354 // Create some initial channels
4355 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4357 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4358 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4359 assert_eq!(revoked_local_txn[0].input.len(), 1);
4360 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4362 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4364 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4365 // A will generate HTLC-Timeout from revoked commitment tx
4366 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4367 check_closed_broadcast!(nodes[0], false);
4368 check_added_monitors!(nodes[0], 1);
4370 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4371 assert_eq!(revoked_htlc_txn.len(), 2);
4372 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4373 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4374 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4375 check_spends!(revoked_htlc_txn[1], chan_1.3);
4377 // B will generate justice tx from A's revoked commitment/HTLC tx
4378 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4379 check_closed_broadcast!(nodes[1], false);
4380 check_added_monitors!(nodes[1], 1);
4382 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4383 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
4384 assert_eq!(node_txn[0].input.len(), 2);
4385 check_spends!(node_txn[0], revoked_local_txn[0]);
4386 check_spends!(node_txn[1], chan_1.3);
4387 assert_eq!(node_txn[2].input.len(), 1);
4388 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4389 assert_eq!(node_txn[3].input.len(), 1);
4390 check_spends!(node_txn[3], revoked_local_txn[0]);
4392 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4393 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4394 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4396 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4397 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4398 assert_eq!(spend_txn.len(), 2);
4399 check_spends!(spend_txn[0], node_txn[0]);
4400 check_spends!(spend_txn[1], node_txn[2]);
4404 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4405 let chanmon_cfgs = create_chanmon_cfgs(2);
4406 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4407 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4408 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4410 // Create some initial channels
4411 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4413 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4414 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4415 assert_eq!(revoked_local_txn[0].input.len(), 1);
4416 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4418 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4420 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4421 // B will generate HTLC-Success from revoked commitment tx
4422 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4423 check_closed_broadcast!(nodes[1], false);
4424 check_added_monitors!(nodes[1], 1);
4425 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4427 assert_eq!(revoked_htlc_txn.len(), 2);
4428 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4429 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4430 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4432 // A will generate justice tx from B's revoked commitment/HTLC tx
4433 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4434 check_closed_broadcast!(nodes[0], false);
4435 check_added_monitors!(nodes[0], 1);
4437 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4438 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4439 assert_eq!(node_txn[2].input.len(), 1);
4440 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4442 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4443 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4444 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4446 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4447 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4448 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4449 assert_eq!(spend_txn[0], spend_txn[1]);
4450 assert_eq!(spend_txn[0], spend_txn[2]);
4451 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4452 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4453 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4457 fn test_onchain_to_onchain_claim() {
4458 // Test that in case of channel closure, we detect the state of output thanks to
4459 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4460 // First, have C claim an HTLC against its own latest commitment transaction.
4461 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4463 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4466 let chanmon_cfgs = create_chanmon_cfgs(3);
4467 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4468 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4469 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4471 // Create some initial channels
4472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4473 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4475 // Rebalance the network a bit by relaying one payment through all the channels ...
4476 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4477 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4479 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4480 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4481 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4482 check_spends!(commitment_tx[0], chan_2.3);
4483 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4484 check_added_monitors!(nodes[2], 1);
4485 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4486 assert!(updates.update_add_htlcs.is_empty());
4487 assert!(updates.update_fail_htlcs.is_empty());
4488 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4489 assert!(updates.update_fail_malformed_htlcs.is_empty());
4491 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4492 check_closed_broadcast!(nodes[2], false);
4493 check_added_monitors!(nodes[2], 1);
4495 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4496 assert_eq!(c_txn.len(), 3);
4497 assert_eq!(c_txn[0], c_txn[2]);
4498 assert_eq!(commitment_tx[0], c_txn[1]);
4499 check_spends!(c_txn[1], chan_2.3);
4500 check_spends!(c_txn[2], c_txn[1]);
4501 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4502 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4503 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4504 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4506 // 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
4507 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4509 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4510 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4511 assert_eq!(b_txn.len(), 3);
4512 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4513 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4514 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4515 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4516 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4517 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4518 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4519 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4520 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4523 check_added_monitors!(nodes[1], 1);
4524 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4525 check_added_monitors!(nodes[1], 1);
4526 match msg_events[0] {
4527 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4528 _ => panic!("Unexpected event"),
4530 match msg_events[1] {
4531 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, .. } } => {
4532 assert!(update_add_htlcs.is_empty());
4533 assert!(update_fail_htlcs.is_empty());
4534 assert_eq!(update_fulfill_htlcs.len(), 1);
4535 assert!(update_fail_malformed_htlcs.is_empty());
4536 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4538 _ => panic!("Unexpected event"),
4540 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4541 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4542 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4543 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4544 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4545 assert_eq!(b_txn.len(), 3);
4546 check_spends!(b_txn[1], chan_1.3);
4547 check_spends!(b_txn[2], b_txn[1]);
4548 check_spends!(b_txn[0], commitment_tx[0]);
4549 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4550 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4551 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4553 check_closed_broadcast!(nodes[1], false);
4554 check_added_monitors!(nodes[1], 1);
4558 fn test_duplicate_payment_hash_one_failure_one_success() {
4559 // Topology : A --> B --> C
4560 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4561 let chanmon_cfgs = create_chanmon_cfgs(3);
4562 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4563 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4564 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4566 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4567 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4569 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4570 *nodes[0].network_payment_count.borrow_mut() -= 1;
4571 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4573 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4574 assert_eq!(commitment_txn[0].input.len(), 1);
4575 check_spends!(commitment_txn[0], chan_2.3);
4577 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4578 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4579 check_closed_broadcast!(nodes[1], false);
4580 check_added_monitors!(nodes[1], 1);
4582 let htlc_timeout_tx;
4583 { // Extract one of the two HTLC-Timeout transaction
4584 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4585 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4586 assert_eq!(node_txn.len(), 5);
4587 check_spends!(node_txn[0], commitment_txn[0]);
4588 assert_eq!(node_txn[0].input.len(), 1);
4589 check_spends!(node_txn[1], commitment_txn[0]);
4590 assert_eq!(node_txn[1].input.len(), 1);
4591 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4592 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4593 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4594 check_spends!(node_txn[2], chan_2.3);
4595 check_spends!(node_txn[3], node_txn[2]);
4596 check_spends!(node_txn[4], node_txn[2]);
4597 htlc_timeout_tx = node_txn[1].clone();
4600 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4601 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4602 check_added_monitors!(nodes[2], 3);
4603 let events = nodes[2].node.get_and_clear_pending_msg_events();
4605 MessageSendEvent::UpdateHTLCs { .. } => {},
4606 _ => panic!("Unexpected event"),
4609 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4610 _ => panic!("Unexepected event"),
4612 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4613 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)
4614 check_spends!(htlc_success_txn[2], chan_2.3);
4615 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4616 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4617 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4618 assert_eq!(htlc_success_txn[0].input.len(), 1);
4619 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4620 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4621 assert_eq!(htlc_success_txn[1].input.len(), 1);
4622 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4623 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4624 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4625 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4627 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4628 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4629 expect_pending_htlcs_forwardable!(nodes[1]);
4630 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4631 assert!(htlc_updates.update_add_htlcs.is_empty());
4632 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4633 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4634 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4635 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4636 check_added_monitors!(nodes[1], 1);
4638 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4639 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4641 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4642 let events = nodes[0].node.get_and_clear_pending_msg_events();
4643 assert_eq!(events.len(), 1);
4645 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4647 _ => { panic!("Unexpected event"); }
4650 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4652 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4653 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4654 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4655 assert!(updates.update_add_htlcs.is_empty());
4656 assert!(updates.update_fail_htlcs.is_empty());
4657 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4658 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4659 assert!(updates.update_fail_malformed_htlcs.is_empty());
4660 check_added_monitors!(nodes[1], 1);
4662 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4663 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4665 let events = nodes[0].node.get_and_clear_pending_events();
4667 Event::PaymentSent { ref payment_preimage } => {
4668 assert_eq!(*payment_preimage, our_payment_preimage);
4670 _ => panic!("Unexpected event"),
4675 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4676 let chanmon_cfgs = create_chanmon_cfgs(2);
4677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4681 // Create some initial channels
4682 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4684 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4685 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4686 assert_eq!(local_txn[0].input.len(), 1);
4687 check_spends!(local_txn[0], chan_1.3);
4689 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4690 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4691 check_added_monitors!(nodes[1], 1);
4692 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4693 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4694 check_added_monitors!(nodes[1], 1);
4695 let events = nodes[1].node.get_and_clear_pending_msg_events();
4697 MessageSendEvent::UpdateHTLCs { .. } => {},
4698 _ => panic!("Unexpected event"),
4701 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4702 _ => panic!("Unexepected event"),
4705 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4706 assert_eq!(node_txn[0].input.len(), 1);
4707 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4708 check_spends!(node_txn[0], local_txn[0]);
4709 vec![node_txn[0].clone(), node_txn[2].clone()]
4712 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4713 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4714 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4716 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4717 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4718 assert_eq!(spend_txn.len(), 2);
4719 check_spends!(spend_txn[0], node_txn[0]);
4720 check_spends!(spend_txn[1], node_txn[1]);
4723 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4724 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4725 // unrevoked commitment transaction.
4726 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4727 // a remote RAA before they could be failed backwards (and combinations thereof).
4728 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4729 // use the same payment hashes.
4730 // Thus, we use a six-node network:
4735 // And test where C fails back to A/B when D announces its latest commitment transaction
4736 let chanmon_cfgs = create_chanmon_cfgs(6);
4737 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4738 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4739 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4741 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported());
4742 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4743 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
4744 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
4745 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
4747 // Rebalance and check output sanity...
4748 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4749 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4750 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4752 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4754 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
4756 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
4757 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();
4759 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
4761 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
4763 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4765 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4766 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4768 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4770 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4773 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4775 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();
4776 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
4779 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
4781 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4782 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4784 // Double-check that six of the new HTLC were added
4785 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4786 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4787 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4788 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4790 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4791 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4792 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
4793 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
4794 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
4795 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
4796 check_added_monitors!(nodes[4], 0);
4797 expect_pending_htlcs_forwardable!(nodes[4]);
4798 check_added_monitors!(nodes[4], 1);
4800 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4801 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4802 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4803 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4804 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4805 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4807 // Fail 3rd below-dust and 7th above-dust HTLCs
4808 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
4809 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
4810 check_added_monitors!(nodes[5], 0);
4811 expect_pending_htlcs_forwardable!(nodes[5]);
4812 check_added_monitors!(nodes[5], 1);
4814 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4815 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4816 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4817 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4819 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4821 expect_pending_htlcs_forwardable!(nodes[3]);
4822 check_added_monitors!(nodes[3], 1);
4823 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4824 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4825 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4826 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4827 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4828 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4829 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4830 if deliver_last_raa {
4831 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4833 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4836 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4837 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4838 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4839 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4841 // We now broadcast the latest commitment transaction, which *should* result in failures for
4842 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4843 // the non-broadcast above-dust HTLCs.
4845 // Alternatively, we may broadcast the previous commitment transaction, which should only
4846 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4847 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4849 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4850 if announce_latest {
4851 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4853 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4855 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4856 check_closed_broadcast!(nodes[2], false);
4857 expect_pending_htlcs_forwardable!(nodes[2]);
4858 check_added_monitors!(nodes[2], 3);
4860 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4861 assert_eq!(cs_msgs.len(), 2);
4862 let mut a_done = false;
4863 for msg in cs_msgs {
4865 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4866 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4867 // should be failed-backwards here.
4868 let target = if *node_id == nodes[0].node.get_our_node_id() {
4869 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4870 for htlc in &updates.update_fail_htlcs {
4871 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 });
4873 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4878 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4879 for htlc in &updates.update_fail_htlcs {
4880 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4882 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4883 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4886 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4887 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4888 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4889 if announce_latest {
4890 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4891 if *node_id == nodes[0].node.get_our_node_id() {
4892 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4895 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4897 _ => panic!("Unexpected event"),
4901 let as_events = nodes[0].node.get_and_clear_pending_events();
4902 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4903 let mut as_failds = HashSet::new();
4904 for event in as_events.iter() {
4905 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4906 assert!(as_failds.insert(*payment_hash));
4907 if *payment_hash != payment_hash_2 {
4908 assert_eq!(*rejected_by_dest, deliver_last_raa);
4910 assert!(!rejected_by_dest);
4912 } else { panic!("Unexpected event"); }
4914 assert!(as_failds.contains(&payment_hash_1));
4915 assert!(as_failds.contains(&payment_hash_2));
4916 if announce_latest {
4917 assert!(as_failds.contains(&payment_hash_3));
4918 assert!(as_failds.contains(&payment_hash_5));
4920 assert!(as_failds.contains(&payment_hash_6));
4922 let bs_events = nodes[1].node.get_and_clear_pending_events();
4923 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4924 let mut bs_failds = HashSet::new();
4925 for event in bs_events.iter() {
4926 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4927 assert!(bs_failds.insert(*payment_hash));
4928 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4929 assert_eq!(*rejected_by_dest, deliver_last_raa);
4931 assert!(!rejected_by_dest);
4933 } else { panic!("Unexpected event"); }
4935 assert!(bs_failds.contains(&payment_hash_1));
4936 assert!(bs_failds.contains(&payment_hash_2));
4937 if announce_latest {
4938 assert!(bs_failds.contains(&payment_hash_4));
4940 assert!(bs_failds.contains(&payment_hash_5));
4942 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4943 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4944 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4945 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4946 // PaymentFailureNetworkUpdates.
4947 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4948 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4949 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4950 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4951 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4953 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4954 _ => panic!("Unexpected event"),
4960 fn test_fail_backwards_latest_remote_announce_a() {
4961 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4965 fn test_fail_backwards_latest_remote_announce_b() {
4966 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4970 fn test_fail_backwards_previous_remote_announce() {
4971 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4972 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4973 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4977 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4978 let chanmon_cfgs = create_chanmon_cfgs(2);
4979 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4980 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4981 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4983 // Create some initial channels
4984 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4986 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
4987 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4988 assert_eq!(local_txn[0].input.len(), 1);
4989 check_spends!(local_txn[0], chan_1.3);
4991 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4992 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4993 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4994 check_closed_broadcast!(nodes[0], false);
4995 check_added_monitors!(nodes[0], 1);
4997 let htlc_timeout = {
4998 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4999 assert_eq!(node_txn[0].input.len(), 1);
5000 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5001 check_spends!(node_txn[0], local_txn[0]);
5005 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5006 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5007 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5008 expect_payment_failed!(nodes[0], our_payment_hash, true);
5010 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5011 let spend_txn = check_spendable_outputs!(nodes[0], 1);
5012 assert_eq!(spend_txn.len(), 3);
5013 assert_eq!(spend_txn[0], spend_txn[1]);
5014 check_spends!(spend_txn[0], local_txn[0]);
5015 check_spends!(spend_txn[2], htlc_timeout);
5019 fn test_static_output_closing_tx() {
5020 let chanmon_cfgs = create_chanmon_cfgs(2);
5021 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5022 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5023 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5025 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5027 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5028 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5030 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5031 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5032 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5034 let spend_txn = check_spendable_outputs!(nodes[0], 2);
5035 assert_eq!(spend_txn.len(), 1);
5036 check_spends!(spend_txn[0], closing_tx);
5038 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5039 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5041 let spend_txn = check_spendable_outputs!(nodes[1], 2);
5042 assert_eq!(spend_txn.len(), 1);
5043 check_spends!(spend_txn[0], closing_tx);
5046 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5047 let chanmon_cfgs = create_chanmon_cfgs(2);
5048 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5049 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5050 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5051 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5053 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5055 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5056 // present in B's local commitment transaction, but none of A's commitment transactions.
5057 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5058 check_added_monitors!(nodes[1], 1);
5060 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5061 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5062 let events = nodes[0].node.get_and_clear_pending_events();
5063 assert_eq!(events.len(), 1);
5065 Event::PaymentSent { payment_preimage } => {
5066 assert_eq!(payment_preimage, our_payment_preimage);
5068 _ => panic!("Unexpected event"),
5071 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5072 check_added_monitors!(nodes[0], 1);
5073 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5074 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5075 check_added_monitors!(nodes[1], 1);
5077 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5078 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5079 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5080 header.prev_blockhash = header.bitcoin_hash();
5082 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5083 check_closed_broadcast!(nodes[1], false);
5084 check_added_monitors!(nodes[1], 1);
5087 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5088 let chanmon_cfgs = create_chanmon_cfgs(2);
5089 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5090 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5091 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5092 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5094 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();
5095 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5096 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5097 check_added_monitors!(nodes[0], 1);
5099 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5101 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5102 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5103 // to "time out" the HTLC.
5105 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5107 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5108 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5109 header.prev_blockhash = header.bitcoin_hash();
5111 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5112 check_closed_broadcast!(nodes[0], false);
5113 check_added_monitors!(nodes[0], 1);
5116 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5117 let chanmon_cfgs = create_chanmon_cfgs(3);
5118 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5119 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5120 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5121 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5123 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5124 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5125 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5126 // actually revoked.
5127 let htlc_value = if use_dust { 50000 } else { 3000000 };
5128 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5129 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5130 expect_pending_htlcs_forwardable!(nodes[1]);
5131 check_added_monitors!(nodes[1], 1);
5133 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5134 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5135 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5136 check_added_monitors!(nodes[0], 1);
5137 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5138 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5139 check_added_monitors!(nodes[1], 1);
5140 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5141 check_added_monitors!(nodes[1], 1);
5142 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5144 if check_revoke_no_close {
5145 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5146 check_added_monitors!(nodes[0], 1);
5149 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5150 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5151 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5152 header.prev_blockhash = header.bitcoin_hash();
5154 if !check_revoke_no_close {
5155 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5156 check_closed_broadcast!(nodes[0], false);
5157 check_added_monitors!(nodes[0], 1);
5159 expect_payment_failed!(nodes[0], our_payment_hash, true);
5163 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5164 // There are only a few cases to test here:
5165 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5166 // broadcastable commitment transactions result in channel closure,
5167 // * its included in an unrevoked-but-previous remote commitment transaction,
5168 // * its included in the latest remote or local commitment transactions.
5169 // We test each of the three possible commitment transactions individually and use both dust and
5171 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5172 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5173 // tested for at least one of the cases in other tests.
5175 fn htlc_claim_single_commitment_only_a() {
5176 do_htlc_claim_local_commitment_only(true);
5177 do_htlc_claim_local_commitment_only(false);
5179 do_htlc_claim_current_remote_commitment_only(true);
5180 do_htlc_claim_current_remote_commitment_only(false);
5184 fn htlc_claim_single_commitment_only_b() {
5185 do_htlc_claim_previous_remote_commitment_only(true, false);
5186 do_htlc_claim_previous_remote_commitment_only(false, false);
5187 do_htlc_claim_previous_remote_commitment_only(true, true);
5188 do_htlc_claim_previous_remote_commitment_only(false, true);
5191 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>)
5192 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5195 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);
5199 // 0: node1 fails backward
5200 // 1: final node fails backward
5201 // 2: payment completed but the user rejects the payment
5202 // 3: final node fails backward (but tamper onion payloads from node0)
5203 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5204 // 200: trigger error in the final node and tamper returning fail_htlc
5205 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>)
5206 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5207 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5211 // reset block height
5212 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5213 for ix in 0..nodes.len() {
5214 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5217 macro_rules! expect_event {
5218 ($node: expr, $event_type: path) => {{
5219 let events = $node.node.get_and_clear_pending_events();
5220 assert_eq!(events.len(), 1);
5222 $event_type { .. } => {},
5223 _ => panic!("Unexpected event"),
5228 macro_rules! expect_htlc_forward {
5230 expect_event!($node, Event::PendingHTLCsForwardable);
5231 $node.node.process_pending_htlc_forwards();
5235 // 0 ~~> 2 send payment
5236 nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5237 check_added_monitors!(nodes[0], 1);
5238 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5239 // temper update_add (0 => 1)
5240 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5241 if test_case == 0 || test_case == 3 || test_case == 100 {
5242 callback_msg(&mut update_add_0);
5245 // 0 => 1 update_add & CS
5246 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5247 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5249 let update_1_0 = match test_case {
5250 0|100 => { // intermediate node failure; fail backward to 0
5251 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5252 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));
5255 1|2|3|200 => { // final node failure; forwarding to 2
5256 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5258 if test_case != 200 {
5261 expect_htlc_forward!(&nodes[1]);
5263 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5264 check_added_monitors!(&nodes[1], 1);
5265 assert_eq!(update_1.update_add_htlcs.len(), 1);
5266 // tamper update_add (1 => 2)
5267 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5268 if test_case != 3 && test_case != 200 {
5269 callback_msg(&mut update_add_1);
5273 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5274 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5276 if test_case == 2 || test_case == 200 {
5277 expect_htlc_forward!(&nodes[2]);
5278 expect_event!(&nodes[2], Event::PaymentReceived);
5280 expect_pending_htlcs_forwardable!(nodes[2]);
5283 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5284 if test_case == 2 || test_case == 200 {
5285 check_added_monitors!(&nodes[2], 1);
5287 assert!(update_2_1.update_fail_htlcs.len() == 1);
5289 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5290 if test_case == 200 {
5291 callback_fail(&mut fail_msg);
5295 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5296 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5298 // backward fail on 1
5299 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5300 assert!(update_1_0.update_fail_htlcs.len() == 1);
5303 _ => unreachable!(),
5306 // 1 => 0 commitment_signed_dance
5307 if update_1_0.update_fail_htlcs.len() > 0 {
5308 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5309 if test_case == 100 {
5310 callback_fail(&mut fail_msg);
5312 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5314 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5317 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5319 let events = nodes[0].node.get_and_clear_pending_events();
5320 assert_eq!(events.len(), 1);
5321 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5322 assert_eq!(*rejected_by_dest, !expected_retryable);
5323 assert_eq!(*error_code, expected_error_code);
5325 panic!("Uexpected event");
5328 let events = nodes[0].node.get_and_clear_pending_msg_events();
5329 if expected_channel_update.is_some() {
5330 assert_eq!(events.len(), 1);
5332 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5334 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5335 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5336 panic!("channel_update not found!");
5339 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5340 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5341 assert!(*short_channel_id == *expected_short_channel_id);
5342 assert!(*is_permanent == *expected_is_permanent);
5344 panic!("Unexpected message event");
5347 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5348 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5349 assert!(*node_id == *expected_node_id);
5350 assert!(*is_permanent == *expected_is_permanent);
5352 panic!("Unexpected message event");
5357 _ => panic!("Unexpected message event"),
5360 assert_eq!(events.len(), 0);
5364 impl msgs::ChannelUpdate {
5365 fn dummy() -> msgs::ChannelUpdate {
5366 use secp256k1::ffi::Signature as FFISignature;
5367 use secp256k1::Signature;
5368 msgs::ChannelUpdate {
5369 signature: Signature::from(FFISignature::new()),
5370 contents: msgs::UnsignedChannelUpdate {
5371 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
5372 short_channel_id: 0,
5375 cltv_expiry_delta: 0,
5376 htlc_minimum_msat: 0,
5378 fee_proportional_millionths: 0,
5379 excess_data: vec![],
5385 struct BogusOnionHopData {
5388 impl BogusOnionHopData {
5389 fn new(orig: msgs::OnionHopData) -> Self {
5390 Self { data: orig.encode() }
5393 impl Writeable for BogusOnionHopData {
5394 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5395 writer.write_all(&self.data[..])
5400 fn test_onion_failure() {
5401 use ln::msgs::ChannelUpdate;
5402 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5405 const BADONION: u16 = 0x8000;
5406 const PERM: u16 = 0x4000;
5407 const NODE: u16 = 0x2000;
5408 const UPDATE: u16 = 0x1000;
5410 let chanmon_cfgs = create_chanmon_cfgs(3);
5411 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5412 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5413 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5414 for node in nodes.iter() {
5415 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5417 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported())];
5418 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5419 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5421 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5423 // intermediate node failure
5424 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5425 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5426 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5427 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5428 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5429 let mut new_payloads = Vec::new();
5430 for payload in onion_payloads.drain(..) {
5431 new_payloads.push(BogusOnionHopData::new(payload));
5433 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5434 // describing a length-1 TLV payload, which is obviously bogus.
5435 new_payloads[0].data[0] = 1;
5436 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5437 }, ||{}, 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
5439 // final node failure
5440 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5441 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5442 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5443 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5444 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5445 let mut new_payloads = Vec::new();
5446 for payload in onion_payloads.drain(..) {
5447 new_payloads.push(BogusOnionHopData::new(payload));
5449 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5450 // length-1 TLV payload, which is obviously bogus.
5451 new_payloads[1].data[0] = 1;
5452 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5453 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5455 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5456 // receiving simulated fail messages
5457 // intermediate node failure
5458 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5460 msg.amount_msat -= 1;
5462 // and tamper returning error message
5463 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5464 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5465 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5466 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5468 // final node failure
5469 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5470 // and tamper returning error message
5471 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5472 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5473 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5475 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5476 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5478 // intermediate node failure
5479 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5480 msg.amount_msat -= 1;
5482 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5483 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5484 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5485 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5487 // final node failure
5488 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5489 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5490 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5491 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5493 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5494 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5496 // intermediate node failure
5497 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5498 msg.amount_msat -= 1;
5500 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5501 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5502 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5504 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5505 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5507 // final node failure
5508 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5509 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5510 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5511 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5513 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5514 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5516 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5517 Some(BADONION|PERM|4), None);
5519 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5520 Some(BADONION|PERM|5), None);
5522 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5523 Some(BADONION|PERM|6), None);
5525 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5526 msg.amount_msat -= 1;
5528 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5529 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5530 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5531 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5533 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5534 msg.amount_msat -= 1;
5536 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5537 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5538 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5539 // short_channel_id from the processing node
5540 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5542 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5543 msg.amount_msat -= 1;
5545 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5546 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5547 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5548 // short_channel_id from the processing node
5549 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5551 let mut bogus_route = route.clone();
5552 bogus_route.paths[0][1].short_channel_id -= 1;
5553 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5554 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5556 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5557 let mut bogus_route = route.clone();
5558 let route_len = bogus_route.paths[0].len();
5559 bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5560 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5562 //TODO: with new config API, we will be able to generate both valid and
5563 //invalid channel_update cases.
5564 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5565 msg.amount_msat -= 1;
5566 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5568 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5569 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5570 msg.cltv_expiry -= 1;
5571 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5573 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5574 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5575 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5577 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5578 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5580 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5581 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5582 }, false, Some(PERM|15), None);
5584 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5585 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5586 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5588 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5589 }, || {}, true, Some(17), None);
5591 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5592 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5593 for f in pending_forwards.iter_mut() {
5595 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5596 forward_info.outgoing_cltv_value += 1,
5601 }, true, Some(18), None);
5603 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5604 // violate amt_to_forward > msg.amount_msat
5605 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5606 for f in pending_forwards.iter_mut() {
5608 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5609 forward_info.amt_to_forward -= 1,
5614 }, true, Some(19), None);
5616 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5617 // disconnect event to the channel between nodes[1] ~ nodes[2]
5618 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5619 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5620 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5621 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5623 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5624 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5625 let mut route = route.clone();
5627 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5628 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5629 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5630 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5631 msg.cltv_expiry = htlc_cltv;
5632 msg.onion_routing_packet = onion_packet;
5633 }, ||{}, true, Some(21), None);
5638 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5639 let chanmon_cfgs = create_chanmon_cfgs(2);
5640 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5641 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5642 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5643 //Force duplicate channel ids
5644 for node in nodes.iter() {
5645 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5648 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5649 let channel_value_satoshis=10000;
5650 let push_msat=10001;
5651 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5652 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5653 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &node0_to_1_send_open_channel);
5655 //Create a second channel with a channel_id collision
5656 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5660 fn bolt2_open_channel_sending_node_checks_part2() {
5661 let chanmon_cfgs = create_chanmon_cfgs(2);
5662 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5663 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5664 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5666 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5667 let channel_value_satoshis=2^24;
5668 let push_msat=10001;
5669 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5671 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5672 let channel_value_satoshis=10000;
5673 // Test when push_msat is equal to 1000 * funding_satoshis.
5674 let push_msat=1000*channel_value_satoshis+1;
5675 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5677 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5678 let channel_value_satoshis=10000;
5679 let push_msat=10001;
5680 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
5681 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5682 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5684 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5685 // 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
5686 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5688 // 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.
5689 assert!(BREAKDOWN_TIMEOUT>0);
5690 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5692 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5693 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5694 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5696 // 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.
5697 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5698 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5699 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5700 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5701 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5704 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5705 // 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.
5706 //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.
5709 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5710 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5711 let chanmon_cfgs = create_chanmon_cfgs(2);
5712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5714 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5715 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5716 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5717 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5719 route.paths[0][0].fee_msat = 100;
5721 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5722 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
5723 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5724 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5728 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5729 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5730 let chanmon_cfgs = create_chanmon_cfgs(2);
5731 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5732 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5733 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5734 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5735 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5736 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5738 route.paths[0][0].fee_msat = 0;
5740 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5741 assert_eq!(err, "Cannot send 0-msat HTLC"));
5742 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5743 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5747 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5748 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5749 let chanmon_cfgs = create_chanmon_cfgs(2);
5750 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5751 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5752 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5753 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5754 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5755 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5757 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5758 check_added_monitors!(nodes[0], 1);
5759 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5760 updates.update_add_htlcs[0].amount_msat = 0;
5762 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5763 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5764 check_closed_broadcast!(nodes[1], true).unwrap();
5765 check_added_monitors!(nodes[1], 1);
5769 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5770 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5771 //It is enforced when constructing a route.
5772 let chanmon_cfgs = create_chanmon_cfgs(2);
5773 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5774 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5775 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5776 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::supported(), InitFeatures::supported());
5777 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5778 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5780 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
5781 assert_eq!(err, "Channel CLTV overflowed?!"));
5785 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5786 //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.
5787 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5788 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
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, 1000000, 0, InitFeatures::supported(), InitFeatures::supported());
5794 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5796 for i in 0..max_accepted_htlcs {
5797 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5798 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5799 let payment_event = {
5800 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5801 check_added_monitors!(nodes[0], 1);
5803 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5804 assert_eq!(events.len(), 1);
5805 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5806 assert_eq!(htlcs[0].htlc_id, i);
5810 SendEvent::from_event(events.remove(0))
5812 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5813 check_added_monitors!(nodes[1], 0);
5814 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5816 expect_pending_htlcs_forwardable!(nodes[1]);
5817 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5819 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5820 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5821 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5822 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
5824 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5825 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5829 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5830 //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.
5831 let chanmon_cfgs = create_chanmon_cfgs(2);
5832 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5833 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5834 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5835 let channel_value = 100000;
5836 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::supported(), InitFeatures::supported());
5837 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5839 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5841 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5842 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5843 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5844 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
5846 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5847 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);
5849 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5852 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5854 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5855 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5856 let chanmon_cfgs = create_chanmon_cfgs(2);
5857 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5858 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5859 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5860 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5861 let htlc_minimum_msat: u64;
5863 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5864 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5865 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5867 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5868 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5869 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5870 check_added_monitors!(nodes[0], 1);
5871 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5872 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5873 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5874 assert!(nodes[1].node.list_channels().is_empty());
5875 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5876 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5877 check_added_monitors!(nodes[1], 1);
5881 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5882 //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
5883 let chanmon_cfgs = create_chanmon_cfgs(2);
5884 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5885 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5886 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5887 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5889 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5891 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5892 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5893 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5894 check_added_monitors!(nodes[0], 1);
5895 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5897 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5898 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5900 assert!(nodes[1].node.list_channels().is_empty());
5901 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5902 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5903 check_added_monitors!(nodes[1], 1);
5907 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5908 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5909 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5910 let chanmon_cfgs = create_chanmon_cfgs(2);
5911 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5912 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5913 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5914 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5915 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5916 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5918 let session_priv = SecretKey::from_slice(&{
5919 let mut session_key = [0; 32];
5920 let mut rng = thread_rng();
5921 rng.fill_bytes(&mut session_key);
5923 }).expect("RNG is bad!");
5925 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5926 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
5927 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
5928 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5930 let mut msg = msgs::UpdateAddHTLC {
5934 payment_hash: our_payment_hash,
5935 cltv_expiry: htlc_cltv,
5936 onion_routing_packet: onion_packet.clone(),
5939 for i in 0..super::channel::OUR_MAX_HTLCS {
5940 msg.htlc_id = i as u64;
5941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5943 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5946 assert!(nodes[1].node.list_channels().is_empty());
5947 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5948 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5949 check_added_monitors!(nodes[1], 1);
5953 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5954 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5955 let chanmon_cfgs = create_chanmon_cfgs(2);
5956 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5957 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5958 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5959 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
5960 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5961 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5962 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5963 check_added_monitors!(nodes[0], 1);
5964 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5965 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5966 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5968 assert!(nodes[1].node.list_channels().is_empty());
5969 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5970 assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
5971 check_added_monitors!(nodes[1], 1);
5975 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5976 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5977 let chanmon_cfgs = create_chanmon_cfgs(2);
5978 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5979 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5980 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5981 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5982 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5983 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5984 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5985 check_added_monitors!(nodes[0], 1);
5986 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5987 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5988 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5990 assert!(nodes[1].node.list_channels().is_empty());
5991 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5992 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
5993 check_added_monitors!(nodes[1], 1);
5997 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5998 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5999 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6000 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6001 let chanmon_cfgs = create_chanmon_cfgs(2);
6002 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6003 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6004 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6005 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6006 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6007 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6008 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6009 check_added_monitors!(nodes[0], 1);
6010 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6011 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6013 //Disconnect and Reconnect
6014 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6015 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6016 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6017 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6018 assert_eq!(reestablish_1.len(), 1);
6019 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6020 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6021 assert_eq!(reestablish_2.len(), 1);
6022 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6023 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6024 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6025 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6028 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6029 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6030 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6031 check_added_monitors!(nodes[1], 1);
6032 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6034 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6036 assert!(nodes[1].node.list_channels().is_empty());
6037 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6038 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6039 check_added_monitors!(nodes[1], 1);
6043 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6044 //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.
6046 let chanmon_cfgs = create_chanmon_cfgs(2);
6047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6049 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6050 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6052 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6053 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6054 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6055 check_added_monitors!(nodes[0], 1);
6056 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6057 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6059 let update_msg = msgs::UpdateFulfillHTLC{
6062 payment_preimage: our_payment_preimage,
6065 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6067 assert!(nodes[0].node.list_channels().is_empty());
6068 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6069 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6070 check_added_monitors!(nodes[0], 1);
6074 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6075 //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.
6077 let chanmon_cfgs = create_chanmon_cfgs(2);
6078 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6079 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6080 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6081 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6083 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6084 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6085 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6086 check_added_monitors!(nodes[0], 1);
6087 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6088 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6090 let update_msg = msgs::UpdateFailHTLC{
6093 reason: msgs::OnionErrorPacket { data: Vec::new()},
6096 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6098 assert!(nodes[0].node.list_channels().is_empty());
6099 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6100 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6101 check_added_monitors!(nodes[0], 1);
6105 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6106 //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.
6108 let chanmon_cfgs = create_chanmon_cfgs(2);
6109 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6110 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6111 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6112 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6114 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6115 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6116 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6117 check_added_monitors!(nodes[0], 1);
6118 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6119 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6121 let update_msg = msgs::UpdateFailMalformedHTLC{
6124 sha256_of_onion: [1; 32],
6125 failure_code: 0x8000,
6128 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6130 assert!(nodes[0].node.list_channels().is_empty());
6131 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6132 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6133 check_added_monitors!(nodes[0], 1);
6137 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6138 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6140 let chanmon_cfgs = create_chanmon_cfgs(2);
6141 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6142 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6143 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6144 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6146 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6148 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6149 check_added_monitors!(nodes[1], 1);
6151 let events = nodes[1].node.get_and_clear_pending_msg_events();
6152 assert_eq!(events.len(), 1);
6153 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6155 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, .. } } => {
6156 assert!(update_add_htlcs.is_empty());
6157 assert_eq!(update_fulfill_htlcs.len(), 1);
6158 assert!(update_fail_htlcs.is_empty());
6159 assert!(update_fail_malformed_htlcs.is_empty());
6160 assert!(update_fee.is_none());
6161 update_fulfill_htlcs[0].clone()
6163 _ => panic!("Unexpected event"),
6167 update_fulfill_msg.htlc_id = 1;
6169 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6171 assert!(nodes[0].node.list_channels().is_empty());
6172 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6173 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6174 check_added_monitors!(nodes[0], 1);
6178 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6179 //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.
6181 let chanmon_cfgs = create_chanmon_cfgs(2);
6182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6185 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6187 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6189 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6190 check_added_monitors!(nodes[1], 1);
6192 let events = nodes[1].node.get_and_clear_pending_msg_events();
6193 assert_eq!(events.len(), 1);
6194 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6196 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, .. } } => {
6197 assert!(update_add_htlcs.is_empty());
6198 assert_eq!(update_fulfill_htlcs.len(), 1);
6199 assert!(update_fail_htlcs.is_empty());
6200 assert!(update_fail_malformed_htlcs.is_empty());
6201 assert!(update_fee.is_none());
6202 update_fulfill_htlcs[0].clone()
6204 _ => panic!("Unexpected event"),
6208 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6210 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6212 assert!(nodes[0].node.list_channels().is_empty());
6213 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6214 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6215 check_added_monitors!(nodes[0], 1);
6219 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6220 //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.
6222 let chanmon_cfgs = create_chanmon_cfgs(2);
6223 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6224 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6225 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6226 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6227 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6228 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6229 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6230 check_added_monitors!(nodes[0], 1);
6232 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6233 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6235 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6236 check_added_monitors!(nodes[1], 0);
6237 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6239 let events = nodes[1].node.get_and_clear_pending_msg_events();
6241 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6243 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, .. } } => {
6244 assert!(update_add_htlcs.is_empty());
6245 assert!(update_fulfill_htlcs.is_empty());
6246 assert!(update_fail_htlcs.is_empty());
6247 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6248 assert!(update_fee.is_none());
6249 update_fail_malformed_htlcs[0].clone()
6251 _ => panic!("Unexpected event"),
6254 update_msg.failure_code &= !0x8000;
6255 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6257 assert!(nodes[0].node.list_channels().is_empty());
6258 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6259 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6260 check_added_monitors!(nodes[0], 1);
6264 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6265 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6266 // * 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.
6268 let chanmon_cfgs = create_chanmon_cfgs(3);
6269 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6270 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6271 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6272 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6273 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6275 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6276 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6279 let mut payment_event = {
6280 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6281 check_added_monitors!(nodes[0], 1);
6282 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6283 assert_eq!(events.len(), 1);
6284 SendEvent::from_event(events.remove(0))
6286 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6287 check_added_monitors!(nodes[1], 0);
6288 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6289 expect_pending_htlcs_forwardable!(nodes[1]);
6290 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6291 assert_eq!(events_2.len(), 1);
6292 check_added_monitors!(nodes[1], 1);
6293 payment_event = SendEvent::from_event(events_2.remove(0));
6294 assert_eq!(payment_event.msgs.len(), 1);
6297 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6298 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6299 check_added_monitors!(nodes[2], 0);
6300 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6302 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6303 assert_eq!(events_3.len(), 1);
6304 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6306 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 } } => {
6307 assert!(update_add_htlcs.is_empty());
6308 assert!(update_fulfill_htlcs.is_empty());
6309 assert!(update_fail_htlcs.is_empty());
6310 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6311 assert!(update_fee.is_none());
6312 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6314 _ => panic!("Unexpected event"),
6318 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6320 check_added_monitors!(nodes[1], 0);
6321 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6322 expect_pending_htlcs_forwardable!(nodes[1]);
6323 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6324 assert_eq!(events_4.len(), 1);
6326 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6328 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, .. } } => {
6329 assert!(update_add_htlcs.is_empty());
6330 assert!(update_fulfill_htlcs.is_empty());
6331 assert_eq!(update_fail_htlcs.len(), 1);
6332 assert!(update_fail_malformed_htlcs.is_empty());
6333 assert!(update_fee.is_none());
6335 _ => panic!("Unexpected event"),
6338 check_added_monitors!(nodes[1], 1);
6341 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6342 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6343 // 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
6344 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6346 let chanmon_cfgs = create_chanmon_cfgs(2);
6347 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6348 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6349 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6350 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6352 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6354 // We route 2 dust-HTLCs between A and B
6355 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6356 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6357 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6359 // Cache one local commitment tx as previous
6360 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6362 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6363 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6364 check_added_monitors!(nodes[1], 0);
6365 expect_pending_htlcs_forwardable!(nodes[1]);
6366 check_added_monitors!(nodes[1], 1);
6368 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6369 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6370 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6371 check_added_monitors!(nodes[0], 1);
6373 // Cache one local commitment tx as lastest
6374 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6376 let events = nodes[0].node.get_and_clear_pending_msg_events();
6378 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6379 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6381 _ => panic!("Unexpected event"),
6384 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6385 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6387 _ => panic!("Unexpected event"),
6390 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6391 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6392 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6394 if announce_latest {
6395 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6397 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6400 check_closed_broadcast!(nodes[0], false);
6401 check_added_monitors!(nodes[0], 1);
6403 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6404 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6405 let events = nodes[0].node.get_and_clear_pending_events();
6406 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6407 assert_eq!(events.len(), 2);
6408 let mut first_failed = false;
6409 for event in events {
6411 Event::PaymentFailed { payment_hash, .. } => {
6412 if payment_hash == payment_hash_1 {
6413 assert!(!first_failed);
6414 first_failed = true;
6416 assert_eq!(payment_hash, payment_hash_2);
6419 _ => panic!("Unexpected event"),
6425 fn test_failure_delay_dust_htlc_local_commitment() {
6426 do_test_failure_delay_dust_htlc_local_commitment(true);
6427 do_test_failure_delay_dust_htlc_local_commitment(false);
6431 fn test_no_failure_dust_htlc_local_commitment() {
6432 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6433 // prone to error, we test here that a dummy transaction don't fail them.
6435 let chanmon_cfgs = create_chanmon_cfgs(2);
6436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6439 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6442 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6444 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6445 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6447 // We route 2 dust-HTLCs between A and B
6448 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6449 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6451 // Build a dummy invalid transaction trying to spend a commitment tx
6453 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6454 script_sig: Script::new(),
6456 witness: Vec::new(),
6460 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6464 let dummy_tx = Transaction {
6471 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6472 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6473 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6474 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6475 // We broadcast a few more block to check everything is all right
6476 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6477 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6478 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6480 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6481 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6484 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6485 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6486 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6487 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6488 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6489 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6490 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6492 let chanmon_cfgs = create_chanmon_cfgs(3);
6493 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6494 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6495 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6496 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6498 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6500 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6501 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6503 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6504 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6506 // We revoked bs_commitment_tx
6508 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6509 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6512 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6513 let mut timeout_tx = Vec::new();
6515 // We fail dust-HTLC 1 by broadcast of local commitment tx
6516 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6517 check_closed_broadcast!(nodes[0], false);
6518 check_added_monitors!(nodes[0], 1);
6519 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6520 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6521 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6522 expect_payment_failed!(nodes[0], dust_hash, true);
6523 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6524 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6525 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6526 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6527 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6528 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6529 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6530 expect_payment_failed!(nodes[0], non_dust_hash, true);
6532 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6533 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6534 check_closed_broadcast!(nodes[0], false);
6535 check_added_monitors!(nodes[0], 1);
6536 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6537 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6538 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6539 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6541 expect_payment_failed!(nodes[0], dust_hash, true);
6542 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6543 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6544 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6545 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6546 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6547 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6548 expect_payment_failed!(nodes[0], non_dust_hash, true);
6550 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6552 let events = nodes[0].node.get_and_clear_pending_events();
6553 assert_eq!(events.len(), 2);
6556 Event::PaymentFailed { payment_hash, .. } => {
6557 if payment_hash == dust_hash { first = true; }
6558 else { first = false; }
6560 _ => panic!("Unexpected event"),
6563 Event::PaymentFailed { payment_hash, .. } => {
6564 if first { assert_eq!(payment_hash, non_dust_hash); }
6565 else { assert_eq!(payment_hash, dust_hash); }
6567 _ => panic!("Unexpected event"),
6574 fn test_sweep_outbound_htlc_failure_update() {
6575 do_test_sweep_outbound_htlc_failure_update(false, true);
6576 do_test_sweep_outbound_htlc_failure_update(false, false);
6577 do_test_sweep_outbound_htlc_failure_update(true, false);
6581 fn test_upfront_shutdown_script() {
6582 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6583 // enforce it at shutdown message
6585 let mut config = UserConfig::default();
6586 config.channel_options.announced_channel = true;
6587 config.peer_channel_config_limits.force_announced_channel_preference = false;
6588 config.channel_options.commit_upfront_shutdown_pubkey = false;
6589 let user_cfgs = [None, Some(config), None];
6590 let chanmon_cfgs = create_chanmon_cfgs(3);
6591 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6592 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6593 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6595 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6596 let flags = InitFeatures::supported();
6597 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6598 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6599 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6600 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6601 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6602 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6603 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6604 check_added_monitors!(nodes[2], 1);
6606 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6607 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6608 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6609 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6610 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6611 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6612 let events = nodes[2].node.get_and_clear_pending_msg_events();
6613 assert_eq!(events.len(), 1);
6615 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6616 _ => panic!("Unexpected event"),
6619 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6620 let mut flags_no = InitFeatures::supported();
6621 flags_no.unset_upfront_shutdown_script();
6622 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6623 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6624 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6625 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6626 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6627 let events = nodes[1].node.get_and_clear_pending_msg_events();
6628 assert_eq!(events.len(), 1);
6630 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6631 _ => panic!("Unexpected event"),
6634 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6635 // channel smoothly, opt-out is from channel initiator here
6636 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6637 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6638 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6639 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6640 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6641 let events = nodes[0].node.get_and_clear_pending_msg_events();
6642 assert_eq!(events.len(), 1);
6644 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6645 _ => panic!("Unexpected event"),
6648 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6649 //// channel smoothly
6650 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6651 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6652 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6653 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6654 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6655 let events = nodes[0].node.get_and_clear_pending_msg_events();
6656 assert_eq!(events.len(), 2);
6658 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6659 _ => panic!("Unexpected event"),
6662 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6663 _ => panic!("Unexpected event"),
6668 fn test_user_configurable_csv_delay() {
6669 // We test our channel constructors yield errors when we pass them absurd csv delay
6671 let mut low_our_to_self_config = UserConfig::default();
6672 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6673 let mut high_their_to_self_config = UserConfig::default();
6674 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6675 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6676 let chanmon_cfgs = create_chanmon_cfgs(2);
6677 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6678 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6679 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6681 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6682 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())));
6683 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) {
6685 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6686 _ => panic!("Unexpected event"),
6688 } else { assert!(false) }
6690 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6691 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6692 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6693 open_channel.to_self_delay = 200;
6694 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::supported(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6696 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6697 _ => panic!("Unexpected event"),
6699 } else { assert!(false); }
6701 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6702 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6703 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6704 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6705 accept_channel.to_self_delay = 200;
6706 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
6707 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6709 &ErrorAction::SendErrorMessage { ref msg } => {
6710 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6712 _ => { assert!(false); }
6714 } else { assert!(false); }
6716 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6717 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6718 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6719 open_channel.to_self_delay = 200;
6720 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::supported(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
6722 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6723 _ => panic!("Unexpected event"),
6725 } else { assert!(false); }
6729 fn test_data_loss_protect() {
6730 // We want to be sure that :
6731 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6732 // * we close channel in case of detecting other being fallen behind
6733 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6739 let chanmon_cfgs = create_chanmon_cfgs(2);
6740 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6741 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6742 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6744 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6746 // Cache node A state before any channel update
6747 let previous_node_state = nodes[0].node.encode();
6748 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6749 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6751 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6752 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6754 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6755 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6757 // Restore node A from previous state
6758 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6759 let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6760 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6761 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6762 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6763 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6764 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6766 let mut channel_monitors = HashMap::new();
6767 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6768 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6769 keys_manager: &keys_manager,
6770 fee_estimator: &fee_estimator,
6772 logger: Arc::clone(&logger),
6773 tx_broadcaster: &tx_broadcaster,
6774 default_config: UserConfig::default(),
6775 channel_monitors: &mut channel_monitors,
6778 nodes[0].node = &node_state_0;
6779 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6780 nodes[0].chan_monitor = &monitor;
6781 nodes[0].chain_monitor = chain_monitor;
6783 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6784 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6785 nodes[0].block_notifier.register_listener(nodes[0].node);
6787 check_added_monitors!(nodes[0], 1);
6789 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6790 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6792 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6794 // Check we update monitor following learning of per_commitment_point from B
6795 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6796 check_added_monitors!(nodes[0], 2);
6799 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6800 assert_eq!(node_txn.len(), 0);
6803 let mut reestablish_1 = Vec::with_capacity(1);
6804 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6805 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6806 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6807 reestablish_1.push(msg.clone());
6808 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6809 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6811 &ErrorAction::SendErrorMessage { ref msg } => {
6812 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");
6814 _ => panic!("Unexpected event!"),
6817 panic!("Unexpected event")
6821 // Check we close channel detecting A is fallen-behind
6822 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6823 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6824 check_added_monitors!(nodes[1], 1);
6827 // Check A is able to claim to_remote output
6828 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6829 assert_eq!(node_txn.len(), 1);
6830 check_spends!(node_txn[0], chan.3);
6831 assert_eq!(node_txn[0].output.len(), 2);
6832 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6833 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
6834 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
6835 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6836 assert_eq!(spend_txn.len(), 1);
6837 check_spends!(spend_txn[0], node_txn[0]);
6841 fn test_check_htlc_underpaying() {
6842 // Send payment through A -> B but A is maliciously
6843 // sending a probe payment (i.e less than expected value0
6844 // to B, B should refuse payment.
6846 let chanmon_cfgs = create_chanmon_cfgs(2);
6847 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6848 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6849 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6851 // Create some initial channels
6852 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6854 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6856 // Node 3 is expecting payment of 100_000 but receive 10_000,
6857 // fail htlc like we didn't know the preimage.
6858 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
6859 nodes[1].node.process_pending_htlc_forwards();
6861 let events = nodes[1].node.get_and_clear_pending_msg_events();
6862 assert_eq!(events.len(), 1);
6863 let (update_fail_htlc, commitment_signed) = match events[0] {
6864 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 } } => {
6865 assert!(update_add_htlcs.is_empty());
6866 assert!(update_fulfill_htlcs.is_empty());
6867 assert_eq!(update_fail_htlcs.len(), 1);
6868 assert!(update_fail_malformed_htlcs.is_empty());
6869 assert!(update_fee.is_none());
6870 (update_fail_htlcs[0].clone(), commitment_signed)
6872 _ => panic!("Unexpected event"),
6874 check_added_monitors!(nodes[1], 1);
6876 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6877 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6879 // 10_000 msat as u64, followed by a height of 99 as u32
6880 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
6881 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
6882 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6883 nodes[1].node.get_and_clear_pending_events();
6887 fn test_announce_disable_channels() {
6888 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6889 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6891 let chanmon_cfgs = create_chanmon_cfgs(2);
6892 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6893 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6894 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6896 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6897 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6898 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6901 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6902 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6904 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6905 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6906 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6907 assert_eq!(msg_events.len(), 3);
6908 for e in msg_events {
6910 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6911 let short_id = msg.contents.short_channel_id;
6912 // Check generated channel_update match list in PendingChannelUpdate
6913 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6914 panic!("Generated ChannelUpdate for wrong chan!");
6917 _ => panic!("Unexpected event"),
6921 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6922 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6923 assert_eq!(reestablish_1.len(), 3);
6924 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6925 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6926 assert_eq!(reestablish_2.len(), 3);
6928 // Reestablish chan_1
6929 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6930 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6931 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6932 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6933 // Reestablish chan_2
6934 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6935 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6936 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6937 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6938 // Reestablish chan_3
6939 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6940 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6941 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6942 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6944 nodes[0].node.timer_chan_freshness_every_min();
6945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6949 fn test_bump_penalty_txn_on_revoked_commitment() {
6950 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6951 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6953 let chanmon_cfgs = create_chanmon_cfgs(2);
6954 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6955 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6956 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6958 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6959 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6960 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6961 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6963 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
6964 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6965 assert_eq!(revoked_txn[0].output.len(), 4);
6966 assert_eq!(revoked_txn[0].input.len(), 1);
6967 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6968 let revoked_txid = revoked_txn[0].txid();
6970 let mut penalty_sum = 0;
6971 for outp in revoked_txn[0].output.iter() {
6972 if outp.script_pubkey.is_v0_p2wsh() {
6973 penalty_sum += outp.value;
6977 // Connect blocks to change height_timer range to see if we use right soonest_timelock
6978 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6980 // Actually revoke tx by claiming a HTLC
6981 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6982 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6983 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6984 check_added_monitors!(nodes[1], 1);
6986 // One or more justice tx should have been broadcast, check it
6990 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6991 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6992 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6993 assert_eq!(node_txn[0].output.len(), 1);
6994 check_spends!(node_txn[0], revoked_txn[0]);
6995 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6996 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6997 penalty_1 = node_txn[0].txid();
7001 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7002 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
7003 let mut penalty_2 = penalty_1;
7004 let mut feerate_2 = 0;
7006 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7007 assert_eq!(node_txn.len(), 1);
7008 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7009 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7010 assert_eq!(node_txn[0].output.len(), 1);
7011 check_spends!(node_txn[0], revoked_txn[0]);
7012 penalty_2 = node_txn[0].txid();
7013 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7014 assert_ne!(penalty_2, penalty_1);
7015 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7016 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7017 // Verify 25% bump heuristic
7018 assert!(feerate_2 * 100 >= feerate_1 * 125);
7022 assert_ne!(feerate_2, 0);
7024 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7025 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7027 let mut feerate_3 = 0;
7029 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7030 assert_eq!(node_txn.len(), 1);
7031 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7032 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7033 assert_eq!(node_txn[0].output.len(), 1);
7034 check_spends!(node_txn[0], revoked_txn[0]);
7035 penalty_3 = node_txn[0].txid();
7036 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7037 assert_ne!(penalty_3, penalty_2);
7038 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7039 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7040 // Verify 25% bump heuristic
7041 assert!(feerate_3 * 100 >= feerate_2 * 125);
7045 assert_ne!(feerate_3, 0);
7047 nodes[1].node.get_and_clear_pending_events();
7048 nodes[1].node.get_and_clear_pending_msg_events();
7052 fn test_bump_penalty_txn_on_revoked_htlcs() {
7053 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7054 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7056 let chanmon_cfgs = create_chanmon_cfgs(2);
7057 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7058 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7059 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7061 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7062 // Lock HTLC in both directions
7063 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7064 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7066 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7067 assert_eq!(revoked_local_txn[0].input.len(), 1);
7068 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7070 // Revoke local commitment tx
7071 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7073 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7074 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7075 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7076 check_closed_broadcast!(nodes[1], false);
7077 check_added_monitors!(nodes[1], 1);
7079 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7080 assert_eq!(revoked_htlc_txn.len(), 4);
7081 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7082 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7083 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7084 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7085 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7086 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7087 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7088 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7089 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7090 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7091 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7092 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7095 // Broadcast set of revoked txn on A
7096 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7097 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7099 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7100 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);
7105 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7106 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7107 // Verify claim tx are spending revoked HTLC txn
7108 assert_eq!(node_txn[4].input.len(), 2);
7109 assert_eq!(node_txn[4].output.len(), 1);
7110 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7111 first = node_txn[4].txid();
7112 // Store both feerates for later comparison
7113 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7114 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7115 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7119 // Connect three more block to see if bumped penalty are issued for HTLC txn
7120 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7121 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7123 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7124 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7126 check_spends!(node_txn[0], revoked_local_txn[0]);
7127 check_spends!(node_txn[1], revoked_local_txn[0]);
7132 // Few more blocks to confirm penalty txn
7133 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7134 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7135 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7137 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7138 assert_eq!(node_txn.len(), 1);
7140 assert_eq!(node_txn[0].input.len(), 2);
7141 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7142 // Verify bumped tx is different and 25% bump heuristic
7143 assert_ne!(first, node_txn[0].txid());
7144 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7145 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7146 assert!(feerate_2 * 100 > feerate_1 * 125);
7147 let txn = vec![node_txn[0].clone()];
7151 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7152 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7153 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7154 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7156 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7157 // We verify than no new transaction has been broadcast because previously
7158 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7159 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7160 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7161 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7162 // up bumped justice generation.
7163 assert_eq!(node_txn.len(), 0);
7166 check_closed_broadcast!(nodes[0], false);
7167 check_added_monitors!(nodes[0], 1);
7171 fn test_bump_penalty_txn_on_remote_commitment() {
7172 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7173 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7176 // Provide preimage for one
7177 // Check aggregation
7179 let chanmon_cfgs = create_chanmon_cfgs(2);
7180 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7181 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7182 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7184 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7185 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7186 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7188 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7189 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7190 assert_eq!(remote_txn[0].output.len(), 4);
7191 assert_eq!(remote_txn[0].input.len(), 1);
7192 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7194 // Claim a HTLC without revocation (provide B monitor with preimage)
7195 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7196 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7197 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7198 check_added_monitors!(nodes[1], 2);
7200 // One or more claim tx should have been broadcast, check it
7203 let feerate_timeout;
7204 let feerate_preimage;
7206 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7207 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7208 assert_eq!(node_txn[0].input.len(), 1);
7209 assert_eq!(node_txn[1].input.len(), 1);
7210 check_spends!(node_txn[0], remote_txn[0]);
7211 check_spends!(node_txn[1], remote_txn[0]);
7212 check_spends!(node_txn[2], chan.3);
7213 check_spends!(node_txn[3], node_txn[2]);
7214 check_spends!(node_txn[4], node_txn[2]);
7215 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7216 timeout = node_txn[0].txid();
7217 let index = node_txn[0].input[0].previous_output.vout;
7218 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7219 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7221 preimage = node_txn[1].txid();
7222 let index = node_txn[1].input[0].previous_output.vout;
7223 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7224 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7226 timeout = node_txn[1].txid();
7227 let index = node_txn[1].input[0].previous_output.vout;
7228 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7229 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7231 preimage = node_txn[0].txid();
7232 let index = node_txn[0].input[0].previous_output.vout;
7233 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7234 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7238 assert_ne!(feerate_timeout, 0);
7239 assert_ne!(feerate_preimage, 0);
7241 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7242 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7244 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7245 assert_eq!(node_txn.len(), 2);
7246 assert_eq!(node_txn[0].input.len(), 1);
7247 assert_eq!(node_txn[1].input.len(), 1);
7248 check_spends!(node_txn[0], remote_txn[0]);
7249 check_spends!(node_txn[1], remote_txn[0]);
7250 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7251 let index = node_txn[0].input[0].previous_output.vout;
7252 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7253 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7254 assert!(new_feerate * 100 > feerate_timeout * 125);
7255 assert_ne!(timeout, node_txn[0].txid());
7257 let index = node_txn[1].input[0].previous_output.vout;
7258 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7259 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7260 assert!(new_feerate * 100 > feerate_preimage * 125);
7261 assert_ne!(preimage, node_txn[1].txid());
7263 let index = node_txn[1].input[0].previous_output.vout;
7264 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7265 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7266 assert!(new_feerate * 100 > feerate_timeout * 125);
7267 assert_ne!(timeout, node_txn[1].txid());
7269 let index = node_txn[0].input[0].previous_output.vout;
7270 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7271 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7272 assert!(new_feerate * 100 > feerate_preimage * 125);
7273 assert_ne!(preimage, node_txn[0].txid());
7278 nodes[1].node.get_and_clear_pending_events();
7279 nodes[1].node.get_and_clear_pending_msg_events();
7283 fn test_set_outpoints_partial_claiming() {
7284 // - remote party claim tx, new bump tx
7285 // - disconnect remote claiming tx, new bump
7286 // - disconnect tx, see no tx anymore
7287 let chanmon_cfgs = create_chanmon_cfgs(2);
7288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7290 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7292 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7293 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7294 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7296 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7297 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7298 assert_eq!(remote_txn.len(), 3);
7299 assert_eq!(remote_txn[0].output.len(), 4);
7300 assert_eq!(remote_txn[0].input.len(), 1);
7301 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7302 check_spends!(remote_txn[1], remote_txn[0]);
7303 check_spends!(remote_txn[2], remote_txn[0]);
7305 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7306 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7307 // Provide node A with both preimage
7308 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7309 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7310 check_added_monitors!(nodes[0], 2);
7311 nodes[0].node.get_and_clear_pending_events();
7312 nodes[0].node.get_and_clear_pending_msg_events();
7314 // Connect blocks on node A commitment transaction
7315 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7316 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7317 check_closed_broadcast!(nodes[0], false);
7318 check_added_monitors!(nodes[0], 1);
7319 // Verify node A broadcast tx claiming both HTLCs
7321 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7322 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7323 assert_eq!(node_txn.len(), 4);
7324 check_spends!(node_txn[0], remote_txn[0]);
7325 check_spends!(node_txn[1], chan.3);
7326 check_spends!(node_txn[2], node_txn[1]);
7327 check_spends!(node_txn[3], node_txn[1]);
7328 assert_eq!(node_txn[0].input.len(), 2);
7332 // Connect blocks on node B
7333 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7334 check_closed_broadcast!(nodes[1], false);
7335 check_added_monitors!(nodes[1], 1);
7336 // Verify node B broadcast 2 HTLC-timeout txn
7337 let partial_claim_tx = {
7338 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7339 assert_eq!(node_txn.len(), 3);
7340 check_spends!(node_txn[1], node_txn[0]);
7341 check_spends!(node_txn[2], node_txn[0]);
7342 assert_eq!(node_txn[1].input.len(), 1);
7343 assert_eq!(node_txn[2].input.len(), 1);
7347 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7348 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7349 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7351 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7352 assert_eq!(node_txn.len(), 1);
7353 check_spends!(node_txn[0], remote_txn[0]);
7354 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7357 nodes[0].node.get_and_clear_pending_msg_events();
7359 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7360 nodes[0].block_notifier.block_disconnected(&header, 102);
7362 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7363 assert_eq!(node_txn.len(), 1);
7364 check_spends!(node_txn[0], remote_txn[0]);
7365 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7369 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7370 nodes[0].block_notifier.block_disconnected(&header, 101);
7371 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7373 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7374 assert_eq!(node_txn.len(), 0);
7380 fn test_counterparty_raa_skip_no_crash() {
7381 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7382 // commitment transaction, we would have happily carried on and provided them the next
7383 // commitment transaction based on one RAA forward. This would probably eventually have led to
7384 // channel closure, but it would not have resulted in funds loss. Still, our
7385 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7386 // check simply that the channel is closed in response to such an RAA, but don't check whether
7387 // we decide to punish our counterparty for revoking their funds (as we don't currently
7389 let chanmon_cfgs = create_chanmon_cfgs(2);
7390 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7391 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7392 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7393 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
7395 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7396 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7397 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7398 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7399 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7401 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7402 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7403 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7404 check_added_monitors!(nodes[1], 1);
7408 fn test_bump_txn_sanitize_tracking_maps() {
7409 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7410 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7412 let chanmon_cfgs = create_chanmon_cfgs(2);
7413 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7414 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7415 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7417 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7418 // Lock HTLC in both directions
7419 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7420 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7422 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7423 assert_eq!(revoked_local_txn[0].input.len(), 1);
7424 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7426 // Revoke local commitment tx
7427 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7429 // Broadcast set of revoked txn on A
7430 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7431 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7433 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7434 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7435 check_closed_broadcast!(nodes[0], false);
7436 check_added_monitors!(nodes[0], 1);
7438 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7439 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7440 check_spends!(node_txn[0], revoked_local_txn[0]);
7441 check_spends!(node_txn[1], revoked_local_txn[0]);
7442 check_spends!(node_txn[2], revoked_local_txn[0]);
7443 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7447 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7448 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7449 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7451 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7452 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7453 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7454 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7460 fn test_override_channel_config() {
7461 let chanmon_cfgs = create_chanmon_cfgs(2);
7462 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7463 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7464 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7466 // Node0 initiates a channel to node1 using the override config.
7467 let mut override_config = UserConfig::default();
7468 override_config.own_channel_config.our_to_self_delay = 200;
7470 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7472 // Assert the channel created by node0 is using the override config.
7473 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7474 assert_eq!(res.channel_flags, 0);
7475 assert_eq!(res.to_self_delay, 200);
7479 fn test_override_0msat_htlc_minimum() {
7480 let mut zero_config = UserConfig::default();
7481 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7482 let chanmon_cfgs = create_chanmon_cfgs(2);
7483 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7484 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7485 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7487 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7488 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7489 assert_eq!(res.htlc_minimum_msat, 1);
7491 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &res);
7492 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7493 assert_eq!(res.htlc_minimum_msat, 1);
7497 fn test_simple_payment_secret() {
7498 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7499 // features, however.
7500 let chanmon_cfgs = create_chanmon_cfgs(3);
7501 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7502 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7503 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7505 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
7506 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
7508 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7509 let payment_secret = PaymentSecret([0xdb; 32]);
7510 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
7511 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7512 // Claiming with all the correct values but the wrong secret should result in nothing...
7513 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7514 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7515 // ...but with the right secret we should be able to claim all the way back
7516 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7520 fn test_simple_mpp() {
7521 // Simple test of sending a multi-path payment.
7522 let chanmon_cfgs = create_chanmon_cfgs(4);
7523 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7524 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7525 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7527 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7528 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7529 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7530 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7532 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7533 let payment_secret = PaymentSecret([0xdb; 32]);
7534 let mut route = nodes[0].router.get_route(&nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
7535 let path = route.paths[0].clone();
7536 route.paths.push(path);
7537 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7538 route.paths[0][0].short_channel_id = chan_1_id;
7539 route.paths[0][1].short_channel_id = chan_3_id;
7540 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7541 route.paths[1][0].short_channel_id = chan_2_id;
7542 route.paths[1][1].short_channel_id = chan_4_id;
7543 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7544 // Claiming with all the correct values but the wrong secret should result in nothing...
7545 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7546 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7547 // ...but with the right secret we should be able to claim all the way back
7548 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7552 fn test_update_err_monitor_lockdown() {
7553 // Our monitor will lock update of local commitment transaction if a broadcastion condition
7554 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7555 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7557 // This scenario may happen in a watchtower setup, where watchtower process a block height
7558 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7559 // commitment at same time.
7561 let chanmon_cfgs = create_chanmon_cfgs(2);
7562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7564 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7566 // Create some initial channel
7567 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
7568 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7570 // Rebalance the network to generate htlc in the two directions
7571 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7573 // Route a HTLC from node 0 to node 1 (but don't settle)
7574 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7576 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7577 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
7579 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7580 let monitor = monitors.get(&outpoint).unwrap();
7581 let mut w = test_utils::TestVecWriter(Vec::new());
7582 monitor.write_for_disk(&mut w).unwrap();
7583 let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7584 &mut ::std::io::Cursor::new(&w.0), Arc::new(test_utils::TestLogger::new())).unwrap().1;
7585 assert!(new_monitor == *monitor);
7586 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
7587 let watchtower = test_utils::TestChannelMonitor::new(chain_monitor, &chanmon_cfgs[0].tx_broadcaster, logger.clone(), &chanmon_cfgs[0].fee_estimator);
7588 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7591 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7592 watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7594 // Try to update ChannelMonitor
7595 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7596 check_added_monitors!(nodes[1], 1);
7597 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7598 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7599 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7600 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7601 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator) {
7602 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7603 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7604 } else { assert!(false); }
7605 } else { assert!(false); };
7606 // Our local monitor is in-sync and hasn't processed yet timeout
7607 check_added_monitors!(nodes[0], 1);
7608 let events = nodes[0].node.get_and_clear_pending_events();
7609 assert_eq!(events.len(), 1);