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);
3622 fn test_htlc_timeout() {
3623 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3624 // to avoid our counterparty failing the channel.
3625 let chanmon_cfgs = create_chanmon_cfgs(2);
3626 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3627 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3628 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3630 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3631 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 100000);
3633 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3634 nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3635 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3636 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3637 header.prev_blockhash = header.bitcoin_hash();
3638 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3639 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3642 expect_pending_htlcs_forwardable!(nodes[1]);
3644 check_added_monitors!(nodes[1], 1);
3645 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3646 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3647 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3648 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3649 assert!(htlc_timeout_updates.update_fee.is_none());
3651 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3652 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3653 // 100_000 msat as u64, followed by a height of 123 as u32
3654 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3655 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3656 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3660 fn test_invalid_channel_announcement() {
3661 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3662 let secp_ctx = Secp256k1::new();
3663 let chanmon_cfgs = create_chanmon_cfgs(2);
3664 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3665 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3666 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3668 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::supported(), InitFeatures::supported());
3670 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3671 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3672 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3673 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3675 nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3677 let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3678 let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3680 let as_network_key = nodes[0].node.get_our_node_id();
3681 let bs_network_key = nodes[1].node.get_our_node_id();
3683 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3685 let mut chan_announcement;
3687 macro_rules! dummy_unsigned_msg {
3689 msgs::UnsignedChannelAnnouncement {
3690 features: ChannelFeatures::supported(),
3691 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3692 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3693 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3694 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3695 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3696 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3697 excess_data: Vec::new(),
3702 macro_rules! sign_msg {
3703 ($unsigned_msg: expr) => {
3704 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3705 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3706 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3707 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3708 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3709 chan_announcement = msgs::ChannelAnnouncement {
3710 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3711 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3712 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3713 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3714 contents: $unsigned_msg
3719 let unsigned_msg = dummy_unsigned_msg!();
3720 sign_msg!(unsigned_msg);
3721 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3722 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 } );
3724 // Configured with Network::Testnet
3725 let mut unsigned_msg = dummy_unsigned_msg!();
3726 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3727 sign_msg!(unsigned_msg);
3728 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3730 let mut unsigned_msg = dummy_unsigned_msg!();
3731 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3732 sign_msg!(unsigned_msg);
3733 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3737 fn test_no_txn_manager_serialize_deserialize() {
3738 let chanmon_cfgs = create_chanmon_cfgs(2);
3739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3741 let fee_estimator: test_utils::TestFeeEstimator;
3742 let new_chan_monitor: test_utils::TestChannelMonitor;
3743 let keys_manager: test_utils::TestKeysInterface;
3744 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3745 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3747 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3749 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3751 let nodes_0_serialized = nodes[0].node.encode();
3752 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3753 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3755 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3756 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);
3757 nodes[0].chan_monitor = &new_chan_monitor;
3758 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3759 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3760 assert!(chan_0_monitor_read.is_empty());
3762 let mut nodes_0_read = &nodes_0_serialized[..];
3763 let config = UserConfig::default();
3764 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3765 let (_, nodes_0_deserialized_tmp) = {
3766 let mut channel_monitors = HashMap::new();
3767 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3768 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3769 default_config: config,
3770 keys_manager: &keys_manager,
3771 fee_estimator: &fee_estimator,
3772 monitor: nodes[0].chan_monitor,
3773 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3774 logger: Arc::new(test_utils::TestLogger::new()),
3775 channel_monitors: &mut channel_monitors,
3778 nodes_0_deserialized = nodes_0_deserialized_tmp;
3779 assert!(nodes_0_read.is_empty());
3781 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3782 nodes[0].node = &nodes_0_deserialized;
3783 nodes[0].block_notifier.register_listener(nodes[0].node);
3784 assert_eq!(nodes[0].node.list_channels().len(), 1);
3785 check_added_monitors!(nodes[0], 1);
3787 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3788 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3789 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3790 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3792 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3793 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3794 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3795 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3797 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3798 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3799 for node in nodes.iter() {
3800 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3801 node.router.handle_channel_update(&as_update).unwrap();
3802 node.router.handle_channel_update(&bs_update).unwrap();
3805 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3809 fn test_simple_manager_serialize_deserialize() {
3810 let chanmon_cfgs = create_chanmon_cfgs(2);
3811 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3812 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3813 let fee_estimator: test_utils::TestFeeEstimator;
3814 let new_chan_monitor: test_utils::TestChannelMonitor;
3815 let keys_manager: test_utils::TestKeysInterface;
3816 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3817 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3818 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3820 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3821 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3823 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3825 let nodes_0_serialized = nodes[0].node.encode();
3826 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3827 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3829 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3830 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);
3831 nodes[0].chan_monitor = &new_chan_monitor;
3832 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3833 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3834 assert!(chan_0_monitor_read.is_empty());
3836 let mut nodes_0_read = &nodes_0_serialized[..];
3837 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3838 let (_, nodes_0_deserialized_tmp) = {
3839 let mut channel_monitors = HashMap::new();
3840 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3841 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3842 default_config: UserConfig::default(),
3843 keys_manager: &keys_manager,
3844 fee_estimator: &fee_estimator,
3845 monitor: nodes[0].chan_monitor,
3846 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3847 logger: Arc::new(test_utils::TestLogger::new()),
3848 channel_monitors: &mut channel_monitors,
3851 nodes_0_deserialized = nodes_0_deserialized_tmp;
3852 assert!(nodes_0_read.is_empty());
3854 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3855 nodes[0].node = &nodes_0_deserialized;
3856 check_added_monitors!(nodes[0], 1);
3858 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3860 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3861 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3865 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3866 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3867 let chanmon_cfgs = create_chanmon_cfgs(4);
3868 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3869 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3870 let fee_estimator: test_utils::TestFeeEstimator;
3871 let new_chan_monitor: test_utils::TestChannelMonitor;
3872 let keys_manager: test_utils::TestKeysInterface;
3873 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3874 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3875 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3876 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::supported(), InitFeatures::supported());
3877 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
3879 let mut node_0_stale_monitors_serialized = Vec::new();
3880 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3881 let mut writer = test_utils::TestVecWriter(Vec::new());
3882 monitor.1.write_for_disk(&mut writer).unwrap();
3883 node_0_stale_monitors_serialized.push(writer.0);
3886 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3888 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3889 let nodes_0_serialized = nodes[0].node.encode();
3891 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3892 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3893 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3894 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3896 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3898 let mut node_0_monitors_serialized = Vec::new();
3899 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3900 let mut writer = test_utils::TestVecWriter(Vec::new());
3901 monitor.1.write_for_disk(&mut writer).unwrap();
3902 node_0_monitors_serialized.push(writer.0);
3905 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3906 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);
3907 nodes[0].chan_monitor = &new_chan_monitor;
3909 let mut node_0_stale_monitors = Vec::new();
3910 for serialized in node_0_stale_monitors_serialized.iter() {
3911 let mut read = &serialized[..];
3912 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3913 assert!(read.is_empty());
3914 node_0_stale_monitors.push(monitor);
3917 let mut node_0_monitors = Vec::new();
3918 for serialized in node_0_monitors_serialized.iter() {
3919 let mut read = &serialized[..];
3920 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3921 assert!(read.is_empty());
3922 node_0_monitors.push(monitor);
3925 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3927 let mut nodes_0_read = &nodes_0_serialized[..];
3928 if let Err(msgs::DecodeError::InvalidValue) =
3929 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3930 default_config: UserConfig::default(),
3931 keys_manager: &keys_manager,
3932 fee_estimator: &fee_estimator,
3933 monitor: nodes[0].chan_monitor,
3934 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3935 logger: Arc::new(test_utils::TestLogger::new()),
3936 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
3938 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
3941 let mut nodes_0_read = &nodes_0_serialized[..];
3942 let (_, nodes_0_deserialized_tmp) =
3943 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3944 default_config: UserConfig::default(),
3945 keys_manager: &keys_manager,
3946 fee_estimator: &fee_estimator,
3947 monitor: nodes[0].chan_monitor,
3948 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3949 logger: Arc::new(test_utils::TestLogger::new()),
3950 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
3952 nodes_0_deserialized = nodes_0_deserialized_tmp;
3953 assert!(nodes_0_read.is_empty());
3955 { // Channel close should result in a commitment tx and an HTLC tx
3956 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3957 assert_eq!(txn.len(), 2);
3958 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3959 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3962 for monitor in node_0_monitors.drain(..) {
3963 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
3964 check_added_monitors!(nodes[0], 1);
3966 nodes[0].node = &nodes_0_deserialized;
3968 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3969 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3970 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3971 //... and we can even still claim the payment!
3972 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3974 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3975 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3976 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3977 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
3978 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3979 assert_eq!(msg_events.len(), 1);
3980 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
3982 &ErrorAction::SendErrorMessage { ref msg } => {
3983 assert_eq!(msg.channel_id, channel_id);
3985 _ => panic!("Unexpected event!"),
3990 macro_rules! check_spendable_outputs {
3991 ($node: expr, $der_idx: expr) => {
3993 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3994 let mut txn = Vec::new();
3995 for event in events {
3997 Event::SpendableOutputs { ref outputs } => {
3998 for outp in outputs {
4000 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4002 previous_output: outpoint.clone(),
4003 script_sig: Script::new(),
4005 witness: Vec::new(),
4008 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4009 value: output.value,
4011 let mut spend_tx = Transaction {
4017 let secp_ctx = Secp256k1::new();
4018 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4019 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4020 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4021 let remotesig = secp_ctx.sign(&sighash, key);
4022 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4023 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4024 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4027 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
4029 previous_output: outpoint.clone(),
4030 script_sig: Script::new(),
4031 sequence: *to_self_delay as u32,
4032 witness: Vec::new(),
4035 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4036 value: output.value,
4038 let mut spend_tx = Transaction {
4044 let secp_ctx = Secp256k1::new();
4045 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
4046 let local_delaysig = secp_ctx.sign(&sighash, key);
4047 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
4048 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4049 spend_tx.input[0].witness.push(vec!());
4050 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4053 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4054 let secp_ctx = Secp256k1::new();
4056 previous_output: outpoint.clone(),
4057 script_sig: Script::new(),
4059 witness: Vec::new(),
4062 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4063 value: output.value,
4065 let mut spend_tx = Transaction {
4069 output: vec![outp.clone()],
4072 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4074 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4076 Err(_) => panic!("Your RNG is busted"),
4079 Err(_) => panic!("Your rng is busted"),
4082 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4083 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4084 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4085 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4086 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4087 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4088 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4094 _ => panic!("Unexpected event"),
4103 fn test_claim_sizeable_push_msat() {
4104 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4105 let chanmon_cfgs = create_chanmon_cfgs(2);
4106 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4107 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4108 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4110 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4111 nodes[1].node.force_close_channel(&chan.2);
4112 check_closed_broadcast!(nodes[1], false);
4113 check_added_monitors!(nodes[1], 1);
4114 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4115 assert_eq!(node_txn.len(), 1);
4116 check_spends!(node_txn[0], chan.3);
4117 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
4119 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4120 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4121 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4123 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4124 assert_eq!(spend_txn.len(), 1);
4125 check_spends!(spend_txn[0], node_txn[0]);
4129 fn test_claim_on_remote_sizeable_push_msat() {
4130 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4131 // to_remote output is encumbered by a P2WPKH
4132 let chanmon_cfgs = create_chanmon_cfgs(2);
4133 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4135 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4137 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4138 nodes[0].node.force_close_channel(&chan.2);
4139 check_closed_broadcast!(nodes[0], false);
4140 check_added_monitors!(nodes[0], 1);
4142 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4143 assert_eq!(node_txn.len(), 1);
4144 check_spends!(node_txn[0], chan.3);
4145 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
4147 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4148 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4149 check_closed_broadcast!(nodes[1], false);
4150 check_added_monitors!(nodes[1], 1);
4151 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4153 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4154 assert_eq!(spend_txn.len(), 2);
4155 assert_eq!(spend_txn[0], spend_txn[1]);
4156 check_spends!(spend_txn[0], node_txn[0]);
4160 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4161 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4162 // to_remote output is encumbered by a P2WPKH
4164 let chanmon_cfgs = create_chanmon_cfgs(2);
4165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4169 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::supported(), InitFeatures::supported());
4170 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4171 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4172 assert_eq!(revoked_local_txn[0].input.len(), 1);
4173 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4175 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4176 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4177 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4178 check_closed_broadcast!(nodes[1], false);
4179 check_added_monitors!(nodes[1], 1);
4181 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4182 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4183 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4184 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4186 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4187 assert_eq!(spend_txn.len(), 3);
4188 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4189 check_spends!(spend_txn[0], revoked_local_txn[0]);
4190 check_spends!(spend_txn[2], node_txn[0]);
4194 fn test_static_spendable_outputs_preimage_tx() {
4195 let chanmon_cfgs = create_chanmon_cfgs(2);
4196 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4197 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4198 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4200 // Create some initial channels
4201 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4203 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4205 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4206 assert_eq!(commitment_tx[0].input.len(), 1);
4207 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4209 // Settle A's commitment tx on B's chain
4210 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4211 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4212 check_added_monitors!(nodes[1], 1);
4213 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4214 check_added_monitors!(nodes[1], 1);
4215 let events = nodes[1].node.get_and_clear_pending_msg_events();
4217 MessageSendEvent::UpdateHTLCs { .. } => {},
4218 _ => panic!("Unexpected event"),
4221 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4222 _ => panic!("Unexepected event"),
4225 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4226 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4227 assert_eq!(node_txn.len(), 3);
4228 check_spends!(node_txn[0], commitment_tx[0]);
4229 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4230 check_spends!(node_txn[1], chan_1.3);
4231 check_spends!(node_txn[2], node_txn[1]);
4233 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4234 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4235 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4237 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4238 assert_eq!(spend_txn.len(), 1);
4239 check_spends!(spend_txn[0], node_txn[0]);
4243 fn test_static_spendable_outputs_timeout_tx() {
4244 let chanmon_cfgs = create_chanmon_cfgs(2);
4245 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4246 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4247 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4249 // Create some initial channels
4250 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4252 // Rebalance the network a bit by relaying one payment through all the channels ...
4253 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4255 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4257 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4258 assert_eq!(commitment_tx[0].input.len(), 1);
4259 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4261 // Settle A's commitment tx on B' chain
4262 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4263 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4264 check_added_monitors!(nodes[1], 1);
4265 let events = nodes[1].node.get_and_clear_pending_msg_events();
4267 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4268 _ => panic!("Unexpected event"),
4271 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4272 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4273 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4274 check_spends!(node_txn[0], commitment_tx[0].clone());
4275 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4276 check_spends!(node_txn[1], chan_1.3.clone());
4277 check_spends!(node_txn[2], node_txn[1]);
4279 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4280 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4281 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4282 expect_payment_failed!(nodes[1], our_payment_hash, true);
4284 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4285 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4286 check_spends!(spend_txn[2], node_txn[0].clone());
4290 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4291 let chanmon_cfgs = create_chanmon_cfgs(2);
4292 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4293 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4294 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4296 // Create some initial channels
4297 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4299 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4300 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4301 assert_eq!(revoked_local_txn[0].input.len(), 1);
4302 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4304 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4306 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4307 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4308 check_closed_broadcast!(nodes[1], false);
4309 check_added_monitors!(nodes[1], 1);
4311 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4312 assert_eq!(node_txn.len(), 2);
4313 assert_eq!(node_txn[0].input.len(), 2);
4314 check_spends!(node_txn[0], revoked_local_txn[0]);
4316 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4317 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4318 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4320 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4321 assert_eq!(spend_txn.len(), 1);
4322 check_spends!(spend_txn[0], node_txn[0]);
4326 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4327 let chanmon_cfgs = create_chanmon_cfgs(2);
4328 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4329 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4330 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4332 // Create some initial channels
4333 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4335 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4336 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4337 assert_eq!(revoked_local_txn[0].input.len(), 1);
4338 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4340 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4342 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4343 // A will generate HTLC-Timeout from revoked commitment tx
4344 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4345 check_closed_broadcast!(nodes[0], false);
4346 check_added_monitors!(nodes[0], 1);
4348 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4349 assert_eq!(revoked_htlc_txn.len(), 2);
4350 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4351 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4352 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4353 check_spends!(revoked_htlc_txn[1], chan_1.3);
4355 // B will generate justice tx from A's revoked commitment/HTLC tx
4356 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4357 check_closed_broadcast!(nodes[1], false);
4358 check_added_monitors!(nodes[1], 1);
4360 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4361 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
4362 assert_eq!(node_txn[0].input.len(), 2);
4363 check_spends!(node_txn[0], revoked_local_txn[0]);
4364 check_spends!(node_txn[1], chan_1.3);
4365 assert_eq!(node_txn[2].input.len(), 1);
4366 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4367 assert_eq!(node_txn[3].input.len(), 1);
4368 check_spends!(node_txn[3], revoked_local_txn[0]);
4370 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4371 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4372 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4374 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4375 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4376 assert_eq!(spend_txn.len(), 2);
4377 check_spends!(spend_txn[0], node_txn[0]);
4378 check_spends!(spend_txn[1], node_txn[2]);
4382 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4383 let chanmon_cfgs = create_chanmon_cfgs(2);
4384 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4385 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4386 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4388 // Create some initial channels
4389 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4391 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4392 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4393 assert_eq!(revoked_local_txn[0].input.len(), 1);
4394 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4396 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4398 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4399 // B will generate HTLC-Success from revoked commitment tx
4400 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4401 check_closed_broadcast!(nodes[1], false);
4402 check_added_monitors!(nodes[1], 1);
4403 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4405 assert_eq!(revoked_htlc_txn.len(), 2);
4406 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4407 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4408 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4410 // A will generate justice tx from B's revoked commitment/HTLC tx
4411 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4412 check_closed_broadcast!(nodes[0], false);
4413 check_added_monitors!(nodes[0], 1);
4415 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4416 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4417 assert_eq!(node_txn[2].input.len(), 1);
4418 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4420 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4421 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4422 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4424 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4425 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4426 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4427 assert_eq!(spend_txn[0], spend_txn[1]);
4428 assert_eq!(spend_txn[0], spend_txn[2]);
4429 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4430 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4431 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4435 fn test_onchain_to_onchain_claim() {
4436 // Test that in case of channel closure, we detect the state of output thanks to
4437 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4438 // First, have C claim an HTLC against its own latest commitment transaction.
4439 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4441 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4444 let chanmon_cfgs = create_chanmon_cfgs(3);
4445 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4446 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4447 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4449 // Create some initial channels
4450 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4451 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4453 // Rebalance the network a bit by relaying one payment through all the channels ...
4454 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4455 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4457 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4458 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4459 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4460 check_spends!(commitment_tx[0], chan_2.3);
4461 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4462 check_added_monitors!(nodes[2], 1);
4463 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4464 assert!(updates.update_add_htlcs.is_empty());
4465 assert!(updates.update_fail_htlcs.is_empty());
4466 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4467 assert!(updates.update_fail_malformed_htlcs.is_empty());
4469 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4470 check_closed_broadcast!(nodes[2], false);
4471 check_added_monitors!(nodes[2], 1);
4473 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4474 assert_eq!(c_txn.len(), 3);
4475 assert_eq!(c_txn[0], c_txn[2]);
4476 assert_eq!(commitment_tx[0], c_txn[1]);
4477 check_spends!(c_txn[1], chan_2.3);
4478 check_spends!(c_txn[2], c_txn[1]);
4479 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4480 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4481 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4482 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4484 // 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
4485 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4487 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4488 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4489 assert_eq!(b_txn.len(), 3);
4490 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4491 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4492 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4493 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4494 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4495 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4496 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4497 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4498 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4501 check_added_monitors!(nodes[1], 1);
4502 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4503 check_added_monitors!(nodes[1], 1);
4504 match msg_events[0] {
4505 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4506 _ => panic!("Unexpected event"),
4508 match msg_events[1] {
4509 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, .. } } => {
4510 assert!(update_add_htlcs.is_empty());
4511 assert!(update_fail_htlcs.is_empty());
4512 assert_eq!(update_fulfill_htlcs.len(), 1);
4513 assert!(update_fail_malformed_htlcs.is_empty());
4514 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4516 _ => panic!("Unexpected event"),
4518 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4519 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4520 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4521 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4522 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4523 assert_eq!(b_txn.len(), 3);
4524 check_spends!(b_txn[1], chan_1.3);
4525 check_spends!(b_txn[2], b_txn[1]);
4526 check_spends!(b_txn[0], commitment_tx[0]);
4527 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4528 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4529 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4531 check_closed_broadcast!(nodes[1], false);
4532 check_added_monitors!(nodes[1], 1);
4536 fn test_duplicate_payment_hash_one_failure_one_success() {
4537 // Topology : A --> B --> C
4538 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4539 let chanmon_cfgs = create_chanmon_cfgs(3);
4540 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4541 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4542 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4544 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4545 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4547 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4548 *nodes[0].network_payment_count.borrow_mut() -= 1;
4549 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4551 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4552 assert_eq!(commitment_txn[0].input.len(), 1);
4553 check_spends!(commitment_txn[0], chan_2.3);
4555 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4556 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4557 check_closed_broadcast!(nodes[1], false);
4558 check_added_monitors!(nodes[1], 1);
4560 let htlc_timeout_tx;
4561 { // Extract one of the two HTLC-Timeout transaction
4562 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4563 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4564 assert_eq!(node_txn.len(), 5);
4565 check_spends!(node_txn[0], commitment_txn[0]);
4566 assert_eq!(node_txn[0].input.len(), 1);
4567 check_spends!(node_txn[1], commitment_txn[0]);
4568 assert_eq!(node_txn[1].input.len(), 1);
4569 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4570 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4571 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4572 check_spends!(node_txn[2], chan_2.3);
4573 check_spends!(node_txn[3], node_txn[2]);
4574 check_spends!(node_txn[4], node_txn[2]);
4575 htlc_timeout_tx = node_txn[1].clone();
4578 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4579 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4580 check_added_monitors!(nodes[2], 3);
4581 let events = nodes[2].node.get_and_clear_pending_msg_events();
4583 MessageSendEvent::UpdateHTLCs { .. } => {},
4584 _ => panic!("Unexpected event"),
4587 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4588 _ => panic!("Unexepected event"),
4590 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4591 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)
4592 check_spends!(htlc_success_txn[2], chan_2.3);
4593 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4594 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4595 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4596 assert_eq!(htlc_success_txn[0].input.len(), 1);
4597 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4598 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4599 assert_eq!(htlc_success_txn[1].input.len(), 1);
4600 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4601 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4602 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4603 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4605 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4606 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4607 expect_pending_htlcs_forwardable!(nodes[1]);
4608 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4609 assert!(htlc_updates.update_add_htlcs.is_empty());
4610 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4611 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4612 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4613 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4614 check_added_monitors!(nodes[1], 1);
4616 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4617 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4619 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4620 let events = nodes[0].node.get_and_clear_pending_msg_events();
4621 assert_eq!(events.len(), 1);
4623 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4625 _ => { panic!("Unexpected event"); }
4628 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4630 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4631 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4632 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4633 assert!(updates.update_add_htlcs.is_empty());
4634 assert!(updates.update_fail_htlcs.is_empty());
4635 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4636 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4637 assert!(updates.update_fail_malformed_htlcs.is_empty());
4638 check_added_monitors!(nodes[1], 1);
4640 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4641 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4643 let events = nodes[0].node.get_and_clear_pending_events();
4645 Event::PaymentSent { ref payment_preimage } => {
4646 assert_eq!(*payment_preimage, our_payment_preimage);
4648 _ => panic!("Unexpected event"),
4653 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4654 let chanmon_cfgs = create_chanmon_cfgs(2);
4655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4657 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4659 // Create some initial channels
4660 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4662 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4663 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4664 assert_eq!(local_txn[0].input.len(), 1);
4665 check_spends!(local_txn[0], chan_1.3);
4667 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4668 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4669 check_added_monitors!(nodes[1], 1);
4670 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4671 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4672 check_added_monitors!(nodes[1], 1);
4673 let events = nodes[1].node.get_and_clear_pending_msg_events();
4675 MessageSendEvent::UpdateHTLCs { .. } => {},
4676 _ => panic!("Unexpected event"),
4679 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4680 _ => panic!("Unexepected event"),
4683 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4684 assert_eq!(node_txn[0].input.len(), 1);
4685 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4686 check_spends!(node_txn[0], local_txn[0]);
4687 vec![node_txn[0].clone(), node_txn[2].clone()]
4690 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4691 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4692 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4694 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4695 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4696 assert_eq!(spend_txn.len(), 2);
4697 check_spends!(spend_txn[0], node_txn[0]);
4698 check_spends!(spend_txn[1], node_txn[1]);
4701 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4702 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4703 // unrevoked commitment transaction.
4704 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4705 // a remote RAA before they could be failed backwards (and combinations thereof).
4706 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4707 // use the same payment hashes.
4708 // Thus, we use a six-node network:
4713 // And test where C fails back to A/B when D announces its latest commitment transaction
4714 let chanmon_cfgs = create_chanmon_cfgs(6);
4715 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4716 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4717 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4719 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported());
4720 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4721 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
4722 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
4723 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
4725 // Rebalance and check output sanity...
4726 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4727 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4728 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4730 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4732 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
4734 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
4735 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();
4737 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
4739 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
4741 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4743 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4744 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4746 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4748 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4751 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4753 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();
4754 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
4757 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
4759 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4760 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4762 // Double-check that six of the new HTLC were added
4763 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4764 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4765 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4766 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4768 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4769 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4770 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
4771 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
4772 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
4773 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
4774 check_added_monitors!(nodes[4], 0);
4775 expect_pending_htlcs_forwardable!(nodes[4]);
4776 check_added_monitors!(nodes[4], 1);
4778 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4779 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4780 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4781 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4782 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4783 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4785 // Fail 3rd below-dust and 7th above-dust HTLCs
4786 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
4787 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
4788 check_added_monitors!(nodes[5], 0);
4789 expect_pending_htlcs_forwardable!(nodes[5]);
4790 check_added_monitors!(nodes[5], 1);
4792 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4793 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4794 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4795 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4797 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4799 expect_pending_htlcs_forwardable!(nodes[3]);
4800 check_added_monitors!(nodes[3], 1);
4801 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4802 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4803 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4804 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4805 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4806 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4807 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4808 if deliver_last_raa {
4809 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4811 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4814 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4815 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4816 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4817 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4819 // We now broadcast the latest commitment transaction, which *should* result in failures for
4820 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4821 // the non-broadcast above-dust HTLCs.
4823 // Alternatively, we may broadcast the previous commitment transaction, which should only
4824 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4825 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4827 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4828 if announce_latest {
4829 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4831 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4833 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4834 check_closed_broadcast!(nodes[2], false);
4835 expect_pending_htlcs_forwardable!(nodes[2]);
4836 check_added_monitors!(nodes[2], 3);
4838 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4839 assert_eq!(cs_msgs.len(), 2);
4840 let mut a_done = false;
4841 for msg in cs_msgs {
4843 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4844 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4845 // should be failed-backwards here.
4846 let target = if *node_id == nodes[0].node.get_our_node_id() {
4847 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4848 for htlc in &updates.update_fail_htlcs {
4849 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 });
4851 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4856 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4857 for htlc in &updates.update_fail_htlcs {
4858 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4860 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4861 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4864 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4865 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4866 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4867 if announce_latest {
4868 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4869 if *node_id == nodes[0].node.get_our_node_id() {
4870 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4873 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4875 _ => panic!("Unexpected event"),
4879 let as_events = nodes[0].node.get_and_clear_pending_events();
4880 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4881 let mut as_failds = HashSet::new();
4882 for event in as_events.iter() {
4883 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4884 assert!(as_failds.insert(*payment_hash));
4885 if *payment_hash != payment_hash_2 {
4886 assert_eq!(*rejected_by_dest, deliver_last_raa);
4888 assert!(!rejected_by_dest);
4890 } else { panic!("Unexpected event"); }
4892 assert!(as_failds.contains(&payment_hash_1));
4893 assert!(as_failds.contains(&payment_hash_2));
4894 if announce_latest {
4895 assert!(as_failds.contains(&payment_hash_3));
4896 assert!(as_failds.contains(&payment_hash_5));
4898 assert!(as_failds.contains(&payment_hash_6));
4900 let bs_events = nodes[1].node.get_and_clear_pending_events();
4901 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4902 let mut bs_failds = HashSet::new();
4903 for event in bs_events.iter() {
4904 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4905 assert!(bs_failds.insert(*payment_hash));
4906 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4907 assert_eq!(*rejected_by_dest, deliver_last_raa);
4909 assert!(!rejected_by_dest);
4911 } else { panic!("Unexpected event"); }
4913 assert!(bs_failds.contains(&payment_hash_1));
4914 assert!(bs_failds.contains(&payment_hash_2));
4915 if announce_latest {
4916 assert!(bs_failds.contains(&payment_hash_4));
4918 assert!(bs_failds.contains(&payment_hash_5));
4920 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4921 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4922 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4923 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4924 // PaymentFailureNetworkUpdates.
4925 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4926 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4927 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4928 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4929 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4931 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4932 _ => panic!("Unexpected event"),
4938 fn test_fail_backwards_latest_remote_announce_a() {
4939 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4943 fn test_fail_backwards_latest_remote_announce_b() {
4944 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4948 fn test_fail_backwards_previous_remote_announce() {
4949 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4950 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4951 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4955 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4956 let chanmon_cfgs = create_chanmon_cfgs(2);
4957 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4958 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4959 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4961 // Create some initial channels
4962 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4964 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
4965 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4966 assert_eq!(local_txn[0].input.len(), 1);
4967 check_spends!(local_txn[0], chan_1.3);
4969 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4970 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4971 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4972 check_closed_broadcast!(nodes[0], false);
4973 check_added_monitors!(nodes[0], 1);
4975 let htlc_timeout = {
4976 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4977 assert_eq!(node_txn[0].input.len(), 1);
4978 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4979 check_spends!(node_txn[0], local_txn[0]);
4983 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4984 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
4985 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4986 expect_payment_failed!(nodes[0], our_payment_hash, true);
4988 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4989 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4990 assert_eq!(spend_txn.len(), 3);
4991 assert_eq!(spend_txn[0], spend_txn[1]);
4992 check_spends!(spend_txn[0], local_txn[0]);
4993 check_spends!(spend_txn[2], htlc_timeout);
4997 fn test_static_output_closing_tx() {
4998 let chanmon_cfgs = create_chanmon_cfgs(2);
4999 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5000 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5001 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5003 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5005 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5006 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5008 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5009 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5010 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5012 let spend_txn = check_spendable_outputs!(nodes[0], 2);
5013 assert_eq!(spend_txn.len(), 1);
5014 check_spends!(spend_txn[0], closing_tx);
5016 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5017 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5019 let spend_txn = check_spendable_outputs!(nodes[1], 2);
5020 assert_eq!(spend_txn.len(), 1);
5021 check_spends!(spend_txn[0], closing_tx);
5024 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5025 let chanmon_cfgs = create_chanmon_cfgs(2);
5026 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5028 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5029 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5031 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5033 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5034 // present in B's local commitment transaction, but none of A's commitment transactions.
5035 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5036 check_added_monitors!(nodes[1], 1);
5038 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5039 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5040 let events = nodes[0].node.get_and_clear_pending_events();
5041 assert_eq!(events.len(), 1);
5043 Event::PaymentSent { payment_preimage } => {
5044 assert_eq!(payment_preimage, our_payment_preimage);
5046 _ => panic!("Unexpected event"),
5049 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5050 check_added_monitors!(nodes[0], 1);
5051 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5052 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5053 check_added_monitors!(nodes[1], 1);
5055 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5056 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5057 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5058 header.prev_blockhash = header.bitcoin_hash();
5060 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5061 check_closed_broadcast!(nodes[1], false);
5062 check_added_monitors!(nodes[1], 1);
5065 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5066 let chanmon_cfgs = create_chanmon_cfgs(2);
5067 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5068 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5069 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5070 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5072 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();
5073 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5074 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5075 check_added_monitors!(nodes[0], 1);
5077 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5079 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5080 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5081 // to "time out" the HTLC.
5083 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5085 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5086 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5087 header.prev_blockhash = header.bitcoin_hash();
5089 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5090 check_closed_broadcast!(nodes[0], false);
5091 check_added_monitors!(nodes[0], 1);
5094 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5095 let chanmon_cfgs = create_chanmon_cfgs(3);
5096 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5097 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5098 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5099 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5101 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5102 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5103 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5104 // actually revoked.
5105 let htlc_value = if use_dust { 50000 } else { 3000000 };
5106 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5107 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5108 expect_pending_htlcs_forwardable!(nodes[1]);
5109 check_added_monitors!(nodes[1], 1);
5111 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5112 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5113 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5114 check_added_monitors!(nodes[0], 1);
5115 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5116 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5117 check_added_monitors!(nodes[1], 1);
5118 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5119 check_added_monitors!(nodes[1], 1);
5120 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5122 if check_revoke_no_close {
5123 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5124 check_added_monitors!(nodes[0], 1);
5127 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5128 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5129 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5130 header.prev_blockhash = header.bitcoin_hash();
5132 if !check_revoke_no_close {
5133 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5134 check_closed_broadcast!(nodes[0], false);
5135 check_added_monitors!(nodes[0], 1);
5137 expect_payment_failed!(nodes[0], our_payment_hash, true);
5141 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5142 // There are only a few cases to test here:
5143 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5144 // broadcastable commitment transactions result in channel closure,
5145 // * its included in an unrevoked-but-previous remote commitment transaction,
5146 // * its included in the latest remote or local commitment transactions.
5147 // We test each of the three possible commitment transactions individually and use both dust and
5149 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5150 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5151 // tested for at least one of the cases in other tests.
5153 fn htlc_claim_single_commitment_only_a() {
5154 do_htlc_claim_local_commitment_only(true);
5155 do_htlc_claim_local_commitment_only(false);
5157 do_htlc_claim_current_remote_commitment_only(true);
5158 do_htlc_claim_current_remote_commitment_only(false);
5162 fn htlc_claim_single_commitment_only_b() {
5163 do_htlc_claim_previous_remote_commitment_only(true, false);
5164 do_htlc_claim_previous_remote_commitment_only(false, false);
5165 do_htlc_claim_previous_remote_commitment_only(true, true);
5166 do_htlc_claim_previous_remote_commitment_only(false, true);
5169 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>)
5170 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5173 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);
5177 // 0: node1 fails backward
5178 // 1: final node fails backward
5179 // 2: payment completed but the user rejects the payment
5180 // 3: final node fails backward (but tamper onion payloads from node0)
5181 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5182 // 200: trigger error in the final node and tamper returning fail_htlc
5183 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>)
5184 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5185 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5189 // reset block height
5190 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5191 for ix in 0..nodes.len() {
5192 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5195 macro_rules! expect_event {
5196 ($node: expr, $event_type: path) => {{
5197 let events = $node.node.get_and_clear_pending_events();
5198 assert_eq!(events.len(), 1);
5200 $event_type { .. } => {},
5201 _ => panic!("Unexpected event"),
5206 macro_rules! expect_htlc_forward {
5208 expect_event!($node, Event::PendingHTLCsForwardable);
5209 $node.node.process_pending_htlc_forwards();
5213 // 0 ~~> 2 send payment
5214 nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5215 check_added_monitors!(nodes[0], 1);
5216 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5217 // temper update_add (0 => 1)
5218 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5219 if test_case == 0 || test_case == 3 || test_case == 100 {
5220 callback_msg(&mut update_add_0);
5223 // 0 => 1 update_add & CS
5224 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5225 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5227 let update_1_0 = match test_case {
5228 0|100 => { // intermediate node failure; fail backward to 0
5229 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5230 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));
5233 1|2|3|200 => { // final node failure; forwarding to 2
5234 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5236 if test_case != 200 {
5239 expect_htlc_forward!(&nodes[1]);
5241 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5242 check_added_monitors!(&nodes[1], 1);
5243 assert_eq!(update_1.update_add_htlcs.len(), 1);
5244 // tamper update_add (1 => 2)
5245 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5246 if test_case != 3 && test_case != 200 {
5247 callback_msg(&mut update_add_1);
5251 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5252 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5254 if test_case == 2 || test_case == 200 {
5255 expect_htlc_forward!(&nodes[2]);
5256 expect_event!(&nodes[2], Event::PaymentReceived);
5258 expect_pending_htlcs_forwardable!(nodes[2]);
5261 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5262 if test_case == 2 || test_case == 200 {
5263 check_added_monitors!(&nodes[2], 1);
5265 assert!(update_2_1.update_fail_htlcs.len() == 1);
5267 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5268 if test_case == 200 {
5269 callback_fail(&mut fail_msg);
5273 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5274 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5276 // backward fail on 1
5277 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5278 assert!(update_1_0.update_fail_htlcs.len() == 1);
5281 _ => unreachable!(),
5284 // 1 => 0 commitment_signed_dance
5285 if update_1_0.update_fail_htlcs.len() > 0 {
5286 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5287 if test_case == 100 {
5288 callback_fail(&mut fail_msg);
5290 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5292 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5295 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5297 let events = nodes[0].node.get_and_clear_pending_events();
5298 assert_eq!(events.len(), 1);
5299 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5300 assert_eq!(*rejected_by_dest, !expected_retryable);
5301 assert_eq!(*error_code, expected_error_code);
5303 panic!("Uexpected event");
5306 let events = nodes[0].node.get_and_clear_pending_msg_events();
5307 if expected_channel_update.is_some() {
5308 assert_eq!(events.len(), 1);
5310 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5312 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5313 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5314 panic!("channel_update not found!");
5317 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5318 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5319 assert!(*short_channel_id == *expected_short_channel_id);
5320 assert!(*is_permanent == *expected_is_permanent);
5322 panic!("Unexpected message event");
5325 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5326 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5327 assert!(*node_id == *expected_node_id);
5328 assert!(*is_permanent == *expected_is_permanent);
5330 panic!("Unexpected message event");
5335 _ => panic!("Unexpected message event"),
5338 assert_eq!(events.len(), 0);
5342 impl msgs::ChannelUpdate {
5343 fn dummy() -> msgs::ChannelUpdate {
5344 use secp256k1::ffi::Signature as FFISignature;
5345 use secp256k1::Signature;
5346 msgs::ChannelUpdate {
5347 signature: Signature::from(FFISignature::new()),
5348 contents: msgs::UnsignedChannelUpdate {
5349 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
5350 short_channel_id: 0,
5353 cltv_expiry_delta: 0,
5354 htlc_minimum_msat: 0,
5356 fee_proportional_millionths: 0,
5357 excess_data: vec![],
5363 struct BogusOnionHopData {
5366 impl BogusOnionHopData {
5367 fn new(orig: msgs::OnionHopData) -> Self {
5368 Self { data: orig.encode() }
5371 impl Writeable for BogusOnionHopData {
5372 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5373 writer.write_all(&self.data[..])
5378 fn test_onion_failure() {
5379 use ln::msgs::ChannelUpdate;
5380 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5383 const BADONION: u16 = 0x8000;
5384 const PERM: u16 = 0x4000;
5385 const NODE: u16 = 0x2000;
5386 const UPDATE: u16 = 0x1000;
5388 let chanmon_cfgs = create_chanmon_cfgs(3);
5389 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5390 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5391 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5392 for node in nodes.iter() {
5393 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5395 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())];
5396 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5397 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5399 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5401 // intermediate node failure
5402 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5403 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5404 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5405 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5406 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5407 let mut new_payloads = Vec::new();
5408 for payload in onion_payloads.drain(..) {
5409 new_payloads.push(BogusOnionHopData::new(payload));
5411 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5412 // describing a length-1 TLV payload, which is obviously bogus.
5413 new_payloads[0].data[0] = 1;
5414 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5415 }, ||{}, 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
5417 // final node failure
5418 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5419 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5420 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5421 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5422 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5423 let mut new_payloads = Vec::new();
5424 for payload in onion_payloads.drain(..) {
5425 new_payloads.push(BogusOnionHopData::new(payload));
5427 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5428 // length-1 TLV payload, which is obviously bogus.
5429 new_payloads[1].data[0] = 1;
5430 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5431 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5433 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5434 // receiving simulated fail messages
5435 // intermediate node failure
5436 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5438 msg.amount_msat -= 1;
5440 // and tamper returning error message
5441 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5442 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5443 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5444 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5446 // final node failure
5447 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5448 // and tamper returning error message
5449 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5450 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5451 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5453 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5454 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5456 // intermediate node failure
5457 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5458 msg.amount_msat -= 1;
5460 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5461 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5462 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5463 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5465 // final node failure
5466 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5467 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5468 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5469 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5471 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5472 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5474 // intermediate node failure
5475 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5476 msg.amount_msat -= 1;
5478 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5479 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5480 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5482 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5483 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5485 // final node failure
5486 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5487 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5488 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5489 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5491 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5492 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5494 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5495 Some(BADONION|PERM|4), None);
5497 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5498 Some(BADONION|PERM|5), None);
5500 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5501 Some(BADONION|PERM|6), None);
5503 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5504 msg.amount_msat -= 1;
5506 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5507 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5508 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5509 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5511 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5512 msg.amount_msat -= 1;
5514 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5515 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5516 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5517 // short_channel_id from the processing node
5518 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5520 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5521 msg.amount_msat -= 1;
5523 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5524 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5525 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5526 // short_channel_id from the processing node
5527 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5529 let mut bogus_route = route.clone();
5530 bogus_route.paths[0][1].short_channel_id -= 1;
5531 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5532 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5534 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5535 let mut bogus_route = route.clone();
5536 let route_len = bogus_route.paths[0].len();
5537 bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5538 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5540 //TODO: with new config API, we will be able to generate both valid and
5541 //invalid channel_update cases.
5542 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5543 msg.amount_msat -= 1;
5544 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5546 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5547 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5548 msg.cltv_expiry -= 1;
5549 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5551 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5552 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5553 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5555 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5556 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5558 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5559 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5560 }, false, Some(PERM|15), None);
5562 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5563 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5564 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5566 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5567 }, || {}, true, Some(17), None);
5569 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5570 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5571 for f in pending_forwards.iter_mut() {
5573 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5574 forward_info.outgoing_cltv_value += 1,
5579 }, true, Some(18), None);
5581 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5582 // violate amt_to_forward > msg.amount_msat
5583 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5584 for f in pending_forwards.iter_mut() {
5586 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5587 forward_info.amt_to_forward -= 1,
5592 }, true, Some(19), None);
5594 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5595 // disconnect event to the channel between nodes[1] ~ nodes[2]
5596 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5597 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5598 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5599 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5601 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5602 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5603 let mut route = route.clone();
5605 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5606 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5607 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5608 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5609 msg.cltv_expiry = htlc_cltv;
5610 msg.onion_routing_packet = onion_packet;
5611 }, ||{}, true, Some(21), None);
5616 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5617 let chanmon_cfgs = create_chanmon_cfgs(2);
5618 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5619 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5620 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5621 //Force duplicate channel ids
5622 for node in nodes.iter() {
5623 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5626 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5627 let channel_value_satoshis=10000;
5628 let push_msat=10001;
5629 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5630 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5631 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &node0_to_1_send_open_channel);
5633 //Create a second channel with a channel_id collision
5634 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5638 fn bolt2_open_channel_sending_node_checks_part2() {
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);
5644 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5645 let channel_value_satoshis=2^24;
5646 let push_msat=10001;
5647 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5649 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5650 let channel_value_satoshis=10000;
5651 // Test when push_msat is equal to 1000 * funding_satoshis.
5652 let push_msat=1000*channel_value_satoshis+1;
5653 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5655 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5656 let channel_value_satoshis=10000;
5657 let push_msat=10001;
5658 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
5659 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5660 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5662 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5663 // 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
5664 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5666 // 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.
5667 assert!(BREAKDOWN_TIMEOUT>0);
5668 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5670 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5671 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5672 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5674 // 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.
5675 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5676 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5677 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5678 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5679 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5682 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5683 // 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.
5684 //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.
5687 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5688 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5689 let chanmon_cfgs = create_chanmon_cfgs(2);
5690 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5691 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5692 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5693 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5694 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5695 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5697 route.paths[0][0].fee_msat = 100;
5699 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5700 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
5701 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5702 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5706 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5707 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5708 let chanmon_cfgs = create_chanmon_cfgs(2);
5709 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5710 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5711 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5712 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5713 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5714 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5716 route.paths[0][0].fee_msat = 0;
5718 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5719 assert_eq!(err, "Cannot send 0-msat HTLC"));
5720 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5721 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5725 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5726 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5727 let chanmon_cfgs = create_chanmon_cfgs(2);
5728 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5729 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5730 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5731 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5732 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5733 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5735 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5736 check_added_monitors!(nodes[0], 1);
5737 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5738 updates.update_add_htlcs[0].amount_msat = 0;
5740 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5741 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5742 check_closed_broadcast!(nodes[1], true).unwrap();
5743 check_added_monitors!(nodes[1], 1);
5747 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5748 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5749 //It is enforced when constructing a route.
5750 let chanmon_cfgs = create_chanmon_cfgs(2);
5751 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5752 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5753 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5754 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::supported(), InitFeatures::supported());
5755 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5756 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5758 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
5759 assert_eq!(err, "Channel CLTV overflowed?!"));
5763 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5764 //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.
5765 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5766 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5767 let chanmon_cfgs = create_chanmon_cfgs(2);
5768 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5769 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5770 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5771 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::supported(), InitFeatures::supported());
5772 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5774 for i in 0..max_accepted_htlcs {
5775 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5776 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5777 let payment_event = {
5778 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5779 check_added_monitors!(nodes[0], 1);
5781 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5782 assert_eq!(events.len(), 1);
5783 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5784 assert_eq!(htlcs[0].htlc_id, i);
5788 SendEvent::from_event(events.remove(0))
5790 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5791 check_added_monitors!(nodes[1], 0);
5792 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5794 expect_pending_htlcs_forwardable!(nodes[1]);
5795 expect_payment_received!(nodes[1], our_payment_hash, 100000);
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 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5800 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
5802 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5803 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5807 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5808 //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.
5809 let chanmon_cfgs = create_chanmon_cfgs(2);
5810 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5811 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5812 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5813 let channel_value = 100000;
5814 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::supported(), InitFeatures::supported());
5815 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5817 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5819 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, 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 send value that would put us over the max HTLC value in flight our peer will accept"));
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 send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
5827 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5830 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5832 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5833 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5834 let chanmon_cfgs = create_chanmon_cfgs(2);
5835 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5836 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5837 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5838 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5839 let htlc_minimum_msat: u64;
5841 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5842 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5843 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5845 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5846 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5847 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5848 check_added_monitors!(nodes[0], 1);
5849 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5850 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5851 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5852 assert!(nodes[1].node.list_channels().is_empty());
5853 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5854 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5855 check_added_monitors!(nodes[1], 1);
5859 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5860 //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
5861 let chanmon_cfgs = create_chanmon_cfgs(2);
5862 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5863 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5864 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5865 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5867 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5869 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5870 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5871 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5872 check_added_monitors!(nodes[0], 1);
5873 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5875 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5876 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5878 assert!(nodes[1].node.list_channels().is_empty());
5879 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5880 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5881 check_added_monitors!(nodes[1], 1);
5885 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5886 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5887 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5888 let chanmon_cfgs = create_chanmon_cfgs(2);
5889 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5890 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5891 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5892 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5893 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5894 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5896 let session_priv = SecretKey::from_slice(&{
5897 let mut session_key = [0; 32];
5898 let mut rng = thread_rng();
5899 rng.fill_bytes(&mut session_key);
5901 }).expect("RNG is bad!");
5903 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5904 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
5905 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
5906 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5908 let mut msg = msgs::UpdateAddHTLC {
5912 payment_hash: our_payment_hash,
5913 cltv_expiry: htlc_cltv,
5914 onion_routing_packet: onion_packet.clone(),
5917 for i in 0..super::channel::OUR_MAX_HTLCS {
5918 msg.htlc_id = i as u64;
5919 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5921 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5922 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5924 assert!(nodes[1].node.list_channels().is_empty());
5925 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5926 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5927 check_added_monitors!(nodes[1], 1);
5931 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5932 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5933 let chanmon_cfgs = create_chanmon_cfgs(2);
5934 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5935 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5936 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5937 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
5938 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5939 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5940 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5941 check_added_monitors!(nodes[0], 1);
5942 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5943 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5944 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
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 HTLC add would put them over our max HTLC value");
5949 check_added_monitors!(nodes[1], 1);
5953 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5954 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: 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 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5960 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, 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].cltv_expiry = 500000000;
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 provided CLTV expiry in seconds instead of block height");
5971 check_added_monitors!(nodes[1], 1);
5975 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5976 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5977 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5978 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5979 let chanmon_cfgs = create_chanmon_cfgs(2);
5980 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5983 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5984 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5985 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5986 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
5987 check_added_monitors!(nodes[0], 1);
5988 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5989 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5991 //Disconnect and Reconnect
5992 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5993 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5994 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5995 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5996 assert_eq!(reestablish_1.len(), 1);
5997 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5998 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5999 assert_eq!(reestablish_2.len(), 1);
6000 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6001 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6002 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6003 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6006 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6007 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6008 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6009 check_added_monitors!(nodes[1], 1);
6010 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6012 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6014 assert!(nodes[1].node.list_channels().is_empty());
6015 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6016 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6017 check_added_monitors!(nodes[1], 1);
6021 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6022 //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.
6024 let chanmon_cfgs = create_chanmon_cfgs(2);
6025 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6026 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6027 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6028 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6030 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6031 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6032 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6033 check_added_monitors!(nodes[0], 1);
6034 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6035 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6037 let update_msg = msgs::UpdateFulfillHTLC{
6040 payment_preimage: our_payment_preimage,
6043 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6045 assert!(nodes[0].node.list_channels().is_empty());
6046 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6047 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6048 check_added_monitors!(nodes[0], 1);
6052 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6053 //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.
6055 let chanmon_cfgs = create_chanmon_cfgs(2);
6056 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6057 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6058 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6059 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6061 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6062 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6063 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6064 check_added_monitors!(nodes[0], 1);
6065 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6066 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6068 let update_msg = msgs::UpdateFailHTLC{
6071 reason: msgs::OnionErrorPacket { data: Vec::new()},
6074 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6076 assert!(nodes[0].node.list_channels().is_empty());
6077 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6078 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6079 check_added_monitors!(nodes[0], 1);
6083 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6084 //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.
6086 let chanmon_cfgs = create_chanmon_cfgs(2);
6087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6089 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6090 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6092 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6093 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6094 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6095 check_added_monitors!(nodes[0], 1);
6096 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6097 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6099 let update_msg = msgs::UpdateFailMalformedHTLC{
6102 sha256_of_onion: [1; 32],
6103 failure_code: 0x8000,
6106 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6108 assert!(nodes[0].node.list_channels().is_empty());
6109 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6110 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6111 check_added_monitors!(nodes[0], 1);
6115 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6116 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6118 let chanmon_cfgs = create_chanmon_cfgs(2);
6119 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6120 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6121 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6122 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6124 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6126 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6127 check_added_monitors!(nodes[1], 1);
6129 let events = nodes[1].node.get_and_clear_pending_msg_events();
6130 assert_eq!(events.len(), 1);
6131 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6133 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, .. } } => {
6134 assert!(update_add_htlcs.is_empty());
6135 assert_eq!(update_fulfill_htlcs.len(), 1);
6136 assert!(update_fail_htlcs.is_empty());
6137 assert!(update_fail_malformed_htlcs.is_empty());
6138 assert!(update_fee.is_none());
6139 update_fulfill_htlcs[0].clone()
6141 _ => panic!("Unexpected event"),
6145 update_fulfill_msg.htlc_id = 1;
6147 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6149 assert!(nodes[0].node.list_channels().is_empty());
6150 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6151 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6152 check_added_monitors!(nodes[0], 1);
6156 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6157 //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.
6159 let chanmon_cfgs = create_chanmon_cfgs(2);
6160 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6161 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6162 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6163 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6165 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6167 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6168 check_added_monitors!(nodes[1], 1);
6170 let events = nodes[1].node.get_and_clear_pending_msg_events();
6171 assert_eq!(events.len(), 1);
6172 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6174 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, .. } } => {
6175 assert!(update_add_htlcs.is_empty());
6176 assert_eq!(update_fulfill_htlcs.len(), 1);
6177 assert!(update_fail_htlcs.is_empty());
6178 assert!(update_fail_malformed_htlcs.is_empty());
6179 assert!(update_fee.is_none());
6180 update_fulfill_htlcs[0].clone()
6182 _ => panic!("Unexpected event"),
6186 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6188 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6190 assert!(nodes[0].node.list_channels().is_empty());
6191 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6192 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6193 check_added_monitors!(nodes[0], 1);
6197 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6198 //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.
6200 let chanmon_cfgs = create_chanmon_cfgs(2);
6201 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6202 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6203 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6204 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6205 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6206 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6207 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6208 check_added_monitors!(nodes[0], 1);
6210 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6211 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6213 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6214 check_added_monitors!(nodes[1], 0);
6215 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6217 let events = nodes[1].node.get_and_clear_pending_msg_events();
6219 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6221 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, .. } } => {
6222 assert!(update_add_htlcs.is_empty());
6223 assert!(update_fulfill_htlcs.is_empty());
6224 assert!(update_fail_htlcs.is_empty());
6225 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6226 assert!(update_fee.is_none());
6227 update_fail_malformed_htlcs[0].clone()
6229 _ => panic!("Unexpected event"),
6232 update_msg.failure_code &= !0x8000;
6233 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6235 assert!(nodes[0].node.list_channels().is_empty());
6236 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6237 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6238 check_added_monitors!(nodes[0], 1);
6242 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6243 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6244 // * 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.
6246 let chanmon_cfgs = create_chanmon_cfgs(3);
6247 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6248 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6249 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6250 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6251 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6253 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6254 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6257 let mut payment_event = {
6258 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6259 check_added_monitors!(nodes[0], 1);
6260 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6261 assert_eq!(events.len(), 1);
6262 SendEvent::from_event(events.remove(0))
6264 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6265 check_added_monitors!(nodes[1], 0);
6266 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6267 expect_pending_htlcs_forwardable!(nodes[1]);
6268 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6269 assert_eq!(events_2.len(), 1);
6270 check_added_monitors!(nodes[1], 1);
6271 payment_event = SendEvent::from_event(events_2.remove(0));
6272 assert_eq!(payment_event.msgs.len(), 1);
6275 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6276 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6277 check_added_monitors!(nodes[2], 0);
6278 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6280 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6281 assert_eq!(events_3.len(), 1);
6282 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6284 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 } } => {
6285 assert!(update_add_htlcs.is_empty());
6286 assert!(update_fulfill_htlcs.is_empty());
6287 assert!(update_fail_htlcs.is_empty());
6288 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6289 assert!(update_fee.is_none());
6290 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6292 _ => panic!("Unexpected event"),
6296 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6298 check_added_monitors!(nodes[1], 0);
6299 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6300 expect_pending_htlcs_forwardable!(nodes[1]);
6301 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6302 assert_eq!(events_4.len(), 1);
6304 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
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, .. } } => {
6307 assert!(update_add_htlcs.is_empty());
6308 assert!(update_fulfill_htlcs.is_empty());
6309 assert_eq!(update_fail_htlcs.len(), 1);
6310 assert!(update_fail_malformed_htlcs.is_empty());
6311 assert!(update_fee.is_none());
6313 _ => panic!("Unexpected event"),
6316 check_added_monitors!(nodes[1], 1);
6319 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6320 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6321 // 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
6322 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6324 let chanmon_cfgs = create_chanmon_cfgs(2);
6325 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6326 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6327 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6328 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6330 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6332 // We route 2 dust-HTLCs between A and B
6333 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6334 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6335 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6337 // Cache one local commitment tx as previous
6338 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6340 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6341 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6342 check_added_monitors!(nodes[1], 0);
6343 expect_pending_htlcs_forwardable!(nodes[1]);
6344 check_added_monitors!(nodes[1], 1);
6346 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6347 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6348 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6349 check_added_monitors!(nodes[0], 1);
6351 // Cache one local commitment tx as lastest
6352 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6354 let events = nodes[0].node.get_and_clear_pending_msg_events();
6356 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6357 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6359 _ => panic!("Unexpected event"),
6362 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6363 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6365 _ => panic!("Unexpected event"),
6368 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6369 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6370 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6372 if announce_latest {
6373 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6375 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6378 check_closed_broadcast!(nodes[0], false);
6379 check_added_monitors!(nodes[0], 1);
6381 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6382 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6383 let events = nodes[0].node.get_and_clear_pending_events();
6384 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6385 assert_eq!(events.len(), 2);
6386 let mut first_failed = false;
6387 for event in events {
6389 Event::PaymentFailed { payment_hash, .. } => {
6390 if payment_hash == payment_hash_1 {
6391 assert!(!first_failed);
6392 first_failed = true;
6394 assert_eq!(payment_hash, payment_hash_2);
6397 _ => panic!("Unexpected event"),
6403 fn test_failure_delay_dust_htlc_local_commitment() {
6404 do_test_failure_delay_dust_htlc_local_commitment(true);
6405 do_test_failure_delay_dust_htlc_local_commitment(false);
6409 fn test_no_failure_dust_htlc_local_commitment() {
6410 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6411 // prone to error, we test here that a dummy transaction don't fail them.
6413 let chanmon_cfgs = create_chanmon_cfgs(2);
6414 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6415 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6416 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6417 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6420 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6422 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6423 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6425 // We route 2 dust-HTLCs between A and B
6426 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6427 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6429 // Build a dummy invalid transaction trying to spend a commitment tx
6431 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6432 script_sig: Script::new(),
6434 witness: Vec::new(),
6438 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6442 let dummy_tx = Transaction {
6449 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6450 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6451 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6452 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6453 // We broadcast a few more block to check everything is all right
6454 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6455 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6456 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6458 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6459 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6462 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6463 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6464 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6465 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6466 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6467 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6468 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6470 let chanmon_cfgs = create_chanmon_cfgs(3);
6471 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6472 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6473 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6474 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6476 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6478 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6479 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6481 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6482 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6484 // We revoked bs_commitment_tx
6486 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6487 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6490 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6491 let mut timeout_tx = Vec::new();
6493 // We fail dust-HTLC 1 by broadcast of local commitment tx
6494 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6495 check_closed_broadcast!(nodes[0], false);
6496 check_added_monitors!(nodes[0], 1);
6497 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6498 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6499 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6500 expect_payment_failed!(nodes[0], dust_hash, true);
6501 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6502 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6503 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6504 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6505 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6506 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6507 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6508 expect_payment_failed!(nodes[0], non_dust_hash, true);
6510 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6511 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6512 check_closed_broadcast!(nodes[0], false);
6513 check_added_monitors!(nodes[0], 1);
6514 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6515 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6516 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6517 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6519 expect_payment_failed!(nodes[0], dust_hash, true);
6520 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6521 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6522 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6523 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6524 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6525 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6526 expect_payment_failed!(nodes[0], non_dust_hash, true);
6528 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6530 let events = nodes[0].node.get_and_clear_pending_events();
6531 assert_eq!(events.len(), 2);
6534 Event::PaymentFailed { payment_hash, .. } => {
6535 if payment_hash == dust_hash { first = true; }
6536 else { first = false; }
6538 _ => panic!("Unexpected event"),
6541 Event::PaymentFailed { payment_hash, .. } => {
6542 if first { assert_eq!(payment_hash, non_dust_hash); }
6543 else { assert_eq!(payment_hash, dust_hash); }
6545 _ => panic!("Unexpected event"),
6552 fn test_sweep_outbound_htlc_failure_update() {
6553 do_test_sweep_outbound_htlc_failure_update(false, true);
6554 do_test_sweep_outbound_htlc_failure_update(false, false);
6555 do_test_sweep_outbound_htlc_failure_update(true, false);
6559 fn test_upfront_shutdown_script() {
6560 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6561 // enforce it at shutdown message
6563 let mut config = UserConfig::default();
6564 config.channel_options.announced_channel = true;
6565 config.peer_channel_config_limits.force_announced_channel_preference = false;
6566 config.channel_options.commit_upfront_shutdown_pubkey = false;
6567 let user_cfgs = [None, Some(config), None];
6568 let chanmon_cfgs = create_chanmon_cfgs(3);
6569 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6570 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6571 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6573 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6574 let flags = InitFeatures::supported();
6575 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6576 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6577 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6578 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6579 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6580 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6581 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6582 check_added_monitors!(nodes[2], 1);
6584 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6585 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6586 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6587 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6588 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6589 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6590 let events = nodes[2].node.get_and_clear_pending_msg_events();
6591 assert_eq!(events.len(), 1);
6593 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6594 _ => panic!("Unexpected event"),
6597 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6598 let mut flags_no = InitFeatures::supported();
6599 flags_no.unset_upfront_shutdown_script();
6600 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6601 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6602 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6603 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6604 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6605 let events = nodes[1].node.get_and_clear_pending_msg_events();
6606 assert_eq!(events.len(), 1);
6608 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6609 _ => panic!("Unexpected event"),
6612 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6613 // channel smoothly, opt-out is from channel initiator here
6614 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6615 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6616 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6617 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6618 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6619 let events = nodes[0].node.get_and_clear_pending_msg_events();
6620 assert_eq!(events.len(), 1);
6622 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6623 _ => panic!("Unexpected event"),
6626 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6627 //// channel smoothly
6628 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6629 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6630 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6631 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6632 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6633 let events = nodes[0].node.get_and_clear_pending_msg_events();
6634 assert_eq!(events.len(), 2);
6636 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6637 _ => panic!("Unexpected event"),
6640 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6641 _ => panic!("Unexpected event"),
6646 fn test_user_configurable_csv_delay() {
6647 // We test our channel constructors yield errors when we pass them absurd csv delay
6649 let mut low_our_to_self_config = UserConfig::default();
6650 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6651 let mut high_their_to_self_config = UserConfig::default();
6652 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6653 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6654 let chanmon_cfgs = create_chanmon_cfgs(2);
6655 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6656 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6657 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6659 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6660 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())));
6661 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) {
6663 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6664 _ => panic!("Unexpected event"),
6666 } else { assert!(false) }
6668 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6669 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6670 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6671 open_channel.to_self_delay = 200;
6672 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) {
6674 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6675 _ => panic!("Unexpected event"),
6677 } else { assert!(false); }
6679 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6680 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6681 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()));
6682 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6683 accept_channel.to_self_delay = 200;
6684 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
6685 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6687 &ErrorAction::SendErrorMessage { ref msg } => {
6688 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6690 _ => { assert!(false); }
6692 } else { assert!(false); }
6694 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6695 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6696 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6697 open_channel.to_self_delay = 200;
6698 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) {
6700 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6701 _ => panic!("Unexpected event"),
6703 } else { assert!(false); }
6707 fn test_data_loss_protect() {
6708 // We want to be sure that :
6709 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6710 // * we close channel in case of detecting other being fallen behind
6711 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6717 let chanmon_cfgs = create_chanmon_cfgs(2);
6718 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6719 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6720 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6722 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6724 // Cache node A state before any channel update
6725 let previous_node_state = nodes[0].node.encode();
6726 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6727 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6729 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6730 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6732 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6733 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6735 // Restore node A from previous state
6736 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6737 let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6738 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6739 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6740 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6741 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6742 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6744 let mut channel_monitors = HashMap::new();
6745 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6746 <(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 {
6747 keys_manager: &keys_manager,
6748 fee_estimator: &fee_estimator,
6750 logger: Arc::clone(&logger),
6751 tx_broadcaster: &tx_broadcaster,
6752 default_config: UserConfig::default(),
6753 channel_monitors: &mut channel_monitors,
6756 nodes[0].node = &node_state_0;
6757 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6758 nodes[0].chan_monitor = &monitor;
6759 nodes[0].chain_monitor = chain_monitor;
6761 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6762 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6763 nodes[0].block_notifier.register_listener(nodes[0].node);
6765 check_added_monitors!(nodes[0], 1);
6767 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6768 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6770 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6772 // Check we update monitor following learning of per_commitment_point from B
6773 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6774 check_added_monitors!(nodes[0], 2);
6777 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6778 assert_eq!(node_txn.len(), 0);
6781 let mut reestablish_1 = Vec::with_capacity(1);
6782 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6783 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6784 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6785 reestablish_1.push(msg.clone());
6786 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6787 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6789 &ErrorAction::SendErrorMessage { ref msg } => {
6790 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");
6792 _ => panic!("Unexpected event!"),
6795 panic!("Unexpected event")
6799 // Check we close channel detecting A is fallen-behind
6800 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6801 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6802 check_added_monitors!(nodes[1], 1);
6805 // Check A is able to claim to_remote output
6806 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6807 assert_eq!(node_txn.len(), 1);
6808 check_spends!(node_txn[0], chan.3);
6809 assert_eq!(node_txn[0].output.len(), 2);
6810 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6811 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
6812 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
6813 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6814 assert_eq!(spend_txn.len(), 1);
6815 check_spends!(spend_txn[0], node_txn[0]);
6819 fn test_check_htlc_underpaying() {
6820 // Send payment through A -> B but A is maliciously
6821 // sending a probe payment (i.e less than expected value0
6822 // to B, B should refuse payment.
6824 let chanmon_cfgs = create_chanmon_cfgs(2);
6825 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6826 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6827 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6829 // Create some initial channels
6830 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6832 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6834 // Node 3 is expecting payment of 100_000 but receive 10_000,
6835 // fail htlc like we didn't know the preimage.
6836 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
6837 nodes[1].node.process_pending_htlc_forwards();
6839 let events = nodes[1].node.get_and_clear_pending_msg_events();
6840 assert_eq!(events.len(), 1);
6841 let (update_fail_htlc, commitment_signed) = match events[0] {
6842 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 } } => {
6843 assert!(update_add_htlcs.is_empty());
6844 assert!(update_fulfill_htlcs.is_empty());
6845 assert_eq!(update_fail_htlcs.len(), 1);
6846 assert!(update_fail_malformed_htlcs.is_empty());
6847 assert!(update_fee.is_none());
6848 (update_fail_htlcs[0].clone(), commitment_signed)
6850 _ => panic!("Unexpected event"),
6852 check_added_monitors!(nodes[1], 1);
6854 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6855 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6857 // 10_000 msat as u64, followed by a height of 99 as u32
6858 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
6859 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
6860 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
6861 nodes[1].node.get_and_clear_pending_events();
6865 fn test_announce_disable_channels() {
6866 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6867 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6869 let chanmon_cfgs = create_chanmon_cfgs(2);
6870 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6871 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6872 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6874 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6875 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6876 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6879 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6880 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6882 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6883 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6884 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6885 assert_eq!(msg_events.len(), 3);
6886 for e in msg_events {
6888 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6889 let short_id = msg.contents.short_channel_id;
6890 // Check generated channel_update match list in PendingChannelUpdate
6891 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6892 panic!("Generated ChannelUpdate for wrong chan!");
6895 _ => panic!("Unexpected event"),
6899 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6900 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6901 assert_eq!(reestablish_1.len(), 3);
6902 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6903 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6904 assert_eq!(reestablish_2.len(), 3);
6906 // Reestablish chan_1
6907 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6908 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6909 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6910 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6911 // Reestablish chan_2
6912 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6913 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6914 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6915 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6916 // Reestablish chan_3
6917 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6918 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6919 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6920 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6922 nodes[0].node.timer_chan_freshness_every_min();
6923 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6927 fn test_bump_penalty_txn_on_revoked_commitment() {
6928 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6929 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6931 let chanmon_cfgs = create_chanmon_cfgs(2);
6932 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6933 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6934 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6936 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6937 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6938 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6939 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6941 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
6942 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6943 assert_eq!(revoked_txn[0].output.len(), 4);
6944 assert_eq!(revoked_txn[0].input.len(), 1);
6945 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6946 let revoked_txid = revoked_txn[0].txid();
6948 let mut penalty_sum = 0;
6949 for outp in revoked_txn[0].output.iter() {
6950 if outp.script_pubkey.is_v0_p2wsh() {
6951 penalty_sum += outp.value;
6955 // Connect blocks to change height_timer range to see if we use right soonest_timelock
6956 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6958 // Actually revoke tx by claiming a HTLC
6959 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6960 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6961 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6962 check_added_monitors!(nodes[1], 1);
6964 // One or more justice tx should have been broadcast, check it
6968 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6969 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6970 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6971 assert_eq!(node_txn[0].output.len(), 1);
6972 check_spends!(node_txn[0], revoked_txn[0]);
6973 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6974 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6975 penalty_1 = node_txn[0].txid();
6979 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
6980 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
6981 let mut penalty_2 = penalty_1;
6982 let mut feerate_2 = 0;
6984 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6985 assert_eq!(node_txn.len(), 1);
6986 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6987 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6988 assert_eq!(node_txn[0].output.len(), 1);
6989 check_spends!(node_txn[0], revoked_txn[0]);
6990 penalty_2 = node_txn[0].txid();
6991 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6992 assert_ne!(penalty_2, penalty_1);
6993 let fee_2 = penalty_sum - node_txn[0].output[0].value;
6994 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
6995 // Verify 25% bump heuristic
6996 assert!(feerate_2 * 100 >= feerate_1 * 125);
7000 assert_ne!(feerate_2, 0);
7002 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7003 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7005 let mut feerate_3 = 0;
7007 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7008 assert_eq!(node_txn.len(), 1);
7009 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7010 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7011 assert_eq!(node_txn[0].output.len(), 1);
7012 check_spends!(node_txn[0], revoked_txn[0]);
7013 penalty_3 = node_txn[0].txid();
7014 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7015 assert_ne!(penalty_3, penalty_2);
7016 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7017 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7018 // Verify 25% bump heuristic
7019 assert!(feerate_3 * 100 >= feerate_2 * 125);
7023 assert_ne!(feerate_3, 0);
7025 nodes[1].node.get_and_clear_pending_events();
7026 nodes[1].node.get_and_clear_pending_msg_events();
7030 fn test_bump_penalty_txn_on_revoked_htlcs() {
7031 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7032 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7034 let chanmon_cfgs = create_chanmon_cfgs(2);
7035 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7036 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7037 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7039 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7040 // Lock HTLC in both directions
7041 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7042 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7044 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7045 assert_eq!(revoked_local_txn[0].input.len(), 1);
7046 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7048 // Revoke local commitment tx
7049 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7051 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7052 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7053 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7054 check_closed_broadcast!(nodes[1], false);
7055 check_added_monitors!(nodes[1], 1);
7057 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7058 assert_eq!(revoked_htlc_txn.len(), 4);
7059 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7060 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7061 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7062 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7063 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7064 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7065 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7066 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7067 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7068 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7069 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7070 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7073 // Broadcast set of revoked txn on A
7074 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7075 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7077 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7078 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);
7083 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7084 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7085 // Verify claim tx are spending revoked HTLC txn
7086 assert_eq!(node_txn[4].input.len(), 2);
7087 assert_eq!(node_txn[4].output.len(), 1);
7088 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7089 first = node_txn[4].txid();
7090 // Store both feerates for later comparison
7091 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7092 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7093 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7097 // Connect three more block to see if bumped penalty are issued for HTLC txn
7098 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7099 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7101 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7102 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7104 check_spends!(node_txn[0], revoked_local_txn[0]);
7105 check_spends!(node_txn[1], revoked_local_txn[0]);
7110 // Few more blocks to confirm penalty txn
7111 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7112 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7113 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7115 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7116 assert_eq!(node_txn.len(), 1);
7118 assert_eq!(node_txn[0].input.len(), 2);
7119 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7120 // Verify bumped tx is different and 25% bump heuristic
7121 assert_ne!(first, node_txn[0].txid());
7122 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7123 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7124 assert!(feerate_2 * 100 > feerate_1 * 125);
7125 let txn = vec![node_txn[0].clone()];
7129 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7130 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7131 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7132 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7134 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7135 // We verify than no new transaction has been broadcast because previously
7136 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7137 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7138 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7139 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7140 // up bumped justice generation.
7141 assert_eq!(node_txn.len(), 0);
7144 check_closed_broadcast!(nodes[0], false);
7145 check_added_monitors!(nodes[0], 1);
7149 fn test_bump_penalty_txn_on_remote_commitment() {
7150 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7151 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7154 // Provide preimage for one
7155 // Check aggregation
7157 let chanmon_cfgs = create_chanmon_cfgs(2);
7158 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7159 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7160 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7162 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7163 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7164 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7166 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7167 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7168 assert_eq!(remote_txn[0].output.len(), 4);
7169 assert_eq!(remote_txn[0].input.len(), 1);
7170 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7172 // Claim a HTLC without revocation (provide B monitor with preimage)
7173 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7174 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7175 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7176 check_added_monitors!(nodes[1], 2);
7178 // One or more claim tx should have been broadcast, check it
7181 let feerate_timeout;
7182 let feerate_preimage;
7184 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7185 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7186 assert_eq!(node_txn[0].input.len(), 1);
7187 assert_eq!(node_txn[1].input.len(), 1);
7188 check_spends!(node_txn[0], remote_txn[0]);
7189 check_spends!(node_txn[1], remote_txn[0]);
7190 check_spends!(node_txn[2], chan.3);
7191 check_spends!(node_txn[3], node_txn[2]);
7192 check_spends!(node_txn[4], node_txn[2]);
7193 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7194 timeout = node_txn[0].txid();
7195 let index = node_txn[0].input[0].previous_output.vout;
7196 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7197 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7199 preimage = node_txn[1].txid();
7200 let index = node_txn[1].input[0].previous_output.vout;
7201 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7202 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7204 timeout = node_txn[1].txid();
7205 let index = node_txn[1].input[0].previous_output.vout;
7206 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7207 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7209 preimage = node_txn[0].txid();
7210 let index = node_txn[0].input[0].previous_output.vout;
7211 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7212 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7216 assert_ne!(feerate_timeout, 0);
7217 assert_ne!(feerate_preimage, 0);
7219 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7220 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7222 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7223 assert_eq!(node_txn.len(), 2);
7224 assert_eq!(node_txn[0].input.len(), 1);
7225 assert_eq!(node_txn[1].input.len(), 1);
7226 check_spends!(node_txn[0], remote_txn[0]);
7227 check_spends!(node_txn[1], remote_txn[0]);
7228 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7229 let index = node_txn[0].input[0].previous_output.vout;
7230 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7231 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7232 assert!(new_feerate * 100 > feerate_timeout * 125);
7233 assert_ne!(timeout, node_txn[0].txid());
7235 let index = node_txn[1].input[0].previous_output.vout;
7236 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7237 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7238 assert!(new_feerate * 100 > feerate_preimage * 125);
7239 assert_ne!(preimage, node_txn[1].txid());
7241 let index = node_txn[1].input[0].previous_output.vout;
7242 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7243 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7244 assert!(new_feerate * 100 > feerate_timeout * 125);
7245 assert_ne!(timeout, node_txn[1].txid());
7247 let index = node_txn[0].input[0].previous_output.vout;
7248 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7249 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7250 assert!(new_feerate * 100 > feerate_preimage * 125);
7251 assert_ne!(preimage, node_txn[0].txid());
7256 nodes[1].node.get_and_clear_pending_events();
7257 nodes[1].node.get_and_clear_pending_msg_events();
7261 fn test_set_outpoints_partial_claiming() {
7262 // - remote party claim tx, new bump tx
7263 // - disconnect remote claiming tx, new bump
7264 // - disconnect tx, see no tx anymore
7265 let chanmon_cfgs = create_chanmon_cfgs(2);
7266 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7267 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7268 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7270 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7271 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7272 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7274 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7275 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7276 assert_eq!(remote_txn.len(), 3);
7277 assert_eq!(remote_txn[0].output.len(), 4);
7278 assert_eq!(remote_txn[0].input.len(), 1);
7279 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7280 check_spends!(remote_txn[1], remote_txn[0]);
7281 check_spends!(remote_txn[2], remote_txn[0]);
7283 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7284 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7285 // Provide node A with both preimage
7286 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7287 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7288 check_added_monitors!(nodes[0], 2);
7289 nodes[0].node.get_and_clear_pending_events();
7290 nodes[0].node.get_and_clear_pending_msg_events();
7292 // Connect blocks on node A commitment transaction
7293 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7294 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7295 check_closed_broadcast!(nodes[0], false);
7296 check_added_monitors!(nodes[0], 1);
7297 // Verify node A broadcast tx claiming both HTLCs
7299 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7300 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7301 assert_eq!(node_txn.len(), 4);
7302 check_spends!(node_txn[0], remote_txn[0]);
7303 check_spends!(node_txn[1], chan.3);
7304 check_spends!(node_txn[2], node_txn[1]);
7305 check_spends!(node_txn[3], node_txn[1]);
7306 assert_eq!(node_txn[0].input.len(), 2);
7310 // Connect blocks on node B
7311 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7312 check_closed_broadcast!(nodes[1], false);
7313 check_added_monitors!(nodes[1], 1);
7314 // Verify node B broadcast 2 HTLC-timeout txn
7315 let partial_claim_tx = {
7316 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7317 assert_eq!(node_txn.len(), 3);
7318 check_spends!(node_txn[1], node_txn[0]);
7319 check_spends!(node_txn[2], node_txn[0]);
7320 assert_eq!(node_txn[1].input.len(), 1);
7321 assert_eq!(node_txn[2].input.len(), 1);
7325 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7326 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7327 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7329 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7330 assert_eq!(node_txn.len(), 1);
7331 check_spends!(node_txn[0], remote_txn[0]);
7332 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7335 nodes[0].node.get_and_clear_pending_msg_events();
7337 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7338 nodes[0].block_notifier.block_disconnected(&header, 102);
7340 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7341 assert_eq!(node_txn.len(), 1);
7342 check_spends!(node_txn[0], remote_txn[0]);
7343 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7347 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7348 nodes[0].block_notifier.block_disconnected(&header, 101);
7349 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7351 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7352 assert_eq!(node_txn.len(), 0);
7358 fn test_counterparty_raa_skip_no_crash() {
7359 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7360 // commitment transaction, we would have happily carried on and provided them the next
7361 // commitment transaction based on one RAA forward. This would probably eventually have led to
7362 // channel closure, but it would not have resulted in funds loss. Still, our
7363 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7364 // check simply that the channel is closed in response to such an RAA, but don't check whether
7365 // we decide to punish our counterparty for revoking their funds (as we don't currently
7367 let chanmon_cfgs = create_chanmon_cfgs(2);
7368 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7369 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7370 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7371 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
7373 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7374 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7375 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7376 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7377 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7379 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7380 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7381 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7382 check_added_monitors!(nodes[1], 1);
7386 fn test_bump_txn_sanitize_tracking_maps() {
7387 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7388 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7390 let chanmon_cfgs = create_chanmon_cfgs(2);
7391 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7392 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7393 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7395 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7396 // Lock HTLC in both directions
7397 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7398 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7400 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7401 assert_eq!(revoked_local_txn[0].input.len(), 1);
7402 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7404 // Revoke local commitment tx
7405 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7407 // Broadcast set of revoked txn on A
7408 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7409 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7411 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7412 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7413 check_closed_broadcast!(nodes[0], false);
7414 check_added_monitors!(nodes[0], 1);
7416 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7417 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7418 check_spends!(node_txn[0], revoked_local_txn[0]);
7419 check_spends!(node_txn[1], revoked_local_txn[0]);
7420 check_spends!(node_txn[2], revoked_local_txn[0]);
7421 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7425 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7426 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7427 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7429 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7430 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7431 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7432 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7438 fn test_override_channel_config() {
7439 let chanmon_cfgs = create_chanmon_cfgs(2);
7440 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7441 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7442 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7444 // Node0 initiates a channel to node1 using the override config.
7445 let mut override_config = UserConfig::default();
7446 override_config.own_channel_config.our_to_self_delay = 200;
7448 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7450 // Assert the channel created by node0 is using the override config.
7451 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7452 assert_eq!(res.channel_flags, 0);
7453 assert_eq!(res.to_self_delay, 200);
7457 fn test_override_0msat_htlc_minimum() {
7458 let mut zero_config = UserConfig::default();
7459 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7460 let chanmon_cfgs = create_chanmon_cfgs(2);
7461 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7462 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7463 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7465 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7466 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7467 assert_eq!(res.htlc_minimum_msat, 1);
7469 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &res);
7470 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7471 assert_eq!(res.htlc_minimum_msat, 1);
7475 fn test_simple_payment_secret() {
7476 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7477 // features, however.
7478 let chanmon_cfgs = create_chanmon_cfgs(3);
7479 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7480 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7481 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7483 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
7484 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
7486 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7487 let payment_secret = PaymentSecret([0xdb; 32]);
7488 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
7489 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7490 // Claiming with all the correct values but the wrong secret should result in nothing...
7491 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7492 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7493 // ...but with the right secret we should be able to claim all the way back
7494 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7498 fn test_simple_mpp() {
7499 // Simple test of sending a multi-path payment.
7500 let chanmon_cfgs = create_chanmon_cfgs(4);
7501 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7502 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7503 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7505 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7506 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7507 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7508 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
7510 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7511 let payment_secret = PaymentSecret([0xdb; 32]);
7512 let mut route = nodes[0].router.get_route(&nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
7513 let path = route.paths[0].clone();
7514 route.paths.push(path);
7515 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7516 route.paths[0][0].short_channel_id = chan_1_id;
7517 route.paths[0][1].short_channel_id = chan_3_id;
7518 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7519 route.paths[1][0].short_channel_id = chan_2_id;
7520 route.paths[1][1].short_channel_id = chan_4_id;
7521 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7522 // Claiming with all the correct values but the wrong secret should result in nothing...
7523 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7524 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7525 // ...but with the right secret we should be able to claim all the way back
7526 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7530 fn test_update_err_monitor_lockdown() {
7531 // Our monitor will lock update of local commitment transaction if a broadcastion condition
7532 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7533 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7535 // This scenario may happen in a watchtower setup, where watchtower process a block height
7536 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7537 // commitment at same time.
7539 let chanmon_cfgs = create_chanmon_cfgs(2);
7540 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7541 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7542 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7544 // Create some initial channel
7545 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
7546 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7548 // Rebalance the network to generate htlc in the two directions
7549 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7551 // Route a HTLC from node 0 to node 1 (but don't settle)
7552 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7554 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7555 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
7557 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7558 let monitor = monitors.get(&outpoint).unwrap();
7559 let mut w = test_utils::TestVecWriter(Vec::new());
7560 monitor.write_for_disk(&mut w).unwrap();
7561 let new_monitor = <(Sha256dHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7562 &mut ::std::io::Cursor::new(&w.0), Arc::new(test_utils::TestLogger::new())).unwrap().1;
7563 assert!(new_monitor == *monitor);
7564 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
7565 let watchtower = test_utils::TestChannelMonitor::new(chain_monitor, &chanmon_cfgs[0].tx_broadcaster, logger.clone(), &chanmon_cfgs[0].fee_estimator);
7566 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7569 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7570 watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7572 // Try to update ChannelMonitor
7573 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7574 check_added_monitors!(nodes[1], 1);
7575 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7576 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7577 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7578 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7579 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator) {
7580 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7581 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7582 } else { assert!(false); }
7583 } else { assert!(false); };
7584 // Our local monitor is in-sync and hasn't processed yet timeout
7585 check_added_monitors!(nodes[0], 1);
7586 let events = nodes[0].node.get_and_clear_pending_events();
7587 assert_eq!(events.len(), 1);