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::chaininterface::{ChainListener, ChainWatchInterfaceUtil};
7 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
8 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
9 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
10 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
11 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT, Channel, ChannelError};
13 use ln::router::{Route, RouteHop};
15 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, Features, FeatureContextChannel, FeatureContextInit, ErrorAction};
16 use util::enforcing_trait_impls::EnforcingChannelKeys;
18 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
19 use util::errors::APIError;
20 use util::ser::{Writeable, ReadableArgs};
21 use util::config::UserConfig;
22 use util::logger::Logger;
24 use bitcoin::util::hash::BitcoinHash;
25 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
26 use bitcoin::util::bip143;
27 use bitcoin::util::address::Address;
28 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
29 use bitcoin::blockdata::block::{Block, BlockHeader};
30 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::network::constants::Network;
36 use bitcoin_hashes::sha256::Hash as Sha256;
37 use bitcoin_hashes::Hash;
39 use secp256k1::{Secp256k1, Message};
40 use secp256k1::key::{PublicKey,SecretKey};
42 use std::collections::{BTreeSet, HashMap, HashSet};
43 use std::default::Default;
44 use std::sync::{Arc, Mutex};
45 use std::sync::atomic::Ordering;
48 use rand::{thread_rng, Rng};
50 use ln::functional_test_utils::*;
53 fn test_insane_channel_opens() {
54 // Stand up a network of 2 nodes
55 let nodes = create_network(2, &[None, None]);
57 // Instantiate channel parameters where we push the maximum msats given our
59 let channel_value_sat = 31337; // same as funding satoshis
60 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_our_channel_reserve_satoshis(channel_value_sat);
61 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
63 // Have node0 initiate a channel to node1 with aforementioned parameters
64 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42).unwrap();
66 // Extract the channel open message from node0 to node1
67 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
69 // Test helper that asserts we get the correct error string given a mutator
70 // that supposedly makes the channel open message insane
71 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
72 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), Features::<FeatureContextInit>::new(), &message_mutator(open_channel_message.clone()));
73 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
74 assert_eq!(msg_events.len(), 1);
75 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
77 &ErrorAction::SendErrorMessage { .. } => {
78 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
80 _ => panic!("unexpected event!"),
82 } else { assert!(false); }
85 use ln::channel::MAX_FUNDING_SATOSHIS;
86 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
88 // Test all mutations that would make the channel open message insane
89 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
91 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
93 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
95 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
97 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
99 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 });
101 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 });
103 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
105 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
109 fn test_async_inbound_update_fee() {
110 let mut nodes = create_network(2, &[None, None]);
111 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
112 let channel_id = chan.2;
115 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
119 // send (1) commitment_signed -.
120 // <- update_add_htlc/commitment_signed
121 // send (2) RAA (awaiting remote revoke) -.
122 // (1) commitment_signed is delivered ->
123 // .- send (3) RAA (awaiting remote revoke)
124 // (2) RAA is delivered ->
125 // .- send (4) commitment_signed
126 // <- (3) RAA is delivered
127 // send (5) commitment_signed -.
128 // <- (4) commitment_signed is delivered
130 // (5) commitment_signed is delivered ->
132 // (6) RAA is delivered ->
134 // First nodes[0] generates an update_fee
135 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
136 check_added_monitors!(nodes[0], 1);
138 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
139 assert_eq!(events_0.len(), 1);
140 let (update_msg, commitment_signed) = match events_0[0] { // (1)
141 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
142 (update_fee.as_ref(), commitment_signed)
144 _ => panic!("Unexpected event"),
147 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
149 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
150 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
151 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).unwrap();
152 check_added_monitors!(nodes[1], 1);
154 let payment_event = {
155 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
156 assert_eq!(events_1.len(), 1);
157 SendEvent::from_event(events_1.remove(0))
159 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
160 assert_eq!(payment_event.msgs.len(), 1);
162 // ...now when the messages get delivered everyone should be happy
163 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
164 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
165 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
166 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
167 check_added_monitors!(nodes[0], 1);
169 // deliver(1), generate (3):
170 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
171 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
172 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
173 check_added_monitors!(nodes[1], 1);
175 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
176 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
177 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
178 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
179 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
180 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
181 assert!(bs_update.update_fee.is_none()); // (4)
182 check_added_monitors!(nodes[1], 1);
184 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
185 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
186 assert!(as_update.update_add_htlcs.is_empty()); // (5)
187 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
188 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
189 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
190 assert!(as_update.update_fee.is_none()); // (5)
191 check_added_monitors!(nodes[0], 1);
193 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
194 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
195 // only (6) so get_event_msg's assert(len == 1) passes
196 check_added_monitors!(nodes[0], 1);
198 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
199 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
200 check_added_monitors!(nodes[1], 1);
202 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
203 check_added_monitors!(nodes[0], 1);
205 let events_2 = nodes[0].node.get_and_clear_pending_events();
206 assert_eq!(events_2.len(), 1);
208 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
209 _ => panic!("Unexpected event"),
212 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
213 check_added_monitors!(nodes[1], 1);
217 fn test_update_fee_unordered_raa() {
218 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
219 // crash in an earlier version of the update_fee patch)
220 let mut nodes = create_network(2, &[None, None]);
221 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
222 let channel_id = chan.2;
225 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
227 // First nodes[0] generates an update_fee
228 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
229 check_added_monitors!(nodes[0], 1);
231 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
232 assert_eq!(events_0.len(), 1);
233 let update_msg = match events_0[0] { // (1)
234 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
237 _ => panic!("Unexpected event"),
240 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
242 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
243 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
244 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).unwrap();
245 check_added_monitors!(nodes[1], 1);
247 let payment_event = {
248 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
249 assert_eq!(events_1.len(), 1);
250 SendEvent::from_event(events_1.remove(0))
252 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
253 assert_eq!(payment_event.msgs.len(), 1);
255 // ...now when the messages get delivered everyone should be happy
256 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
257 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
258 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
259 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
260 check_added_monitors!(nodes[0], 1);
262 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
263 check_added_monitors!(nodes[1], 1);
265 // We can't continue, sadly, because our (1) now has a bogus signature
269 fn test_multi_flight_update_fee() {
270 let nodes = create_network(2, &[None, None]);
271 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
272 let channel_id = chan.2;
275 // update_fee/commitment_signed ->
276 // .- send (1) RAA and (2) commitment_signed
277 // update_fee (never committed) ->
279 // We have to manually generate the above update_fee, it is allowed by the protocol but we
280 // don't track which updates correspond to which revoke_and_ack responses so we're in
281 // AwaitingRAA mode and will not generate the update_fee yet.
282 // <- (1) RAA delivered
283 // (3) is generated and send (4) CS -.
284 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
285 // know the per_commitment_point to use for it.
286 // <- (2) commitment_signed delivered
288 // B should send no response here
289 // (4) commitment_signed delivered ->
290 // <- RAA/commitment_signed delivered
293 // First nodes[0] generates an update_fee
294 let initial_feerate = get_feerate!(nodes[0], channel_id);
295 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
296 check_added_monitors!(nodes[0], 1);
298 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
299 assert_eq!(events_0.len(), 1);
300 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
301 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
302 (update_fee.as_ref().unwrap(), commitment_signed)
304 _ => panic!("Unexpected event"),
307 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
308 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
309 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
310 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
311 check_added_monitors!(nodes[1], 1);
313 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
315 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
316 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
317 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
319 // Create the (3) update_fee message that nodes[0] will generate before it does...
320 let mut update_msg_2 = msgs::UpdateFee {
321 channel_id: update_msg_1.channel_id.clone(),
322 feerate_per_kw: (initial_feerate + 30) as u32,
325 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
327 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
329 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
331 // Deliver (1), generating (3) and (4)
332 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
333 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
334 check_added_monitors!(nodes[0], 1);
335 assert!(as_second_update.update_add_htlcs.is_empty());
336 assert!(as_second_update.update_fulfill_htlcs.is_empty());
337 assert!(as_second_update.update_fail_htlcs.is_empty());
338 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
339 // Check that the update_fee newly generated matches what we delivered:
340 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
341 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
343 // Deliver (2) commitment_signed
344 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
345 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
346 check_added_monitors!(nodes[0], 1);
347 // No commitment_signed so get_event_msg's assert(len == 1) passes
349 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
350 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
351 check_added_monitors!(nodes[1], 1);
354 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
355 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
356 check_added_monitors!(nodes[1], 1);
358 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
359 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
360 check_added_monitors!(nodes[0], 1);
362 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
363 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
364 // No commitment_signed so get_event_msg's assert(len == 1) passes
365 check_added_monitors!(nodes[0], 1);
367 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
368 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
369 check_added_monitors!(nodes[1], 1);
373 fn test_update_fee_vanilla() {
374 let nodes = create_network(2, &[None, None]);
375 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
376 let channel_id = chan.2;
378 let feerate = get_feerate!(nodes[0], channel_id);
379 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
380 check_added_monitors!(nodes[0], 1);
382 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
383 assert_eq!(events_0.len(), 1);
384 let (update_msg, commitment_signed) = match events_0[0] {
385 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 } } => {
386 (update_fee.as_ref(), commitment_signed)
388 _ => panic!("Unexpected event"),
390 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
392 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
393 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
394 check_added_monitors!(nodes[1], 1);
396 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
397 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
398 check_added_monitors!(nodes[0], 1);
400 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
401 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
402 // No commitment_signed so get_event_msg's assert(len == 1) passes
403 check_added_monitors!(nodes[0], 1);
405 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
406 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
407 check_added_monitors!(nodes[1], 1);
411 fn test_update_fee_that_funder_cannot_afford() {
412 let nodes = create_network(2, &[None, None]);
413 let channel_value = 1888;
414 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
415 let channel_id = chan.2;
418 nodes[0].node.update_fee(channel_id, feerate).unwrap();
419 check_added_monitors!(nodes[0], 1);
420 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
422 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
424 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
426 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
427 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
429 let mut chan_lock = nodes[1].node.channel_state.lock().unwrap();
430 let chan = chan_lock.by_id.get_mut(&channel_id).unwrap();
432 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
433 let num_htlcs = chan.channel_monitor().get_latest_local_commitment_txn()[0].output.len() - 2;
434 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
435 let mut actual_fee = chan.channel_monitor().get_latest_local_commitment_txn()[0].output.iter().fold(0, |acc, output| acc + output.value);
436 actual_fee = channel_value - actual_fee;
437 assert_eq!(total_fee, actual_fee);
440 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
441 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
442 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
443 check_added_monitors!(nodes[0], 1);
445 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
447 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
449 //While producing the commitment_signed response after handling a received update_fee request the
450 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
451 //Should produce and error.
452 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
453 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
455 //clear the message we could not handle
456 nodes[1].node.get_and_clear_pending_msg_events();
460 fn test_update_fee_with_fundee_update_add_htlc() {
461 let mut nodes = create_network(2, &[None, None]);
462 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
463 let channel_id = chan.2;
466 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
468 let feerate = get_feerate!(nodes[0], channel_id);
469 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
470 check_added_monitors!(nodes[0], 1);
472 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
473 assert_eq!(events_0.len(), 1);
474 let (update_msg, commitment_signed) = match events_0[0] {
475 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 } } => {
476 (update_fee.as_ref(), commitment_signed)
478 _ => panic!("Unexpected event"),
480 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
482 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
487 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
489 // nothing happens since node[1] is in AwaitingRemoteRevoke
490 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
492 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
493 assert_eq!(added_monitors.len(), 0);
494 added_monitors.clear();
496 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
497 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
498 // node[1] has nothing to do
500 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
501 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
502 check_added_monitors!(nodes[0], 1);
504 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
505 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
506 // No commitment_signed so get_event_msg's assert(len == 1) passes
507 check_added_monitors!(nodes[0], 1);
508 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
509 check_added_monitors!(nodes[1], 1);
510 // AwaitingRemoteRevoke ends here
512 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
513 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
514 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
515 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
516 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
517 assert_eq!(commitment_update.update_fee.is_none(), true);
519 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
520 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
521 check_added_monitors!(nodes[0], 1);
522 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
524 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
525 check_added_monitors!(nodes[1], 1);
526 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
528 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
529 check_added_monitors!(nodes[1], 1);
530 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
531 // No commitment_signed so get_event_msg's assert(len == 1) passes
533 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
534 check_added_monitors!(nodes[0], 1);
535 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
537 expect_pending_htlcs_forwardable!(nodes[0]);
539 let events = nodes[0].node.get_and_clear_pending_events();
540 assert_eq!(events.len(), 1);
542 Event::PaymentReceived { .. } => { },
543 _ => panic!("Unexpected event"),
546 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
548 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
549 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
550 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
554 fn test_update_fee() {
555 let nodes = create_network(2, &[None, None]);
556 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
557 let channel_id = chan.2;
560 // (1) update_fee/commitment_signed ->
561 // <- (2) revoke_and_ack
562 // .- send (3) commitment_signed
563 // (4) update_fee/commitment_signed ->
564 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
565 // <- (3) commitment_signed delivered
566 // send (6) revoke_and_ack -.
567 // <- (5) deliver revoke_and_ack
568 // (6) deliver revoke_and_ack ->
569 // .- send (7) commitment_signed in response to (4)
570 // <- (7) deliver commitment_signed
573 // Create and deliver (1)...
574 let feerate = get_feerate!(nodes[0], channel_id);
575 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
576 check_added_monitors!(nodes[0], 1);
578 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
579 assert_eq!(events_0.len(), 1);
580 let (update_msg, commitment_signed) = match events_0[0] {
581 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 } } => {
582 (update_fee.as_ref(), commitment_signed)
584 _ => panic!("Unexpected event"),
586 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
588 // Generate (2) and (3):
589 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
590 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
591 check_added_monitors!(nodes[1], 1);
594 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
595 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
596 check_added_monitors!(nodes[0], 1);
598 // Create and deliver (4)...
599 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
600 check_added_monitors!(nodes[0], 1);
601 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602 assert_eq!(events_0.len(), 1);
603 let (update_msg, commitment_signed) = match events_0[0] {
604 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 } } => {
605 (update_fee.as_ref(), commitment_signed)
607 _ => panic!("Unexpected event"),
610 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
611 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
612 check_added_monitors!(nodes[1], 1);
614 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
615 // No commitment_signed so get_event_msg's assert(len == 1) passes
617 // Handle (3), creating (6):
618 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
619 check_added_monitors!(nodes[0], 1);
620 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621 // No commitment_signed so get_event_msg's assert(len == 1) passes
624 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
625 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
626 check_added_monitors!(nodes[0], 1);
628 // Deliver (6), creating (7):
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
630 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
631 assert!(commitment_update.update_add_htlcs.is_empty());
632 assert!(commitment_update.update_fulfill_htlcs.is_empty());
633 assert!(commitment_update.update_fail_htlcs.is_empty());
634 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
635 assert!(commitment_update.update_fee.is_none());
636 check_added_monitors!(nodes[1], 1);
639 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
640 check_added_monitors!(nodes[0], 1);
641 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
642 // No commitment_signed so get_event_msg's assert(len == 1) passes
644 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
645 check_added_monitors!(nodes[1], 1);
646 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
648 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
649 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
650 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
654 fn pre_funding_lock_shutdown_test() {
655 // Test sending a shutdown prior to funding_locked after funding generation
656 let nodes = create_network(2, &[None, None]);
657 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
658 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
659 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
660 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
662 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
663 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
665 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
666 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
668 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
669 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
670 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
671 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
672 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
673 assert!(node_0_none.is_none());
675 assert!(nodes[0].node.list_channels().is_empty());
676 assert!(nodes[1].node.list_channels().is_empty());
680 fn updates_shutdown_wait() {
681 // Test sending a shutdown with outstanding updates pending
682 let mut nodes = create_network(3, &[None, None, None]);
683 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
684 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
685 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
686 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
688 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
690 nodes[0].node.close_channel(&chan_1.2).unwrap();
691 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
692 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
693 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
694 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
696 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
697 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
699 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
700 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
701 else { panic!("New sends should fail!") };
702 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
703 else { panic!("New sends should fail!") };
705 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
706 check_added_monitors!(nodes[2], 1);
707 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
708 assert!(updates.update_add_htlcs.is_empty());
709 assert!(updates.update_fail_htlcs.is_empty());
710 assert!(updates.update_fail_malformed_htlcs.is_empty());
711 assert!(updates.update_fee.is_none());
712 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
713 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
714 check_added_monitors!(nodes[1], 1);
715 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
716 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
718 assert!(updates_2.update_add_htlcs.is_empty());
719 assert!(updates_2.update_fail_htlcs.is_empty());
720 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
721 assert!(updates_2.update_fee.is_none());
722 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
723 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
724 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
726 let events = nodes[0].node.get_and_clear_pending_events();
727 assert_eq!(events.len(), 1);
729 Event::PaymentSent { ref payment_preimage } => {
730 assert_eq!(our_payment_preimage, *payment_preimage);
732 _ => panic!("Unexpected event"),
735 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
736 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
737 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
738 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
739 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
740 assert!(node_0_none.is_none());
742 assert!(nodes[0].node.list_channels().is_empty());
744 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
745 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
746 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
747 assert!(nodes[1].node.list_channels().is_empty());
748 assert!(nodes[2].node.list_channels().is_empty());
752 fn htlc_fail_async_shutdown() {
753 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
754 let mut nodes = create_network(3, &[None, None, None]);
755 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
756 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
758 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
759 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
760 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
761 check_added_monitors!(nodes[0], 1);
762 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
763 assert_eq!(updates.update_add_htlcs.len(), 1);
764 assert!(updates.update_fulfill_htlcs.is_empty());
765 assert!(updates.update_fail_htlcs.is_empty());
766 assert!(updates.update_fail_malformed_htlcs.is_empty());
767 assert!(updates.update_fee.is_none());
769 nodes[1].node.close_channel(&chan_1.2).unwrap();
770 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
771 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
772 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
774 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
776 check_added_monitors!(nodes[1], 1);
777 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
778 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
780 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
781 assert!(updates_2.update_add_htlcs.is_empty());
782 assert!(updates_2.update_fulfill_htlcs.is_empty());
783 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
784 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
785 assert!(updates_2.update_fee.is_none());
787 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
788 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
790 let events = nodes[0].node.get_and_clear_pending_events();
791 assert_eq!(events.len(), 1);
793 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
794 assert_eq!(our_payment_hash, *payment_hash);
795 assert!(!rejected_by_dest);
797 _ => panic!("Unexpected event"),
800 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
801 assert_eq!(msg_events.len(), 2);
802 let node_0_closing_signed = match msg_events[0] {
803 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
804 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
807 _ => panic!("Unexpected event"),
809 match msg_events[1] {
810 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
811 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
813 _ => panic!("Unexpected event"),
816 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
818 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
819 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
820 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
821 assert!(node_0_none.is_none());
823 assert!(nodes[0].node.list_channels().is_empty());
825 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
826 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
827 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
828 assert!(nodes[1].node.list_channels().is_empty());
829 assert!(nodes[2].node.list_channels().is_empty());
832 fn do_test_shutdown_rebroadcast(recv_count: u8) {
833 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
834 // messages delivered prior to disconnect
835 let nodes = create_network(3, &[None, None, None]);
836 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
837 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
839 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
841 nodes[1].node.close_channel(&chan_1.2).unwrap();
842 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
844 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
845 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
847 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
851 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
852 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
854 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
855 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
856 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
857 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
859 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
860 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
861 assert!(node_1_shutdown == node_1_2nd_shutdown);
863 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
864 let node_0_2nd_shutdown = if recv_count > 0 {
865 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
866 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
871 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
873 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
876 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
878 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
879 check_added_monitors!(nodes[2], 1);
880 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
881 assert!(updates.update_add_htlcs.is_empty());
882 assert!(updates.update_fail_htlcs.is_empty());
883 assert!(updates.update_fail_malformed_htlcs.is_empty());
884 assert!(updates.update_fee.is_none());
885 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
886 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
887 check_added_monitors!(nodes[1], 1);
888 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
891 assert!(updates_2.update_add_htlcs.is_empty());
892 assert!(updates_2.update_fail_htlcs.is_empty());
893 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
894 assert!(updates_2.update_fee.is_none());
895 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
896 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
897 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
899 let events = nodes[0].node.get_and_clear_pending_events();
900 assert_eq!(events.len(), 1);
902 Event::PaymentSent { ref payment_preimage } => {
903 assert_eq!(our_payment_preimage, *payment_preimage);
905 _ => panic!("Unexpected event"),
908 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
910 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
911 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
912 assert!(node_1_closing_signed.is_some());
915 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
916 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
918 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
919 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
920 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
922 // If all closing_signeds weren't delivered we can just resume where we left off...
923 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
925 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
926 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
927 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
929 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
930 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
931 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
933 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
934 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
936 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
937 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
938 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
940 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
941 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
942 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
943 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
944 assert!(node_0_none.is_none());
946 // If one node, however, received + responded with an identical closing_signed we end
947 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
948 // There isn't really anything better we can do simply, but in the future we might
949 // explore storing a set of recently-closed channels that got disconnected during
950 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
951 // give our counterparty enough time to (potentially) broadcast a cooperative closing
953 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
955 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
956 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
957 assert_eq!(msg_events.len(), 1);
958 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
960 &ErrorAction::SendErrorMessage { ref msg } => {
961 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
962 assert_eq!(msg.channel_id, chan_1.2);
964 _ => panic!("Unexpected event!"),
966 } else { panic!("Needed SendErrorMessage close"); }
968 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
969 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
970 // closing_signed so we do it ourselves
971 check_closed_broadcast!(nodes[0], false);
974 assert!(nodes[0].node.list_channels().is_empty());
976 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
977 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
978 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
979 assert!(nodes[1].node.list_channels().is_empty());
980 assert!(nodes[2].node.list_channels().is_empty());
984 fn test_shutdown_rebroadcast() {
985 do_test_shutdown_rebroadcast(0);
986 do_test_shutdown_rebroadcast(1);
987 do_test_shutdown_rebroadcast(2);
991 fn fake_network_test() {
992 // Simple test which builds a network of ChannelManagers, connects them to each other, and
993 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
994 let nodes = create_network(4, &[None, None, None, None]);
996 // Create some initial channels
997 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
998 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
999 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1001 // Rebalance the network a bit by relaying one payment through all the channels...
1002 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1003 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1004 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1005 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1007 // Send some more payments
1008 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1009 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1010 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1012 // Test failure packets
1013 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1014 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1016 // Add a new channel that skips 3
1017 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1019 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1020 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1021 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1022 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1023 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1024 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1025 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1027 // Do some rebalance loop payments, simultaneously
1028 let mut hops = Vec::with_capacity(3);
1029 hops.push(RouteHop {
1030 pubkey: nodes[2].node.get_our_node_id(),
1031 short_channel_id: chan_2.0.contents.short_channel_id,
1033 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1035 hops.push(RouteHop {
1036 pubkey: nodes[3].node.get_our_node_id(),
1037 short_channel_id: chan_3.0.contents.short_channel_id,
1039 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1041 hops.push(RouteHop {
1042 pubkey: nodes[1].node.get_our_node_id(),
1043 short_channel_id: chan_4.0.contents.short_channel_id,
1045 cltv_expiry_delta: TEST_FINAL_CLTV,
1047 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;
1048 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;
1049 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1051 let mut hops = Vec::with_capacity(3);
1052 hops.push(RouteHop {
1053 pubkey: nodes[3].node.get_our_node_id(),
1054 short_channel_id: chan_4.0.contents.short_channel_id,
1056 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1058 hops.push(RouteHop {
1059 pubkey: nodes[2].node.get_our_node_id(),
1060 short_channel_id: chan_3.0.contents.short_channel_id,
1062 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1064 hops.push(RouteHop {
1065 pubkey: nodes[1].node.get_our_node_id(),
1066 short_channel_id: chan_2.0.contents.short_channel_id,
1068 cltv_expiry_delta: TEST_FINAL_CLTV,
1070 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;
1071 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;
1072 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1074 // Claim the rebalances...
1075 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1076 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1078 // Add a duplicate new channel from 2 to 4
1079 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1081 // Send some payments across both channels
1082 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1083 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1084 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1087 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1088 let events = nodes[0].node.get_and_clear_pending_msg_events();
1089 assert_eq!(events.len(), 0);
1090 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);
1092 //TODO: Test that routes work again here as we've been notified that the channel is full
1094 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1095 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1096 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1098 // Close down the channels...
1099 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1100 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1101 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1102 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1103 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1107 fn holding_cell_htlc_counting() {
1108 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1109 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1110 // commitment dance rounds.
1111 let mut nodes = create_network(3, &[None, None, None]);
1112 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1113 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1115 let mut payments = Vec::new();
1116 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1117 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1118 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1119 nodes[1].node.send_payment(route, payment_hash).unwrap();
1120 payments.push((payment_preimage, payment_hash));
1122 check_added_monitors!(nodes[1], 1);
1124 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1125 assert_eq!(events.len(), 1);
1126 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1127 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1129 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1130 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1132 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1133 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1134 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1135 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1136 } else { panic!("Unexpected event"); }
1137 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1138 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1140 // This should also be true if we try to forward a payment.
1141 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1142 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1143 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1144 check_added_monitors!(nodes[0], 1);
1146 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1147 assert_eq!(events.len(), 1);
1148 let payment_event = SendEvent::from_event(events.pop().unwrap());
1149 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1151 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1152 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1153 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1154 // fails), the second will process the resulting failure and fail the HTLC backward.
1155 expect_pending_htlcs_forwardable!(nodes[1]);
1156 expect_pending_htlcs_forwardable!(nodes[1]);
1157 check_added_monitors!(nodes[1], 1);
1159 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1160 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1161 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1163 let events = nodes[0].node.get_and_clear_pending_msg_events();
1164 assert_eq!(events.len(), 1);
1166 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1167 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1169 _ => panic!("Unexpected event"),
1172 let events = nodes[0].node.get_and_clear_pending_events();
1173 assert_eq!(events.len(), 1);
1175 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1176 assert_eq!(payment_hash, payment_hash_2);
1177 assert!(!rejected_by_dest);
1179 _ => panic!("Unexpected event"),
1182 // Now forward all the pending HTLCs and claim them back
1183 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1184 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1185 check_added_monitors!(nodes[2], 1);
1187 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1188 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1189 check_added_monitors!(nodes[1], 1);
1190 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1192 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1193 check_added_monitors!(nodes[1], 1);
1194 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1196 for ref update in as_updates.update_add_htlcs.iter() {
1197 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1199 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1200 check_added_monitors!(nodes[2], 1);
1201 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1202 check_added_monitors!(nodes[2], 1);
1203 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1205 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1206 check_added_monitors!(nodes[1], 1);
1207 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1208 check_added_monitors!(nodes[1], 1);
1209 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1211 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1212 check_added_monitors!(nodes[2], 1);
1214 expect_pending_htlcs_forwardable!(nodes[2]);
1216 let events = nodes[2].node.get_and_clear_pending_events();
1217 assert_eq!(events.len(), payments.len());
1218 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1220 &Event::PaymentReceived { ref payment_hash, .. } => {
1221 assert_eq!(*payment_hash, *hash);
1223 _ => panic!("Unexpected event"),
1227 for (preimage, _) in payments.drain(..) {
1228 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1231 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1235 fn duplicate_htlc_test() {
1236 // Test that we accept duplicate payment_hash HTLCs across the network and that
1237 // claiming/failing them are all separate and don't affect each other
1238 let mut nodes = create_network(6, &[None, None, None, None, None, None]);
1240 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1241 create_announced_chan_between_nodes(&nodes, 0, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1242 create_announced_chan_between_nodes(&nodes, 1, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1243 create_announced_chan_between_nodes(&nodes, 2, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1244 create_announced_chan_between_nodes(&nodes, 3, 4, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1245 create_announced_chan_between_nodes(&nodes, 3, 5, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1247 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1249 *nodes[0].network_payment_count.borrow_mut() -= 1;
1250 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1252 *nodes[0].network_payment_count.borrow_mut() -= 1;
1253 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1255 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1256 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1257 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1261 fn test_duplicate_htlc_different_direction_onchain() {
1262 // Test that ChannelMonitor doesn't generate 2 preimage txn
1263 // when we have 2 HTLCs with same preimage that go across a node
1264 // in opposite directions.
1265 let nodes = create_network(2, &[None, None]);
1267 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1270 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1272 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1274 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1275 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1277 // Provide preimage to node 0 by claiming payment
1278 nodes[0].node.claim_funds(payment_preimage, 800_000);
1279 check_added_monitors!(nodes[0], 1);
1281 // Broadcast node 1 commitment txn
1282 let remote_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
1284 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1285 let mut has_both_htlcs = 0; // check htlcs match ones committed
1286 for outp in remote_txn[0].output.iter() {
1287 if outp.value == 800_000 / 1000 {
1288 has_both_htlcs += 1;
1289 } else if outp.value == 900_000 / 1000 {
1290 has_both_htlcs += 1;
1293 assert_eq!(has_both_htlcs, 2);
1295 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1296 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1298 // Check we only broadcast 1 timeout tx
1299 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1300 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()) };
1301 assert_eq!(claim_txn.len(), 7);
1302 check_spends!(claim_txn[2], chan_1.3);
1303 check_spends!(claim_txn[3], claim_txn[2]);
1304 assert_eq!(claim_txn[0], claim_txn[5]);
1305 assert_eq!(claim_txn[1], claim_txn[6]);
1306 assert_eq!(htlc_pair.0.input.len(), 1);
1307 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1308 check_spends!(htlc_pair.0, remote_txn[0].clone());
1309 assert_eq!(htlc_pair.1.input.len(), 1);
1310 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1311 check_spends!(htlc_pair.1, remote_txn[0].clone());
1313 let events = nodes[0].node.get_and_clear_pending_msg_events();
1314 assert_eq!(events.len(), 2);
1317 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1318 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, .. } } => {
1319 assert!(update_add_htlcs.is_empty());
1320 assert!(update_fail_htlcs.is_empty());
1321 assert_eq!(update_fulfill_htlcs.len(), 1);
1322 assert!(update_fail_malformed_htlcs.is_empty());
1323 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1325 _ => panic!("Unexpected event"),
1330 fn do_channel_reserve_test(test_recv: bool) {
1332 let mut nodes = create_network(3, &[None, None, None]);
1333 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1334 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1336 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1337 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1339 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1340 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1342 macro_rules! get_route_and_payment_hash {
1343 ($recv_value: expr) => {{
1344 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1345 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1346 (route, payment_hash, payment_preimage)
1350 macro_rules! expect_forward {
1352 let mut events = $node.node.get_and_clear_pending_msg_events();
1353 assert_eq!(events.len(), 1);
1354 check_added_monitors!($node, 1);
1355 let payment_event = SendEvent::from_event(events.remove(0));
1360 let feemsat = 239; // somehow we know?
1361 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1363 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1365 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1367 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1368 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1369 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1371 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
1372 _ => panic!("Unknown error variants"),
1374 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1375 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);
1378 let mut htlc_id = 0;
1379 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1380 // nodes[0]'s wealth
1382 let amt_msat = recv_value_0 + total_fee_msat;
1383 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1386 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1389 let (stat01_, stat11_, stat12_, stat22_) = (
1390 get_channel_value_stat!(nodes[0], chan_1.2),
1391 get_channel_value_stat!(nodes[1], chan_1.2),
1392 get_channel_value_stat!(nodes[1], chan_2.2),
1393 get_channel_value_stat!(nodes[2], chan_2.2),
1396 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1397 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1398 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1399 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1400 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1404 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1405 // attempt to get channel_reserve violation
1406 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1407 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1409 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1410 _ => panic!("Unknown error variants"),
1412 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1413 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 1);
1416 // adding pending output
1417 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1418 let amt_msat_1 = recv_value_1 + total_fee_msat;
1420 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1421 let payment_event_1 = {
1422 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1423 check_added_monitors!(nodes[0], 1);
1425 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1426 assert_eq!(events.len(), 1);
1427 SendEvent::from_event(events.remove(0))
1429 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1431 // channel reserve test with htlc pending output > 0
1432 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1434 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1435 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1436 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1437 _ => panic!("Unknown error variants"),
1439 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1440 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 2);
1444 // test channel_reserve test on nodes[1] side
1445 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1447 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1448 let secp_ctx = Secp256k1::new();
1449 let session_priv = SecretKey::from_slice(&{
1450 let mut session_key = [0; 32];
1451 let mut rng = thread_rng();
1452 rng.fill_bytes(&mut session_key);
1454 }).expect("RNG is bad!");
1456 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1457 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1458 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1459 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1460 let msg = msgs::UpdateAddHTLC {
1461 channel_id: chan_1.2,
1463 amount_msat: htlc_msat,
1464 payment_hash: our_payment_hash,
1465 cltv_expiry: htlc_cltv,
1466 onion_routing_packet: onion_packet,
1470 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1471 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1472 assert_eq!(nodes[1].node.list_channels().len(), 1);
1473 assert_eq!(nodes[1].node.list_channels().len(), 1);
1474 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1475 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
1480 // split the rest to test holding cell
1481 let recv_value_21 = recv_value_2/2;
1482 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1484 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1485 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);
1488 // now see if they go through on both sides
1489 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1490 // but this will stuck in the holding cell
1491 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1492 check_added_monitors!(nodes[0], 0);
1493 let events = nodes[0].node.get_and_clear_pending_events();
1494 assert_eq!(events.len(), 0);
1496 // test with outbound holding cell amount > 0
1498 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1499 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1500 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1501 _ => panic!("Unknown error variants"),
1503 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1504 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 3);
1507 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1508 // this will also stuck in the holding cell
1509 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1510 check_added_monitors!(nodes[0], 0);
1511 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1512 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1514 // flush the pending htlc
1515 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1516 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1517 check_added_monitors!(nodes[1], 1);
1519 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1520 check_added_monitors!(nodes[0], 1);
1521 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1523 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1524 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1525 // No commitment_signed so get_event_msg's assert(len == 1) passes
1526 check_added_monitors!(nodes[0], 1);
1528 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1529 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1530 check_added_monitors!(nodes[1], 1);
1532 expect_pending_htlcs_forwardable!(nodes[1]);
1534 let ref payment_event_11 = expect_forward!(nodes[1]);
1535 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1536 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1538 expect_pending_htlcs_forwardable!(nodes[2]);
1539 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1541 // flush the htlcs in the holding cell
1542 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1543 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1544 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1545 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1546 expect_pending_htlcs_forwardable!(nodes[1]);
1548 let ref payment_event_3 = expect_forward!(nodes[1]);
1549 assert_eq!(payment_event_3.msgs.len(), 2);
1550 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1551 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1553 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1554 expect_pending_htlcs_forwardable!(nodes[2]);
1556 let events = nodes[2].node.get_and_clear_pending_events();
1557 assert_eq!(events.len(), 2);
1559 Event::PaymentReceived { ref payment_hash, amt } => {
1560 assert_eq!(our_payment_hash_21, *payment_hash);
1561 assert_eq!(recv_value_21, amt);
1563 _ => panic!("Unexpected event"),
1566 Event::PaymentReceived { ref payment_hash, amt } => {
1567 assert_eq!(our_payment_hash_22, *payment_hash);
1568 assert_eq!(recv_value_22, amt);
1570 _ => panic!("Unexpected event"),
1573 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1574 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1575 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1577 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);
1578 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1579 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1580 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1582 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1583 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1587 fn channel_reserve_test() {
1588 do_channel_reserve_test(false);
1589 do_channel_reserve_test(true);
1593 fn channel_reserve_in_flight_removes() {
1594 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1595 // can send to its counterparty, but due to update ordering, the other side may not yet have
1596 // considered those HTLCs fully removed.
1597 // This tests that we don't count HTLCs which will not be included in the next remote
1598 // commitment transaction towards the reserve value (as it implies no commitment transaction
1599 // will be generated which violates the remote reserve value).
1600 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1602 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1603 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1604 // you only consider the value of the first HTLC, it may not),
1605 // * start routing a third HTLC from A to B,
1606 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1607 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1608 // * deliver the first fulfill from B
1609 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1611 // * deliver A's response CS and RAA.
1612 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1613 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1614 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1615 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1616 let mut nodes = create_network(2, &[None, None]);
1617 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1619 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1620 // Route the first two HTLCs.
1621 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1622 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1624 // Start routing the third HTLC (this is just used to get everyone in the right state).
1625 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1627 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1628 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1629 check_added_monitors!(nodes[0], 1);
1630 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1631 assert_eq!(events.len(), 1);
1632 SendEvent::from_event(events.remove(0))
1635 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1636 // initial fulfill/CS.
1637 assert!(nodes[1].node.claim_funds(payment_preimage_1, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1638 check_added_monitors!(nodes[1], 1);
1639 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1641 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1642 // remove the second HTLC when we send the HTLC back from B to A.
1643 assert!(nodes[1].node.claim_funds(payment_preimage_2, 20000));
1644 check_added_monitors!(nodes[1], 1);
1645 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1647 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1648 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1649 check_added_monitors!(nodes[0], 1);
1650 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1651 expect_payment_sent!(nodes[0], payment_preimage_1);
1653 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1654 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1655 check_added_monitors!(nodes[1], 1);
1656 // B is already AwaitingRAA, so cant generate a CS here
1657 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1659 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1660 check_added_monitors!(nodes[1], 1);
1661 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1663 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1664 check_added_monitors!(nodes[0], 1);
1665 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1667 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1668 check_added_monitors!(nodes[1], 1);
1669 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1671 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1672 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1673 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1674 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1675 // on-chain as necessary).
1676 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1677 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1678 check_added_monitors!(nodes[0], 1);
1679 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1680 expect_payment_sent!(nodes[0], payment_preimage_2);
1682 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1683 check_added_monitors!(nodes[1], 1);
1684 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1686 expect_pending_htlcs_forwardable!(nodes[1]);
1687 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1689 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1690 // resolve the second HTLC from A's point of view.
1691 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1692 check_added_monitors!(nodes[0], 1);
1693 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1695 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1696 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1697 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1699 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1700 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1701 check_added_monitors!(nodes[1], 1);
1702 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1703 assert_eq!(events.len(), 1);
1704 SendEvent::from_event(events.remove(0))
1707 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1708 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1709 check_added_monitors!(nodes[0], 1);
1710 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1712 // Now just resolve all the outstanding messages/HTLCs for completeness...
1714 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1715 check_added_monitors!(nodes[1], 1);
1716 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1718 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1719 check_added_monitors!(nodes[1], 1);
1721 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1722 check_added_monitors!(nodes[0], 1);
1723 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1725 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1726 check_added_monitors!(nodes[1], 1);
1727 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1729 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1730 check_added_monitors!(nodes[0], 1);
1732 expect_pending_htlcs_forwardable!(nodes[0]);
1733 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1735 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1736 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1740 fn channel_monitor_network_test() {
1741 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1742 // tests that ChannelMonitor is able to recover from various states.
1743 let nodes = create_network(5, &[None, None, None, None, None]);
1745 // Create some initial channels
1746 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1747 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1748 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1749 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1751 // Rebalance the network a bit by relaying one payment through all the channels...
1752 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1753 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1754 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1755 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1757 // Simple case with no pending HTLCs:
1758 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1760 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1761 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1762 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1763 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1765 get_announce_close_broadcast_events(&nodes, 0, 1);
1766 assert_eq!(nodes[0].node.list_channels().len(), 0);
1767 assert_eq!(nodes[1].node.list_channels().len(), 1);
1769 // One pending HTLC is discarded by the force-close:
1770 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1772 // Simple case of one pending HTLC to HTLC-Timeout
1773 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1775 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1776 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1777 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1778 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1780 get_announce_close_broadcast_events(&nodes, 1, 2);
1781 assert_eq!(nodes[1].node.list_channels().len(), 0);
1782 assert_eq!(nodes[2].node.list_channels().len(), 1);
1784 macro_rules! claim_funds {
1785 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1787 assert!($node.node.claim_funds($preimage, $amount));
1788 check_added_monitors!($node, 1);
1790 let events = $node.node.get_and_clear_pending_msg_events();
1791 assert_eq!(events.len(), 1);
1793 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1794 assert!(update_add_htlcs.is_empty());
1795 assert!(update_fail_htlcs.is_empty());
1796 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1798 _ => panic!("Unexpected event"),
1804 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1805 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1806 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1807 let node2_commitment_txid;
1809 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1810 node2_commitment_txid = node_txn[0].txid();
1812 // Claim the payment on nodes[3], giving it knowledge of the preimage
1813 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
1815 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1816 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1818 check_preimage_claim(&nodes[3], &node_txn);
1820 get_announce_close_broadcast_events(&nodes, 2, 3);
1821 assert_eq!(nodes[2].node.list_channels().len(), 0);
1822 assert_eq!(nodes[3].node.list_channels().len(), 1);
1824 { // Cheat and reset nodes[4]'s height to 1
1825 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1826 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
1829 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
1830 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
1831 // One pending HTLC to time out:
1832 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
1833 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
1837 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1838 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1839 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
1840 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1841 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1844 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
1846 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
1847 node_txn.retain(|tx| {
1848 if tx.input[0].previous_output.txid == node2_commitment_txid {
1854 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
1856 // Claim the payment on nodes[4], giving it knowledge of the preimage
1857 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
1859 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1861 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1862 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
1863 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1864 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1867 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
1869 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1870 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
1872 check_preimage_claim(&nodes[4], &node_txn);
1874 get_announce_close_broadcast_events(&nodes, 3, 4);
1875 assert_eq!(nodes[3].node.list_channels().len(), 0);
1876 assert_eq!(nodes[4].node.list_channels().len(), 0);
1880 fn test_justice_tx() {
1881 // Test justice txn built on revoked HTLC-Success tx, against both sides
1882 let mut alice_config = UserConfig::default();
1883 alice_config.channel_options.announced_channel = true;
1884 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
1885 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
1886 let mut bob_config = UserConfig::default();
1887 bob_config.channel_options.announced_channel = true;
1888 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
1889 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
1890 let cfgs = [Some(alice_config), Some(bob_config)];
1891 let nodes = create_network(2, &cfgs);
1892 // Create some new channels:
1893 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1895 // A pending HTLC which will be revoked:
1896 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1897 // Get the will-be-revoked local txn from nodes[0]
1898 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter_mut().next().unwrap().1.channel_monitor().get_latest_local_commitment_txn();
1899 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
1900 assert_eq!(revoked_local_txn[0].input.len(), 1);
1901 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
1902 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
1903 assert_eq!(revoked_local_txn[1].input.len(), 1);
1904 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1905 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1906 // Revoke the old state
1907 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
1910 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1911 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1913 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1914 assert_eq!(node_txn.len(), 3);
1915 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1916 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
1918 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1919 node_txn.swap_remove(0);
1920 node_txn.truncate(1);
1922 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
1924 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1925 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
1926 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1927 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1928 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
1930 get_announce_close_broadcast_events(&nodes, 0, 1);
1932 assert_eq!(nodes[0].node.list_channels().len(), 0);
1933 assert_eq!(nodes[1].node.list_channels().len(), 0);
1935 // We test justice_tx build by A on B's revoked HTLC-Success tx
1936 // Create some new channels:
1937 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1939 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1943 // A pending HTLC which will be revoked:
1944 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1945 // Get the will-be-revoked local txn from B
1946 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter_mut().next().unwrap().1.channel_monitor().get_latest_local_commitment_txn();
1947 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
1948 assert_eq!(revoked_local_txn[0].input.len(), 1);
1949 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
1950 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
1951 // Revoke the old state
1952 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
1954 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1955 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1957 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
1958 assert_eq!(node_txn.len(), 3);
1959 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1960 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
1962 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1963 node_txn.swap_remove(0);
1965 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
1967 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1968 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
1969 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1970 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1971 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
1973 get_announce_close_broadcast_events(&nodes, 0, 1);
1974 assert_eq!(nodes[0].node.list_channels().len(), 0);
1975 assert_eq!(nodes[1].node.list_channels().len(), 0);
1979 fn revoked_output_claim() {
1980 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
1981 // transaction is broadcast by its counterparty
1982 let nodes = create_network(2, &[None, None]);
1983 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
1984 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
1985 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
1986 assert_eq!(revoked_local_txn.len(), 1);
1987 // Only output is the full channel value back to nodes[0]:
1988 assert_eq!(revoked_local_txn[0].output.len(), 1);
1989 // Send a payment through, updating everyone's latest commitment txn
1990 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
1992 // Inform nodes[1] that nodes[0] broadcast a stale tx
1993 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1994 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1995 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1996 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
1998 assert_eq!(node_txn[0], node_txn[2]);
2000 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2001 check_spends!(node_txn[1], chan_1.3.clone());
2003 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2004 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2005 get_announce_close_broadcast_events(&nodes, 0, 1);
2009 fn claim_htlc_outputs_shared_tx() {
2010 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2011 let nodes = create_network(2, &[None, None]);
2013 // Create some new channel:
2014 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2016 // Rebalance the network to generate htlc in the two directions
2017 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2018 // 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
2019 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2020 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2022 // Get the will-be-revoked local txn from node[0]
2023 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2024 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2025 assert_eq!(revoked_local_txn[0].input.len(), 1);
2026 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2027 assert_eq!(revoked_local_txn[1].input.len(), 1);
2028 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2029 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2030 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
2032 //Revoke the old state
2033 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2036 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2037 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2038 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2039 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2041 let events = nodes[1].node.get_and_clear_pending_events();
2042 assert_eq!(events.len(), 1);
2044 Event::PaymentFailed { payment_hash, .. } => {
2045 assert_eq!(payment_hash, payment_hash_2);
2047 _ => panic!("Unexpected event"),
2050 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2051 assert_eq!(node_txn.len(), 4);
2053 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2054 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2056 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
2058 let mut witness_lens = BTreeSet::new();
2059 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2060 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2061 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2062 assert_eq!(witness_lens.len(), 3);
2063 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2064 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2065 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2067 // Next nodes[1] broadcasts its current local tx state:
2068 assert_eq!(node_txn[1].input.len(), 1);
2069 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2071 assert_eq!(node_txn[2].input.len(), 1);
2072 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2073 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2074 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2075 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2076 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2078 get_announce_close_broadcast_events(&nodes, 0, 1);
2079 assert_eq!(nodes[0].node.list_channels().len(), 0);
2080 assert_eq!(nodes[1].node.list_channels().len(), 0);
2084 fn claim_htlc_outputs_single_tx() {
2085 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2086 let nodes = create_network(2, &[None, None]);
2088 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2090 // Rebalance the network to generate htlc in the two directions
2091 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2092 // 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
2093 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2094 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2095 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2097 // Get the will-be-revoked local txn from node[0]
2098 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2100 //Revoke the old state
2101 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2104 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2105 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2106 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2107 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2109 let events = nodes[1].node.get_and_clear_pending_events();
2110 assert_eq!(events.len(), 1);
2112 Event::PaymentFailed { payment_hash, .. } => {
2113 assert_eq!(payment_hash, payment_hash_2);
2115 _ => panic!("Unexpected event"),
2118 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2119 assert_eq!(node_txn.len(), 29); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan) + 5 * (1 local commitment tx + 1 htlc timeout tx)
2121 assert_eq!(node_txn[0], node_txn[7]);
2122 assert_eq!(node_txn[1], node_txn[8]);
2123 assert_eq!(node_txn[2], node_txn[9]);
2124 assert_eq!(node_txn[3], node_txn[10]);
2125 assert_eq!(node_txn[4], node_txn[11]);
2126 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
2127 assert_eq!(node_txn[4], node_txn[6]);
2129 assert_eq!(node_txn[0].input.len(), 1);
2130 assert_eq!(node_txn[1].input.len(), 1);
2131 assert_eq!(node_txn[2].input.len(), 1);
2133 fn get_txout(out_point: &BitcoinOutPoint, tx: &Transaction) -> Option<TxOut> {
2134 if out_point.txid == tx.txid() {
2135 tx.output.get(out_point.vout as usize).cloned()
2140 node_txn[0].verify(|out|get_txout(out, &revoked_local_txn[0])).unwrap();
2141 node_txn[1].verify(|out|get_txout(out, &revoked_local_txn[0])).unwrap();
2142 node_txn[2].verify(|out|get_txout(out, &revoked_local_txn[0])).unwrap();
2144 let mut witness_lens = BTreeSet::new();
2145 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2146 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2147 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2148 assert_eq!(witness_lens.len(), 3);
2149 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2150 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2151 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2153 assert_eq!(node_txn[3].input.len(), 1);
2154 check_spends!(node_txn[3], chan_1.3.clone());
2156 assert_eq!(node_txn[4].input.len(), 1);
2157 let witness_script = node_txn[4].input[0].witness.last().unwrap();
2158 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2159 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2160 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2161 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2163 get_announce_close_broadcast_events(&nodes, 0, 1);
2164 assert_eq!(nodes[0].node.list_channels().len(), 0);
2165 assert_eq!(nodes[1].node.list_channels().len(), 0);
2169 fn test_htlc_on_chain_success() {
2170 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2171 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2172 // broadcasting the right event to other nodes in payment path.
2173 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2174 // A --------------------> B ----------------------> C (preimage)
2175 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2176 // commitment transaction was broadcast.
2177 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2179 // B should be able to claim via preimage if A then broadcasts its local tx.
2180 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2181 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2182 // PaymentSent event).
2184 let nodes = create_network(3, &[None, None, None]);
2186 // Create some initial channels
2187 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2188 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2190 // Rebalance the network a bit by relaying one payment through all the channels...
2191 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2192 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2194 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2195 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2196 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2198 // Broadcast legit commitment tx from C on B's chain
2199 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2200 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2201 assert_eq!(commitment_tx.len(), 1);
2202 check_spends!(commitment_tx[0], chan_2.3.clone());
2203 nodes[2].node.claim_funds(our_payment_preimage, 3_000_000);
2204 nodes[2].node.claim_funds(our_payment_preimage_2, 3_000_000);
2205 check_added_monitors!(nodes[2], 2);
2206 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2207 assert!(updates.update_add_htlcs.is_empty());
2208 assert!(updates.update_fail_htlcs.is_empty());
2209 assert!(updates.update_fail_malformed_htlcs.is_empty());
2210 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2212 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2213 check_closed_broadcast!(nodes[2], false);
2214 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2215 assert_eq!(node_txn.len(), 7);
2216 assert_eq!(node_txn[0], node_txn[3]);
2217 assert_eq!(node_txn[1], node_txn[4]);
2218 assert_eq!(node_txn[0], node_txn[5]);
2219 assert_eq!(node_txn[1], node_txn[6]);
2220 assert_eq!(node_txn[2], commitment_tx[0]);
2221 check_spends!(node_txn[0], commitment_tx[0].clone());
2222 check_spends!(node_txn[1], commitment_tx[0].clone());
2223 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2224 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2225 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2226 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2227 assert_eq!(node_txn[0].lock_time, 0);
2228 assert_eq!(node_txn[1].lock_time, 0);
2230 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2231 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2232 let events = nodes[1].node.get_and_clear_pending_msg_events();
2234 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2235 assert_eq!(added_monitors.len(), 2);
2236 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2237 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2238 added_monitors.clear();
2240 assert_eq!(events.len(), 2);
2242 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2243 _ => panic!("Unexpected event"),
2246 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, .. } } => {
2247 assert!(update_add_htlcs.is_empty());
2248 assert!(update_fail_htlcs.is_empty());
2249 assert_eq!(update_fulfill_htlcs.len(), 1);
2250 assert!(update_fail_malformed_htlcs.is_empty());
2251 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2253 _ => panic!("Unexpected event"),
2255 macro_rules! check_tx_local_broadcast {
2256 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2257 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2258 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2259 assert_eq!(node_txn.len(), 7);
2260 assert_eq!(node_txn[0], node_txn[5]);
2261 assert_eq!(node_txn[1], node_txn[6]);
2262 check_spends!(node_txn[0], $commitment_tx.clone());
2263 check_spends!(node_txn[1], $commitment_tx.clone());
2264 assert_ne!(node_txn[0].lock_time, 0);
2265 assert_ne!(node_txn[1].lock_time, 0);
2267 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2268 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2269 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2270 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2272 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2273 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2274 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2275 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2277 check_spends!(node_txn[2], $chan_tx.clone());
2278 check_spends!(node_txn[3], node_txn[2].clone());
2279 check_spends!(node_txn[4], node_txn[2].clone());
2280 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2281 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2282 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2283 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2284 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2285 assert_ne!(node_txn[3].lock_time, 0);
2286 assert_ne!(node_txn[4].lock_time, 0);
2290 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2291 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2292 // timeout-claim of the output that nodes[2] just claimed via success.
2293 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2295 // Broadcast legit commitment tx from A on B's chain
2296 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2297 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2298 check_spends!(commitment_tx[0], chan_1.3.clone());
2299 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2300 check_closed_broadcast!(nodes[1], false);
2301 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + 2*HTLC-Success), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2302 assert_eq!(node_txn.len(), 5);
2303 assert_eq!(node_txn[0], node_txn[4]);
2304 check_spends!(node_txn[0], commitment_tx[0].clone());
2305 assert_eq!(node_txn[0].input.len(), 2);
2306 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2307 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2308 assert_eq!(node_txn[0].lock_time, 0);
2309 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2310 check_spends!(node_txn[1], chan_1.3.clone());
2311 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2312 check_spends!(node_txn[2], node_txn[1]);
2313 check_spends!(node_txn[3], node_txn[1]);
2314 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2315 // we already checked the same situation with A.
2317 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2318 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2319 check_closed_broadcast!(nodes[0], false);
2320 let events = nodes[0].node.get_and_clear_pending_events();
2321 assert_eq!(events.len(), 2);
2322 let mut first_claimed = false;
2323 for event in events {
2325 Event::PaymentSent { payment_preimage } => {
2326 if payment_preimage == our_payment_preimage {
2327 assert!(!first_claimed);
2328 first_claimed = true;
2330 assert_eq!(payment_preimage, our_payment_preimage_2);
2333 _ => panic!("Unexpected event"),
2336 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2340 fn test_htlc_on_chain_timeout() {
2341 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2342 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2343 // broadcasting the right event to other nodes in payment path.
2344 // A ------------------> B ----------------------> C (timeout)
2345 // B's commitment tx C's commitment tx
2347 // B's HTLC timeout tx B's timeout tx
2349 let nodes = create_network(3, &[None, None, None]);
2351 // Create some intial channels
2352 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2353 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2355 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2356 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2357 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2359 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2360 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2362 // Broadcast legit commitment tx from C on B's chain
2363 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2364 check_spends!(commitment_tx[0], chan_2.3.clone());
2365 nodes[2].node.fail_htlc_backwards(&payment_hash);
2366 check_added_monitors!(nodes[2], 0);
2367 expect_pending_htlcs_forwardable!(nodes[2]);
2368 check_added_monitors!(nodes[2], 1);
2370 let events = nodes[2].node.get_and_clear_pending_msg_events();
2371 assert_eq!(events.len(), 1);
2373 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, .. } } => {
2374 assert!(update_add_htlcs.is_empty());
2375 assert!(!update_fail_htlcs.is_empty());
2376 assert!(update_fulfill_htlcs.is_empty());
2377 assert!(update_fail_malformed_htlcs.is_empty());
2378 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2380 _ => panic!("Unexpected event"),
2382 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2383 check_closed_broadcast!(nodes[2], false);
2384 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2385 assert_eq!(node_txn.len(), 1);
2386 check_spends!(node_txn[0], chan_2.3.clone());
2387 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2389 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2390 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2391 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2394 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2395 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
2396 assert_eq!(node_txn[0], node_txn[5]);
2397 assert_eq!(node_txn[1], node_txn[6]);
2398 assert_eq!(node_txn[2], node_txn[7]);
2399 check_spends!(node_txn[0], commitment_tx[0].clone());
2400 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2401 check_spends!(node_txn[1], chan_2.3.clone());
2402 check_spends!(node_txn[2], node_txn[1].clone());
2403 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2404 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2405 check_spends!(node_txn[3], chan_2.3.clone());
2406 check_spends!(node_txn[4], node_txn[3].clone());
2407 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2408 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2409 timeout_tx = node_txn[0].clone();
2413 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2414 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2415 check_added_monitors!(nodes[1], 0);
2416 check_closed_broadcast!(nodes[1], false);
2418 expect_pending_htlcs_forwardable!(nodes[1]);
2419 check_added_monitors!(nodes[1], 1);
2420 let events = nodes[1].node.get_and_clear_pending_msg_events();
2421 assert_eq!(events.len(), 1);
2423 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, .. } } => {
2424 assert!(update_add_htlcs.is_empty());
2425 assert!(!update_fail_htlcs.is_empty());
2426 assert!(update_fulfill_htlcs.is_empty());
2427 assert!(update_fail_malformed_htlcs.is_empty());
2428 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2430 _ => panic!("Unexpected event"),
2432 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
2433 assert_eq!(node_txn.len(), 0);
2435 // Broadcast legit commitment tx from B on A's chain
2436 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2437 check_spends!(commitment_tx[0], chan_1.3.clone());
2439 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2440 check_closed_broadcast!(nodes[0], false);
2441 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
2442 assert_eq!(node_txn.len(), 4);
2443 assert_eq!(node_txn[0], node_txn[3]);
2444 check_spends!(node_txn[0], commitment_tx[0].clone());
2445 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2446 check_spends!(node_txn[1], chan_1.3.clone());
2447 check_spends!(node_txn[2], node_txn[1].clone());
2448 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2449 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2453 fn test_simple_commitment_revoked_fail_backward() {
2454 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2455 // and fail backward accordingly.
2457 let nodes = create_network(3, &[None, None, None]);
2459 // Create some initial channels
2460 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2461 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2463 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2464 // Get the will-be-revoked local txn from nodes[2]
2465 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2466 // Revoke the old state
2467 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2469 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2471 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2472 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2473 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2474 check_added_monitors!(nodes[1], 0);
2475 check_closed_broadcast!(nodes[1], false);
2477 expect_pending_htlcs_forwardable!(nodes[1]);
2478 check_added_monitors!(nodes[1], 1);
2479 let events = nodes[1].node.get_and_clear_pending_msg_events();
2480 assert_eq!(events.len(), 1);
2482 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, .. } } => {
2483 assert!(update_add_htlcs.is_empty());
2484 assert_eq!(update_fail_htlcs.len(), 1);
2485 assert!(update_fulfill_htlcs.is_empty());
2486 assert!(update_fail_malformed_htlcs.is_empty());
2487 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2489 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2490 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2492 let events = nodes[0].node.get_and_clear_pending_msg_events();
2493 assert_eq!(events.len(), 1);
2495 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2496 _ => panic!("Unexpected event"),
2498 let events = nodes[0].node.get_and_clear_pending_events();
2499 assert_eq!(events.len(), 1);
2501 Event::PaymentFailed { .. } => {},
2502 _ => panic!("Unexpected event"),
2505 _ => panic!("Unexpected event"),
2509 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2510 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2511 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2512 // commitment transaction anymore.
2513 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2514 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2515 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2516 // technically disallowed and we should probably handle it reasonably.
2517 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2518 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2520 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2521 // commitment_signed (implying it will be in the latest remote commitment transaction).
2522 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2523 // and once they revoke the previous commitment transaction (allowing us to send a new
2524 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2525 let mut nodes = create_network(3, &[None, None, None]);
2527 // Create some initial channels
2528 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2529 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2531 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2532 // Get the will-be-revoked local txn from nodes[2]
2533 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2534 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2535 // Revoke the old state
2536 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2538 let value = if use_dust {
2539 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2540 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2541 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2544 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2545 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2546 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2548 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2549 expect_pending_htlcs_forwardable!(nodes[2]);
2550 check_added_monitors!(nodes[2], 1);
2551 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2552 assert!(updates.update_add_htlcs.is_empty());
2553 assert!(updates.update_fulfill_htlcs.is_empty());
2554 assert!(updates.update_fail_malformed_htlcs.is_empty());
2555 assert_eq!(updates.update_fail_htlcs.len(), 1);
2556 assert!(updates.update_fee.is_none());
2557 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2558 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2559 // Drop the last RAA from 3 -> 2
2561 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2562 expect_pending_htlcs_forwardable!(nodes[2]);
2563 check_added_monitors!(nodes[2], 1);
2564 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2565 assert!(updates.update_add_htlcs.is_empty());
2566 assert!(updates.update_fulfill_htlcs.is_empty());
2567 assert!(updates.update_fail_malformed_htlcs.is_empty());
2568 assert_eq!(updates.update_fail_htlcs.len(), 1);
2569 assert!(updates.update_fee.is_none());
2570 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2571 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2572 check_added_monitors!(nodes[1], 1);
2573 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2574 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2575 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2576 check_added_monitors!(nodes[2], 1);
2578 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2579 expect_pending_htlcs_forwardable!(nodes[2]);
2580 check_added_monitors!(nodes[2], 1);
2581 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2582 assert!(updates.update_add_htlcs.is_empty());
2583 assert!(updates.update_fulfill_htlcs.is_empty());
2584 assert!(updates.update_fail_malformed_htlcs.is_empty());
2585 assert_eq!(updates.update_fail_htlcs.len(), 1);
2586 assert!(updates.update_fee.is_none());
2587 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2588 // At this point first_payment_hash has dropped out of the latest two commitment
2589 // transactions that nodes[1] is tracking...
2590 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2591 check_added_monitors!(nodes[1], 1);
2592 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2593 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2594 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2595 check_added_monitors!(nodes[2], 1);
2597 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2598 // on nodes[2]'s RAA.
2599 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2600 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2601 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2602 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2603 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2604 check_added_monitors!(nodes[1], 0);
2607 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2608 // One monitor for the new revocation preimage, no second on as we won't generate a new
2609 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2610 check_added_monitors!(nodes[1], 1);
2611 let events = nodes[1].node.get_and_clear_pending_events();
2612 assert_eq!(events.len(), 1);
2614 Event::PendingHTLCsForwardable { .. } => { },
2615 _ => panic!("Unexpected event"),
2617 // Deliberately don't process the pending fail-back so they all fail back at once after
2618 // block connection just like the !deliver_bs_raa case
2621 let mut failed_htlcs = HashSet::new();
2622 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2624 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2625 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2626 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2628 let events = nodes[1].node.get_and_clear_pending_events();
2629 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2631 Event::PaymentFailed { ref payment_hash, .. } => {
2632 assert_eq!(*payment_hash, fourth_payment_hash);
2634 _ => panic!("Unexpected event"),
2636 if !deliver_bs_raa {
2638 Event::PendingHTLCsForwardable { .. } => { },
2639 _ => panic!("Unexpected event"),
2642 nodes[1].node.process_pending_htlc_forwards();
2643 check_added_monitors!(nodes[1], 1);
2645 let events = nodes[1].node.get_and_clear_pending_msg_events();
2646 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2647 match events[if deliver_bs_raa { 1 } else { 0 }] {
2648 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2649 _ => panic!("Unexpected event"),
2653 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, .. } } => {
2654 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2655 assert_eq!(update_add_htlcs.len(), 1);
2656 assert!(update_fulfill_htlcs.is_empty());
2657 assert!(update_fail_htlcs.is_empty());
2658 assert!(update_fail_malformed_htlcs.is_empty());
2660 _ => panic!("Unexpected event"),
2663 match events[if deliver_bs_raa { 2 } else { 1 }] {
2664 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, .. } } => {
2665 assert!(update_add_htlcs.is_empty());
2666 assert_eq!(update_fail_htlcs.len(), 3);
2667 assert!(update_fulfill_htlcs.is_empty());
2668 assert!(update_fail_malformed_htlcs.is_empty());
2669 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2671 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2672 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2673 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2675 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2677 let events = nodes[0].node.get_and_clear_pending_msg_events();
2678 // If we delivered B's RAA we got an unknown preimage error, not something
2679 // that we should update our routing table for.
2680 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2681 for event in events {
2683 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2684 _ => panic!("Unexpected event"),
2687 let events = nodes[0].node.get_and_clear_pending_events();
2688 assert_eq!(events.len(), 3);
2690 Event::PaymentFailed { ref payment_hash, .. } => {
2691 assert!(failed_htlcs.insert(payment_hash.0));
2693 _ => panic!("Unexpected event"),
2696 Event::PaymentFailed { ref payment_hash, .. } => {
2697 assert!(failed_htlcs.insert(payment_hash.0));
2699 _ => panic!("Unexpected event"),
2702 Event::PaymentFailed { ref payment_hash, .. } => {
2703 assert!(failed_htlcs.insert(payment_hash.0));
2705 _ => panic!("Unexpected event"),
2708 _ => panic!("Unexpected event"),
2711 assert!(failed_htlcs.contains(&first_payment_hash.0));
2712 assert!(failed_htlcs.contains(&second_payment_hash.0));
2713 assert!(failed_htlcs.contains(&third_payment_hash.0));
2717 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2718 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2719 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2720 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2721 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2725 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2726 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2727 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2728 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2729 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2733 fn test_htlc_ignore_latest_remote_commitment() {
2734 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2735 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2736 let nodes = create_network(2, &[None, None]);
2737 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2739 route_payment(&nodes[0], &[&nodes[1]], 10000000);
2740 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
2741 check_closed_broadcast!(nodes[0], false);
2743 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2744 assert_eq!(node_txn.len(), 2);
2746 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2747 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
2748 check_closed_broadcast!(nodes[1], false);
2750 // Duplicate the block_connected call since this may happen due to other listeners
2751 // registering new transactions
2752 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
2756 fn test_force_close_fail_back() {
2757 // Check which HTLCs are failed-backwards on channel force-closure
2758 let mut nodes = create_network(3, &[None, None, None]);
2759 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2760 create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2762 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
2764 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2766 let mut payment_event = {
2767 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
2768 check_added_monitors!(nodes[0], 1);
2770 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2771 assert_eq!(events.len(), 1);
2772 SendEvent::from_event(events.remove(0))
2775 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2776 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2778 expect_pending_htlcs_forwardable!(nodes[1]);
2780 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2781 assert_eq!(events_2.len(), 1);
2782 payment_event = SendEvent::from_event(events_2.remove(0));
2783 assert_eq!(payment_event.msgs.len(), 1);
2785 check_added_monitors!(nodes[1], 1);
2786 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
2787 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
2788 check_added_monitors!(nodes[2], 1);
2789 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2791 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
2792 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
2793 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
2795 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
2796 check_closed_broadcast!(nodes[2], false);
2798 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2799 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
2800 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
2801 // back to nodes[1] upon timeout otherwise.
2802 assert_eq!(node_txn.len(), 1);
2806 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2807 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
2809 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
2810 check_closed_broadcast!(nodes[1], false);
2812 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
2814 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
2815 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
2816 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
2818 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
2819 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2820 assert_eq!(node_txn.len(), 1);
2821 assert_eq!(node_txn[0].input.len(), 1);
2822 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
2823 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
2824 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
2826 check_spends!(node_txn[0], tx);
2830 fn test_unconf_chan() {
2831 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
2832 let nodes = create_network(2, &[None, None]);
2833 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2835 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2836 assert_eq!(channel_state.by_id.len(), 1);
2837 assert_eq!(channel_state.short_to_id.len(), 1);
2838 mem::drop(channel_state);
2840 let mut headers = Vec::new();
2841 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2842 headers.push(header.clone());
2844 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2845 headers.push(header.clone());
2847 let mut height = 99;
2848 while !headers.is_empty() {
2849 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
2852 check_closed_broadcast!(nodes[0], false);
2853 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2854 assert_eq!(channel_state.by_id.len(), 0);
2855 assert_eq!(channel_state.short_to_id.len(), 0);
2859 fn test_simple_peer_disconnect() {
2860 // Test that we can reconnect when there are no lost messages
2861 let nodes = create_network(3, &[None, None, None]);
2862 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2863 create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2865 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2866 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2867 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2869 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2870 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2871 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
2872 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
2874 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2875 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2876 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2878 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2879 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2880 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2881 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2883 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2884 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2886 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
2887 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
2889 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
2891 let events = nodes[0].node.get_and_clear_pending_events();
2892 assert_eq!(events.len(), 2);
2894 Event::PaymentSent { payment_preimage } => {
2895 assert_eq!(payment_preimage, payment_preimage_3);
2897 _ => panic!("Unexpected event"),
2900 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
2901 assert_eq!(payment_hash, payment_hash_5);
2902 assert!(rejected_by_dest);
2904 _ => panic!("Unexpected event"),
2908 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
2909 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
2912 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
2913 // Test that we can reconnect when in-flight HTLC updates get dropped
2914 let mut nodes = create_network(2, &[None, None]);
2915 if messages_delivered == 0 {
2916 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2917 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
2919 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
2922 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();
2923 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
2925 let payment_event = {
2926 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
2927 check_added_monitors!(nodes[0], 1);
2929 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2930 assert_eq!(events.len(), 1);
2931 SendEvent::from_event(events.remove(0))
2933 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
2935 if messages_delivered < 2 {
2936 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
2938 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
2939 if messages_delivered >= 3 {
2940 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
2941 check_added_monitors!(nodes[1], 1);
2942 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2944 if messages_delivered >= 4 {
2945 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
2946 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2947 check_added_monitors!(nodes[0], 1);
2949 if messages_delivered >= 5 {
2950 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
2951 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2952 // No commitment_signed so get_event_msg's assert(len == 1) passes
2953 check_added_monitors!(nodes[0], 1);
2955 if messages_delivered >= 6 {
2956 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
2957 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2958 check_added_monitors!(nodes[1], 1);
2965 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2966 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2967 if messages_delivered < 3 {
2968 // Even if the funding_locked messages get exchanged, as long as nothing further was
2969 // received on either side, both sides will need to resend them.
2970 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
2971 } else if messages_delivered == 3 {
2972 // nodes[0] still wants its RAA + commitment_signed
2973 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
2974 } else if messages_delivered == 4 {
2975 // nodes[0] still wants its commitment_signed
2976 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
2977 } else if messages_delivered == 5 {
2978 // nodes[1] still wants its final RAA
2979 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
2980 } else if messages_delivered == 6 {
2981 // Everything was delivered...
2982 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2985 let events_1 = nodes[1].node.get_and_clear_pending_events();
2986 assert_eq!(events_1.len(), 1);
2988 Event::PendingHTLCsForwardable { .. } => { },
2989 _ => panic!("Unexpected event"),
2992 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2993 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2994 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2996 nodes[1].node.process_pending_htlc_forwards();
2998 let events_2 = nodes[1].node.get_and_clear_pending_events();
2999 assert_eq!(events_2.len(), 1);
3001 Event::PaymentReceived { ref payment_hash, amt } => {
3002 assert_eq!(payment_hash_1, *payment_hash);
3003 assert_eq!(amt, 1000000);
3005 _ => panic!("Unexpected event"),
3008 nodes[1].node.claim_funds(payment_preimage_1, 1_000_000);
3009 check_added_monitors!(nodes[1], 1);
3011 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3012 assert_eq!(events_3.len(), 1);
3013 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3014 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3015 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3016 assert!(updates.update_add_htlcs.is_empty());
3017 assert!(updates.update_fail_htlcs.is_empty());
3018 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3019 assert!(updates.update_fail_malformed_htlcs.is_empty());
3020 assert!(updates.update_fee.is_none());
3021 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3023 _ => panic!("Unexpected event"),
3026 if messages_delivered >= 1 {
3027 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3029 let events_4 = nodes[0].node.get_and_clear_pending_events();
3030 assert_eq!(events_4.len(), 1);
3032 Event::PaymentSent { ref payment_preimage } => {
3033 assert_eq!(payment_preimage_1, *payment_preimage);
3035 _ => panic!("Unexpected event"),
3038 if messages_delivered >= 2 {
3039 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3040 check_added_monitors!(nodes[0], 1);
3041 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3043 if messages_delivered >= 3 {
3044 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3045 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3046 check_added_monitors!(nodes[1], 1);
3048 if messages_delivered >= 4 {
3049 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3050 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3051 // No commitment_signed so get_event_msg's assert(len == 1) passes
3052 check_added_monitors!(nodes[1], 1);
3054 if messages_delivered >= 5 {
3055 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3056 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3057 check_added_monitors!(nodes[0], 1);
3064 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3065 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3066 if messages_delivered < 2 {
3067 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3068 //TODO: Deduplicate PaymentSent events, then enable this if:
3069 //if messages_delivered < 1 {
3070 let events_4 = nodes[0].node.get_and_clear_pending_events();
3071 assert_eq!(events_4.len(), 1);
3073 Event::PaymentSent { ref payment_preimage } => {
3074 assert_eq!(payment_preimage_1, *payment_preimage);
3076 _ => panic!("Unexpected event"),
3079 } else if messages_delivered == 2 {
3080 // nodes[0] still wants its RAA + commitment_signed
3081 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3082 } else if messages_delivered == 3 {
3083 // nodes[0] still wants its commitment_signed
3084 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3085 } else if messages_delivered == 4 {
3086 // nodes[1] still wants its final RAA
3087 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3088 } else if messages_delivered == 5 {
3089 // Everything was delivered...
3090 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3093 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3094 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3095 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3097 // Channel should still work fine...
3098 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3099 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3103 fn test_drop_messages_peer_disconnect_a() {
3104 do_test_drop_messages_peer_disconnect(0);
3105 do_test_drop_messages_peer_disconnect(1);
3106 do_test_drop_messages_peer_disconnect(2);
3107 do_test_drop_messages_peer_disconnect(3);
3111 fn test_drop_messages_peer_disconnect_b() {
3112 do_test_drop_messages_peer_disconnect(4);
3113 do_test_drop_messages_peer_disconnect(5);
3114 do_test_drop_messages_peer_disconnect(6);
3118 fn test_funding_peer_disconnect() {
3119 // Test that we can lock in our funding tx while disconnected
3120 let nodes = create_network(2, &[None, None]);
3121 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3123 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3124 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3126 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3127 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3128 assert_eq!(events_1.len(), 1);
3130 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3131 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3133 _ => panic!("Unexpected event"),
3136 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
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);
3141 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3142 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3143 assert_eq!(events_2.len(), 2);
3144 let funding_locked = match events_2[0] {
3145 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3146 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3149 _ => panic!("Unexpected event"),
3151 let bs_announcement_sigs = match events_2[1] {
3152 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3153 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3156 _ => panic!("Unexpected event"),
3159 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3161 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3162 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3163 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3164 assert_eq!(events_3.len(), 2);
3165 let as_announcement_sigs = match events_3[0] {
3166 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3167 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3170 _ => panic!("Unexpected event"),
3172 let (as_announcement, as_update) = match events_3[1] {
3173 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3174 (msg.clone(), update_msg.clone())
3176 _ => panic!("Unexpected event"),
3179 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3180 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3181 assert_eq!(events_4.len(), 1);
3182 let (_, bs_update) = match events_4[0] {
3183 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3184 (msg.clone(), update_msg.clone())
3186 _ => panic!("Unexpected event"),
3189 nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3190 nodes[0].router.handle_channel_update(&bs_update).unwrap();
3191 nodes[0].router.handle_channel_update(&as_update).unwrap();
3193 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3194 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3195 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3199 fn test_drop_messages_peer_disconnect_dual_htlc() {
3200 // Test that we can handle reconnecting when both sides of a channel have pending
3201 // commitment_updates when we disconnect.
3202 let mut nodes = create_network(2, &[None, None]);
3203 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3205 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3207 // Now try to send a second payment which will fail to send
3208 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3209 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3211 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3212 check_added_monitors!(nodes[0], 1);
3214 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3215 assert_eq!(events_1.len(), 1);
3217 MessageSendEvent::UpdateHTLCs { .. } => {},
3218 _ => panic!("Unexpected event"),
3221 assert!(nodes[1].node.claim_funds(payment_preimage_1, 1_000_000));
3222 check_added_monitors!(nodes[1], 1);
3224 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3225 assert_eq!(events_2.len(), 1);
3227 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 } } => {
3228 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3229 assert!(update_add_htlcs.is_empty());
3230 assert_eq!(update_fulfill_htlcs.len(), 1);
3231 assert!(update_fail_htlcs.is_empty());
3232 assert!(update_fail_malformed_htlcs.is_empty());
3233 assert!(update_fee.is_none());
3235 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3236 let events_3 = nodes[0].node.get_and_clear_pending_events();
3237 assert_eq!(events_3.len(), 1);
3239 Event::PaymentSent { ref payment_preimage } => {
3240 assert_eq!(*payment_preimage, payment_preimage_1);
3242 _ => panic!("Unexpected event"),
3245 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3246 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3247 // No commitment_signed so get_event_msg's assert(len == 1) passes
3248 check_added_monitors!(nodes[0], 1);
3250 _ => panic!("Unexpected event"),
3253 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3254 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3256 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3257 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3258 assert_eq!(reestablish_1.len(), 1);
3259 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3260 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3261 assert_eq!(reestablish_2.len(), 1);
3263 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3264 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3265 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3266 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3268 assert!(as_resp.0.is_none());
3269 assert!(bs_resp.0.is_none());
3271 assert!(bs_resp.1.is_none());
3272 assert!(bs_resp.2.is_none());
3274 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3276 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3277 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3278 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3279 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3280 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3281 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3282 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3283 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3284 // No commitment_signed so get_event_msg's assert(len == 1) passes
3285 check_added_monitors!(nodes[1], 1);
3287 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3288 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3289 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3290 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3291 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3292 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3293 assert!(bs_second_commitment_signed.update_fee.is_none());
3294 check_added_monitors!(nodes[1], 1);
3296 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3297 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3298 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3299 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3300 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3301 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3302 assert!(as_commitment_signed.update_fee.is_none());
3303 check_added_monitors!(nodes[0], 1);
3305 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3306 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3307 // No commitment_signed so get_event_msg's assert(len == 1) passes
3308 check_added_monitors!(nodes[0], 1);
3310 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3311 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3312 // No commitment_signed so get_event_msg's assert(len == 1) passes
3313 check_added_monitors!(nodes[1], 1);
3315 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3316 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3317 check_added_monitors!(nodes[1], 1);
3319 expect_pending_htlcs_forwardable!(nodes[1]);
3321 let events_5 = nodes[1].node.get_and_clear_pending_events();
3322 assert_eq!(events_5.len(), 1);
3324 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3325 assert_eq!(payment_hash_2, *payment_hash);
3327 _ => panic!("Unexpected event"),
3330 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3331 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3332 check_added_monitors!(nodes[0], 1);
3334 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3338 fn test_invalid_channel_announcement() {
3339 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3340 let secp_ctx = Secp256k1::new();
3341 let nodes = create_network(2, &[None, None]);
3343 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3345 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3346 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3347 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3348 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3350 nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3352 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().inner.funding_key);
3353 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().inner.funding_key);
3355 let as_network_key = nodes[0].node.get_our_node_id();
3356 let bs_network_key = nodes[1].node.get_our_node_id();
3358 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3360 let mut chan_announcement;
3362 macro_rules! dummy_unsigned_msg {
3364 msgs::UnsignedChannelAnnouncement {
3365 features: msgs::Features::<FeatureContextChannel>::new(),
3366 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3367 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3368 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3369 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3370 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3371 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3372 excess_data: Vec::new(),
3377 macro_rules! sign_msg {
3378 ($unsigned_msg: expr) => {
3379 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3380 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key);
3381 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key);
3382 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3383 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3384 chan_announcement = msgs::ChannelAnnouncement {
3385 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3386 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3387 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3388 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3389 contents: $unsigned_msg
3394 let unsigned_msg = dummy_unsigned_msg!();
3395 sign_msg!(unsigned_msg);
3396 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3397 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 } );
3399 // Configured with Network::Testnet
3400 let mut unsigned_msg = dummy_unsigned_msg!();
3401 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3402 sign_msg!(unsigned_msg);
3403 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3405 let mut unsigned_msg = dummy_unsigned_msg!();
3406 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3407 sign_msg!(unsigned_msg);
3408 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3412 fn test_no_txn_manager_serialize_deserialize() {
3413 let mut nodes = create_network(2, &[None, None]);
3415 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3417 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3419 let nodes_0_serialized = nodes[0].node.encode();
3420 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3421 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3423 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3424 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3425 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3426 assert!(chan_0_monitor_read.is_empty());
3428 let mut nodes_0_read = &nodes_0_serialized[..];
3429 let config = UserConfig::default();
3430 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3431 let (_, nodes_0_deserialized) = {
3432 let mut channel_monitors = HashMap::new();
3433 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3434 <(Sha256dHash, ChannelManager<EnforcingChannelKeys>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3435 default_config: config,
3437 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3438 monitor: nodes[0].chan_monitor.clone(),
3439 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3440 logger: Arc::new(test_utils::TestLogger::new()),
3441 channel_monitors: &mut channel_monitors,
3444 assert!(nodes_0_read.is_empty());
3446 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3447 nodes[0].node = Arc::new(nodes_0_deserialized);
3448 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3449 nodes[0].block_notifier.register_listener(Arc::downgrade(&nodes_0_as_listener));
3450 assert_eq!(nodes[0].node.list_channels().len(), 1);
3451 check_added_monitors!(nodes[0], 1);
3453 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3454 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3455 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3456 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3458 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3459 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3460 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3461 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3463 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3464 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3465 for node in nodes.iter() {
3466 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3467 node.router.handle_channel_update(&as_update).unwrap();
3468 node.router.handle_channel_update(&bs_update).unwrap();
3471 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3475 fn test_simple_manager_serialize_deserialize() {
3476 let mut nodes = create_network(2, &[None, None]);
3477 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3479 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3480 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3482 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3484 let nodes_0_serialized = nodes[0].node.encode();
3485 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3486 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3488 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3489 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3490 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3491 assert!(chan_0_monitor_read.is_empty());
3493 let mut nodes_0_read = &nodes_0_serialized[..];
3494 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3495 let (_, nodes_0_deserialized) = {
3496 let mut channel_monitors = HashMap::new();
3497 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3498 <(Sha256dHash, ChannelManager<EnforcingChannelKeys>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3499 default_config: UserConfig::default(),
3501 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3502 monitor: nodes[0].chan_monitor.clone(),
3503 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3504 logger: Arc::new(test_utils::TestLogger::new()),
3505 channel_monitors: &mut channel_monitors,
3508 assert!(nodes_0_read.is_empty());
3510 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3511 nodes[0].node = Arc::new(nodes_0_deserialized);
3512 check_added_monitors!(nodes[0], 1);
3514 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3516 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3517 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3521 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3522 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3523 let mut nodes = create_network(4, &[None, None, None, None]);
3524 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3525 create_announced_chan_between_nodes(&nodes, 2, 0, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3526 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3528 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3530 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3531 let nodes_0_serialized = nodes[0].node.encode();
3533 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3534 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3535 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3536 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3538 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3540 let mut node_0_monitors_serialized = Vec::new();
3541 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3542 let mut writer = test_utils::TestVecWriter(Vec::new());
3543 monitor.1.write_for_disk(&mut writer).unwrap();
3544 node_0_monitors_serialized.push(writer.0);
3547 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3548 let mut node_0_monitors = Vec::new();
3549 for serialized in node_0_monitors_serialized.iter() {
3550 let mut read = &serialized[..];
3551 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3552 assert!(read.is_empty());
3553 node_0_monitors.push(monitor);
3556 let mut nodes_0_read = &nodes_0_serialized[..];
3557 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3558 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager<EnforcingChannelKeys>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3559 default_config: UserConfig::default(),
3561 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3562 monitor: nodes[0].chan_monitor.clone(),
3563 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3564 logger: Arc::new(test_utils::TestLogger::new()),
3565 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3567 assert!(nodes_0_read.is_empty());
3569 { // Channel close should result in a commitment tx and an HTLC tx
3570 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3571 assert_eq!(txn.len(), 2);
3572 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3573 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3576 for monitor in node_0_monitors.drain(..) {
3577 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3578 check_added_monitors!(nodes[0], 1);
3580 nodes[0].node = Arc::new(nodes_0_deserialized);
3582 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3583 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3584 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3585 //... and we can even still claim the payment!
3586 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3588 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
3589 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3590 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
3591 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
3592 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3593 assert_eq!(msg_events.len(), 1);
3594 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
3596 &ErrorAction::SendErrorMessage { ref msg } => {
3597 assert_eq!(msg.channel_id, channel_id);
3599 _ => panic!("Unexpected event!"),
3604 macro_rules! check_spendable_outputs {
3605 ($node: expr, $der_idx: expr) => {
3607 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3608 let mut txn = Vec::new();
3609 for event in events {
3611 Event::SpendableOutputs { ref outputs } => {
3612 for outp in outputs {
3614 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3616 previous_output: outpoint.clone(),
3617 script_sig: Script::new(),
3619 witness: Vec::new(),
3622 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3623 value: output.value,
3625 let mut spend_tx = Transaction {
3631 let secp_ctx = Secp256k1::new();
3632 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3633 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3634 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3635 let remotesig = secp_ctx.sign(&sighash, key);
3636 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3637 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3638 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3641 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3643 previous_output: outpoint.clone(),
3644 script_sig: Script::new(),
3645 sequence: *to_self_delay as u32,
3646 witness: Vec::new(),
3649 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3650 value: output.value,
3652 let mut spend_tx = Transaction {
3658 let secp_ctx = Secp256k1::new();
3659 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3660 let local_delaysig = secp_ctx.sign(&sighash, key);
3661 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3662 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3663 spend_tx.input[0].witness.push(vec!(0));
3664 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3667 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3668 let secp_ctx = Secp256k1::new();
3670 previous_output: outpoint.clone(),
3671 script_sig: Script::new(),
3673 witness: Vec::new(),
3676 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3677 value: output.value,
3679 let mut spend_tx = Transaction {
3683 output: vec![outp.clone()],
3686 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
3688 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
3690 Err(_) => panic!("Your RNG is busted"),
3693 Err(_) => panic!("Your rng is busted"),
3696 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
3697 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
3698 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3699 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
3700 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
3701 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3702 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
3708 _ => panic!("Unexpected event"),
3717 fn test_claim_sizeable_push_msat() {
3718 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
3719 let nodes = create_network(2, &[None, None]);
3721 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3722 nodes[1].node.force_close_channel(&chan.2);
3723 check_closed_broadcast!(nodes[1], false);
3724 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3725 assert_eq!(node_txn.len(), 1);
3726 check_spends!(node_txn[0], chan.3.clone());
3727 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
3729 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3730 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3731 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3732 assert_eq!(spend_txn.len(), 1);
3733 check_spends!(spend_txn[0], node_txn[0].clone());
3737 fn test_claim_on_remote_sizeable_push_msat() {
3738 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3739 // to_remote output is encumbered by a P2WPKH
3740 let nodes = create_network(2, &[None, None]);
3742 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3743 nodes[0].node.force_close_channel(&chan.2);
3744 check_closed_broadcast!(nodes[0], false);
3746 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3747 assert_eq!(node_txn.len(), 1);
3748 check_spends!(node_txn[0], chan.3.clone());
3749 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
3751 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3752 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3753 check_closed_broadcast!(nodes[1], false);
3754 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3755 assert_eq!(spend_txn.len(), 2);
3756 assert_eq!(spend_txn[0], spend_txn[1]);
3757 check_spends!(spend_txn[0], node_txn[0].clone());
3761 fn test_claim_on_remote_revoked_sizeable_push_msat() {
3762 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3763 // to_remote output is encumbered by a P2WPKH
3765 let nodes = create_network(2, &[None, None]);
3767 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3768 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3769 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
3770 assert_eq!(revoked_local_txn[0].input.len(), 1);
3771 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
3773 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3774 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3775 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3776 check_closed_broadcast!(nodes[1], false);
3778 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3779 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3780 assert_eq!(spend_txn.len(), 4);
3781 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
3782 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
3783 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
3784 check_spends!(spend_txn[1], node_txn[0].clone());
3788 fn test_static_spendable_outputs_preimage_tx() {
3789 let nodes = create_network(2, &[None, None]);
3791 // Create some initial channels
3792 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3794 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3796 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
3797 assert_eq!(commitment_tx[0].input.len(), 1);
3798 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
3800 // Settle A's commitment tx on B's chain
3801 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3802 assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000));
3803 check_added_monitors!(nodes[1], 1);
3804 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
3805 let events = nodes[1].node.get_and_clear_pending_msg_events();
3807 MessageSendEvent::UpdateHTLCs { .. } => {},
3808 _ => panic!("Unexpected event"),
3811 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3812 _ => panic!("Unexepected event"),
3815 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
3816 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: 2 (1 preimage tx)
3817 assert_eq!(node_txn.len(), 4);
3818 check_spends!(node_txn[0], commitment_tx[0].clone());
3819 assert_eq!(node_txn[0], node_txn[3]);
3820 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3821 eprintln!("{:?}", node_txn[1]);
3822 check_spends!(node_txn[1], chan_1.3.clone());
3823 check_spends!(node_txn[2], node_txn[1]);
3825 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
3826 assert_eq!(spend_txn.len(), 2);
3827 assert_eq!(spend_txn[0], spend_txn[1]);
3828 check_spends!(spend_txn[0], node_txn[0].clone());
3832 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
3833 let nodes = create_network(2, &[None, None]);
3835 // Create some initial channels
3836 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3838 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3839 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter_mut().next().unwrap().1.channel_monitor().get_latest_local_commitment_txn();
3840 assert_eq!(revoked_local_txn[0].input.len(), 1);
3841 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3843 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3845 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3846 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3847 check_closed_broadcast!(nodes[1], false);
3849 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3850 assert_eq!(node_txn.len(), 3);
3851 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
3852 assert_eq!(node_txn[0].input.len(), 2);
3853 check_spends!(node_txn[0], revoked_local_txn[0].clone());
3855 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3856 assert_eq!(spend_txn.len(), 2);
3857 assert_eq!(spend_txn[0], spend_txn[1]);
3858 check_spends!(spend_txn[0], node_txn[0].clone());
3862 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
3863 let nodes = create_network(2, &[None, None]);
3865 // Create some initial channels
3866 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3868 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3869 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
3870 assert_eq!(revoked_local_txn[0].input.len(), 1);
3871 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3873 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3875 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3876 // A will generate HTLC-Timeout from revoked commitment tx
3877 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3878 check_closed_broadcast!(nodes[0], false);
3880 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3881 assert_eq!(revoked_htlc_txn.len(), 3);
3882 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3883 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3884 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3885 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3886 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
3888 // B will generate justice tx from A's revoked commitment/HTLC tx
3889 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3890 check_closed_broadcast!(nodes[1], false);
3892 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3893 assert_eq!(node_txn.len(), 5);
3894 assert_eq!(node_txn[3].input.len(), 1);
3895 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3897 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
3898 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3899 assert_eq!(spend_txn.len(), 3);
3900 assert_eq!(spend_txn[0], spend_txn[1]);
3901 check_spends!(spend_txn[0], node_txn[0].clone());
3902 check_spends!(spend_txn[2], node_txn[3].clone());
3906 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
3907 let nodes = create_network(2, &[None, None]);
3909 // Create some initial channels
3910 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3912 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3913 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
3914 assert_eq!(revoked_local_txn[0].input.len(), 1);
3915 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3917 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3919 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3920 // B will generate HTLC-Success from revoked commitment tx
3921 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3922 check_closed_broadcast!(nodes[1], false);
3923 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3925 assert_eq!(revoked_htlc_txn.len(), 3);
3926 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3927 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3928 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3929 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3931 // A will generate justice tx from B's revoked commitment/HTLC tx
3932 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3933 check_closed_broadcast!(nodes[0], false);
3935 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3936 assert_eq!(node_txn.len(), 4);
3937 assert_eq!(node_txn[3].input.len(), 1);
3938 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3940 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
3941 let spend_txn = check_spendable_outputs!(nodes[0], 1);
3942 assert_eq!(spend_txn.len(), 5);
3943 assert_eq!(spend_txn[0], spend_txn[2]);
3944 assert_eq!(spend_txn[1], spend_txn[3]);
3945 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
3946 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
3947 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
3951 fn test_onchain_to_onchain_claim() {
3952 // Test that in case of channel closure, we detect the state of output thanks to
3953 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
3954 // First, have C claim an HTLC against its own latest commitment transaction.
3955 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
3957 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
3960 let nodes = create_network(3, &[None, None, None]);
3962 // Create some initial channels
3963 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3964 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
3966 // Rebalance the network a bit by relaying one payment through all the channels ...
3967 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
3968 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
3970 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3971 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3972 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
3973 check_spends!(commitment_tx[0], chan_2.3.clone());
3974 nodes[2].node.claim_funds(payment_preimage, 3_000_000);
3975 check_added_monitors!(nodes[2], 1);
3976 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3977 assert!(updates.update_add_htlcs.is_empty());
3978 assert!(updates.update_fail_htlcs.is_empty());
3979 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3980 assert!(updates.update_fail_malformed_htlcs.is_empty());
3982 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3983 check_closed_broadcast!(nodes[2], false);
3985 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
3986 assert_eq!(c_txn.len(), 4);
3987 assert_eq!(c_txn[0], c_txn[2]);
3988 assert_eq!(c_txn[0], c_txn[3]);
3989 assert_eq!(commitment_tx[0], c_txn[1]);
3990 check_spends!(c_txn[1], chan_2.3.clone());
3991 check_spends!(c_txn[2], c_txn[1].clone());
3992 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
3993 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3994 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3995 assert_eq!(c_txn[0].lock_time, 0); // Success tx
3997 // 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
3998 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4000 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4001 assert_eq!(b_txn.len(), 4);
4002 assert_eq!(b_txn[0], b_txn[3]);
4003 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4004 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4005 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4006 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4007 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4008 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4009 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4010 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4011 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4014 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4015 check_added_monitors!(nodes[1], 1);
4016 match msg_events[0] {
4017 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4018 _ => panic!("Unexpected event"),
4020 match msg_events[1] {
4021 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, .. } } => {
4022 assert!(update_add_htlcs.is_empty());
4023 assert!(update_fail_htlcs.is_empty());
4024 assert_eq!(update_fulfill_htlcs.len(), 1);
4025 assert!(update_fail_malformed_htlcs.is_empty());
4026 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4028 _ => panic!("Unexpected event"),
4030 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4031 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4032 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4033 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4034 assert_eq!(b_txn.len(), 4);
4035 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
4036 check_spends!(b_txn[2], b_txn[1]); // HTLC-Success tx, as a part of the local txn rebroadcast by ChannelManager in the force close
4037 assert_eq!(b_txn[0], b_txn[3]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
4038 check_spends!(b_txn[0], commitment_tx[0].clone());
4039 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4040 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4041 assert_eq!(b_txn[2].lock_time, 0); // Success tx
4043 check_closed_broadcast!(nodes[1], false);
4047 fn test_duplicate_payment_hash_one_failure_one_success() {
4048 // Topology : A --> B --> C
4049 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4050 let mut nodes = create_network(3, &[None, None, None]);
4052 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4053 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4055 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4056 *nodes[0].network_payment_count.borrow_mut() -= 1;
4057 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4059 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4060 assert_eq!(commitment_txn[0].input.len(), 1);
4061 check_spends!(commitment_txn[0], chan_2.3.clone());
4063 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4064 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4065 check_closed_broadcast!(nodes[1], false);
4067 let htlc_timeout_tx;
4068 { // Extract one of the two HTLC-Timeout transaction
4069 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4070 assert_eq!(node_txn.len(), 7);
4071 assert_eq!(node_txn[0], node_txn[5]);
4072 assert_eq!(node_txn[1], node_txn[6]);
4073 check_spends!(node_txn[0], commitment_txn[0].clone());
4074 assert_eq!(node_txn[0].input.len(), 1);
4075 check_spends!(node_txn[1], commitment_txn[0].clone());
4076 assert_eq!(node_txn[1].input.len(), 1);
4077 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4078 check_spends!(node_txn[2], chan_2.3.clone());
4079 check_spends!(node_txn[3], node_txn[2].clone());
4080 check_spends!(node_txn[4], node_txn[2].clone());
4081 htlc_timeout_tx = node_txn[1].clone();
4084 nodes[2].node.claim_funds(our_payment_preimage, 900_000);
4085 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4086 check_added_monitors!(nodes[2], 2);
4087 let events = nodes[2].node.get_and_clear_pending_msg_events();
4089 MessageSendEvent::UpdateHTLCs { .. } => {},
4090 _ => panic!("Unexpected event"),
4093 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4094 _ => panic!("Unexepected event"),
4096 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4097 assert_eq!(htlc_success_txn.len(), 7);
4098 check_spends!(htlc_success_txn[2], chan_2.3.clone());
4099 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4100 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4101 assert_eq!(htlc_success_txn[0], htlc_success_txn[5]);
4102 assert_eq!(htlc_success_txn[0].input.len(), 1);
4103 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4104 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4105 assert_eq!(htlc_success_txn[1].input.len(), 1);
4106 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4107 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4108 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
4109 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
4111 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4112 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4113 expect_pending_htlcs_forwardable!(nodes[1]);
4114 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4115 assert!(htlc_updates.update_add_htlcs.is_empty());
4116 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4117 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4118 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4119 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4120 check_added_monitors!(nodes[1], 1);
4122 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4123 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4125 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4126 let events = nodes[0].node.get_and_clear_pending_msg_events();
4127 assert_eq!(events.len(), 1);
4129 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4131 _ => { panic!("Unexpected event"); }
4134 let events = nodes[0].node.get_and_clear_pending_events();
4136 Event::PaymentFailed { ref payment_hash, .. } => {
4137 assert_eq!(*payment_hash, duplicate_payment_hash);
4139 _ => panic!("Unexpected event"),
4142 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4143 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4144 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4145 assert!(updates.update_add_htlcs.is_empty());
4146 assert!(updates.update_fail_htlcs.is_empty());
4147 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4148 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4149 assert!(updates.update_fail_malformed_htlcs.is_empty());
4150 check_added_monitors!(nodes[1], 1);
4152 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4153 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4155 let events = nodes[0].node.get_and_clear_pending_events();
4157 Event::PaymentSent { ref payment_preimage } => {
4158 assert_eq!(*payment_preimage, our_payment_preimage);
4160 _ => panic!("Unexpected event"),
4165 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4166 let nodes = create_network(2, &[None, None]);
4168 // Create some initial channels
4169 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4171 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4172 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4173 assert_eq!(local_txn[0].input.len(), 1);
4174 check_spends!(local_txn[0], chan_1.3.clone());
4176 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4177 nodes[1].node.claim_funds(payment_preimage, 9_000_000);
4178 check_added_monitors!(nodes[1], 1);
4179 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4180 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4181 let events = nodes[1].node.get_and_clear_pending_msg_events();
4183 MessageSendEvent::UpdateHTLCs { .. } => {},
4184 _ => panic!("Unexpected event"),
4187 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4188 _ => panic!("Unexepected event"),
4190 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4191 assert_eq!(node_txn[0].input.len(), 1);
4192 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4193 check_spends!(node_txn[0], local_txn[0].clone());
4195 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4196 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4197 assert_eq!(spend_txn.len(), 2);
4198 check_spends!(spend_txn[0], node_txn[0].clone());
4199 check_spends!(spend_txn[1], node_txn[2].clone());
4202 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4203 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4204 // unrevoked commitment transaction.
4205 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4206 // a remote RAA before they could be failed backwards (and combinations thereof).
4207 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4208 // use the same payment hashes.
4209 // Thus, we use a six-node network:
4214 // And test where C fails back to A/B when D announces its latest commitment transaction
4215 let nodes = create_network(6, &[None, None, None, None, None, None]);
4217 create_announced_chan_between_nodes(&nodes, 0, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4218 create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4219 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4220 create_announced_chan_between_nodes(&nodes, 3, 4, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4221 create_announced_chan_between_nodes(&nodes, 3, 5, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4223 // Rebalance and check output sanity...
4224 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4225 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4226 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn()[0].output.len(), 2);
4228 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4230 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
4232 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
4233 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();
4235 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
4237 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
4239 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4241 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4242 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4244 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4246 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4249 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4251 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();
4252 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
4255 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
4257 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4258 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4260 // Double-check that six of the new HTLC were added
4261 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4262 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4263 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn().len(), 1);
4264 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn()[0].output.len(), 8);
4266 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4267 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4268 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4269 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4270 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4271 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4272 check_added_monitors!(nodes[4], 0);
4273 expect_pending_htlcs_forwardable!(nodes[4]);
4274 check_added_monitors!(nodes[4], 1);
4276 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4277 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4278 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4279 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4280 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4281 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4283 // Fail 3rd below-dust and 7th above-dust HTLCs
4284 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4285 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4286 check_added_monitors!(nodes[5], 0);
4287 expect_pending_htlcs_forwardable!(nodes[5]);
4288 check_added_monitors!(nodes[5], 1);
4290 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4291 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4292 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4293 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4295 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4297 expect_pending_htlcs_forwardable!(nodes[3]);
4298 check_added_monitors!(nodes[3], 1);
4299 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4300 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4301 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4302 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4303 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4304 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4305 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4306 if deliver_last_raa {
4307 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4309 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4312 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4313 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4314 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4315 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4317 // We now broadcast the latest commitment transaction, which *should* result in failures for
4318 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4319 // the non-broadcast above-dust HTLCs.
4321 // Alternatively, we may broadcast the previous commitment transaction, which should only
4322 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4323 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4325 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4326 if announce_latest {
4327 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4329 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4331 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4332 check_closed_broadcast!(nodes[2], false);
4333 expect_pending_htlcs_forwardable!(nodes[2]);
4334 check_added_monitors!(nodes[2], 2);
4336 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4337 assert_eq!(cs_msgs.len(), 2);
4338 let mut a_done = false;
4339 for msg in cs_msgs {
4341 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4342 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4343 // should be failed-backwards here.
4344 let target = if *node_id == nodes[0].node.get_our_node_id() {
4345 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4346 for htlc in &updates.update_fail_htlcs {
4347 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 });
4349 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4354 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4355 for htlc in &updates.update_fail_htlcs {
4356 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4358 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4359 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4362 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4363 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4364 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4365 if announce_latest {
4366 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4367 if *node_id == nodes[0].node.get_our_node_id() {
4368 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4371 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4373 _ => panic!("Unexpected event"),
4377 let as_events = nodes[0].node.get_and_clear_pending_events();
4378 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4379 let mut as_failds = HashSet::new();
4380 for event in as_events.iter() {
4381 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4382 assert!(as_failds.insert(*payment_hash));
4383 if *payment_hash != payment_hash_2 {
4384 assert_eq!(*rejected_by_dest, deliver_last_raa);
4386 assert!(!rejected_by_dest);
4388 } else { panic!("Unexpected event"); }
4390 assert!(as_failds.contains(&payment_hash_1));
4391 assert!(as_failds.contains(&payment_hash_2));
4392 if announce_latest {
4393 assert!(as_failds.contains(&payment_hash_3));
4394 assert!(as_failds.contains(&payment_hash_5));
4396 assert!(as_failds.contains(&payment_hash_6));
4398 let bs_events = nodes[1].node.get_and_clear_pending_events();
4399 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4400 let mut bs_failds = HashSet::new();
4401 for event in bs_events.iter() {
4402 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4403 assert!(bs_failds.insert(*payment_hash));
4404 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4405 assert_eq!(*rejected_by_dest, deliver_last_raa);
4407 assert!(!rejected_by_dest);
4409 } else { panic!("Unexpected event"); }
4411 assert!(bs_failds.contains(&payment_hash_1));
4412 assert!(bs_failds.contains(&payment_hash_2));
4413 if announce_latest {
4414 assert!(bs_failds.contains(&payment_hash_4));
4416 assert!(bs_failds.contains(&payment_hash_5));
4418 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4419 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4420 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4421 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4422 // PaymentFailureNetworkUpdates.
4423 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4424 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4425 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4426 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4427 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4429 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4430 _ => panic!("Unexpected event"),
4436 fn test_fail_backwards_latest_remote_announce_a() {
4437 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4441 fn test_fail_backwards_latest_remote_announce_b() {
4442 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4446 fn test_fail_backwards_previous_remote_announce() {
4447 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4448 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4449 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4453 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4454 let nodes = create_network(2, &[None, None]);
4456 // Create some initial channels
4457 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4459 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4460 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4461 assert_eq!(local_txn[0].input.len(), 1);
4462 check_spends!(local_txn[0], chan_1.3.clone());
4464 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4465 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4466 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4467 check_closed_broadcast!(nodes[0], false);
4469 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4470 assert_eq!(node_txn[0].input.len(), 1);
4471 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4472 check_spends!(node_txn[0], local_txn[0].clone());
4474 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4475 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4476 assert_eq!(spend_txn.len(), 8);
4477 assert_eq!(spend_txn[0], spend_txn[2]);
4478 assert_eq!(spend_txn[0], spend_txn[4]);
4479 assert_eq!(spend_txn[0], spend_txn[6]);
4480 assert_eq!(spend_txn[1], spend_txn[3]);
4481 assert_eq!(spend_txn[1], spend_txn[5]);
4482 assert_eq!(spend_txn[1], spend_txn[7]);
4483 check_spends!(spend_txn[0], local_txn[0].clone());
4484 check_spends!(spend_txn[1], node_txn[0].clone());
4488 fn test_static_output_closing_tx() {
4489 let nodes = create_network(2, &[None, None]);
4491 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4493 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4494 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4496 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4497 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4498 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4499 assert_eq!(spend_txn.len(), 1);
4500 check_spends!(spend_txn[0], closing_tx.clone());
4502 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4503 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4504 assert_eq!(spend_txn.len(), 1);
4505 check_spends!(spend_txn[0], closing_tx);
4508 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4509 let nodes = create_network(2, &[None, None]);
4510 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4512 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4514 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4515 // present in B's local commitment transaction, but none of A's commitment transactions.
4516 assert!(nodes[1].node.claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 }));
4517 check_added_monitors!(nodes[1], 1);
4519 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4520 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
4521 let events = nodes[0].node.get_and_clear_pending_events();
4522 assert_eq!(events.len(), 1);
4524 Event::PaymentSent { payment_preimage } => {
4525 assert_eq!(payment_preimage, our_payment_preimage);
4527 _ => panic!("Unexpected event"),
4530 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4531 check_added_monitors!(nodes[0], 1);
4532 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4533 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4534 check_added_monitors!(nodes[1], 1);
4536 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4537 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4538 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4539 header.prev_blockhash = header.bitcoin_hash();
4541 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4542 check_closed_broadcast!(nodes[1], false);
4545 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4546 let mut nodes = create_network(2, &[None, None]);
4547 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4549 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();
4550 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4551 nodes[0].node.send_payment(route, payment_hash).unwrap();
4552 check_added_monitors!(nodes[0], 1);
4554 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4556 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4557 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4558 // to "time out" the HTLC.
4560 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4562 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4563 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
4564 header.prev_blockhash = header.bitcoin_hash();
4566 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4567 check_closed_broadcast!(nodes[0], false);
4570 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4571 let nodes = create_network(3, &[None, None, None]);
4572 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
4574 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4575 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4576 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4577 // actually revoked.
4578 let htlc_value = if use_dust { 50000 } else { 3000000 };
4579 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4580 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4581 expect_pending_htlcs_forwardable!(nodes[1]);
4582 check_added_monitors!(nodes[1], 1);
4584 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4585 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
4586 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4587 check_added_monitors!(nodes[0], 1);
4588 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4589 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4590 check_added_monitors!(nodes[1], 1);
4591 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
4592 check_added_monitors!(nodes[1], 1);
4593 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4595 if check_revoke_no_close {
4596 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4597 check_added_monitors!(nodes[0], 1);
4600 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4601 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4602 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4603 header.prev_blockhash = header.bitcoin_hash();
4605 if !check_revoke_no_close {
4606 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4607 check_closed_broadcast!(nodes[0], false);
4609 let events = nodes[0].node.get_and_clear_pending_events();
4610 assert_eq!(events.len(), 1);
4612 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4613 assert_eq!(payment_hash, our_payment_hash);
4614 assert!(rejected_by_dest);
4616 _ => panic!("Unexpected event"),
4621 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
4622 // There are only a few cases to test here:
4623 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
4624 // broadcastable commitment transactions result in channel closure,
4625 // * its included in an unrevoked-but-previous remote commitment transaction,
4626 // * its included in the latest remote or local commitment transactions.
4627 // We test each of the three possible commitment transactions individually and use both dust and
4629 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
4630 // assume they are handled the same across all six cases, as both outbound and inbound failures are
4631 // tested for at least one of the cases in other tests.
4633 fn htlc_claim_single_commitment_only_a() {
4634 do_htlc_claim_local_commitment_only(true);
4635 do_htlc_claim_local_commitment_only(false);
4637 do_htlc_claim_current_remote_commitment_only(true);
4638 do_htlc_claim_current_remote_commitment_only(false);
4642 fn htlc_claim_single_commitment_only_b() {
4643 do_htlc_claim_previous_remote_commitment_only(true, false);
4644 do_htlc_claim_previous_remote_commitment_only(false, false);
4645 do_htlc_claim_previous_remote_commitment_only(true, true);
4646 do_htlc_claim_previous_remote_commitment_only(false, true);
4649 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>)
4650 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4653 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);
4657 // 0: node1 fails backward
4658 // 1: final node fails backward
4659 // 2: payment completed but the user rejects the payment
4660 // 3: final node fails backward (but tamper onion payloads from node0)
4661 // 100: trigger error in the intermediate node and tamper returning fail_htlc
4662 // 200: trigger error in the final node and tamper returning fail_htlc
4663 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>)
4664 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4665 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
4669 // reset block height
4670 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4671 for ix in 0..nodes.len() {
4672 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
4675 macro_rules! expect_event {
4676 ($node: expr, $event_type: path) => {{
4677 let events = $node.node.get_and_clear_pending_events();
4678 assert_eq!(events.len(), 1);
4680 $event_type { .. } => {},
4681 _ => panic!("Unexpected event"),
4686 macro_rules! expect_htlc_forward {
4688 expect_event!($node, Event::PendingHTLCsForwardable);
4689 $node.node.process_pending_htlc_forwards();
4693 // 0 ~~> 2 send payment
4694 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
4695 check_added_monitors!(nodes[0], 1);
4696 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4697 // temper update_add (0 => 1)
4698 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
4699 if test_case == 0 || test_case == 3 || test_case == 100 {
4700 callback_msg(&mut update_add_0);
4703 // 0 => 1 update_add & CS
4704 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
4705 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
4707 let update_1_0 = match test_case {
4708 0|100 => { // intermediate node failure; fail backward to 0
4709 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4710 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));
4713 1|2|3|200 => { // final node failure; forwarding to 2
4714 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4716 if test_case != 200 {
4719 expect_htlc_forward!(&nodes[1]);
4721 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4722 check_added_monitors!(&nodes[1], 1);
4723 assert_eq!(update_1.update_add_htlcs.len(), 1);
4724 // tamper update_add (1 => 2)
4725 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
4726 if test_case != 3 && test_case != 200 {
4727 callback_msg(&mut update_add_1);
4731 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
4732 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
4734 if test_case == 2 || test_case == 200 {
4735 expect_htlc_forward!(&nodes[2]);
4736 expect_event!(&nodes[2], Event::PaymentReceived);
4738 expect_pending_htlcs_forwardable!(nodes[2]);
4741 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4742 if test_case == 2 || test_case == 200 {
4743 check_added_monitors!(&nodes[2], 1);
4745 assert!(update_2_1.update_fail_htlcs.len() == 1);
4747 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
4748 if test_case == 200 {
4749 callback_fail(&mut fail_msg);
4753 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
4754 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
4756 // backward fail on 1
4757 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4758 assert!(update_1_0.update_fail_htlcs.len() == 1);
4761 _ => unreachable!(),
4764 // 1 => 0 commitment_signed_dance
4765 if update_1_0.update_fail_htlcs.len() > 0 {
4766 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
4767 if test_case == 100 {
4768 callback_fail(&mut fail_msg);
4770 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
4772 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
4775 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
4777 let events = nodes[0].node.get_and_clear_pending_events();
4778 assert_eq!(events.len(), 1);
4779 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
4780 assert_eq!(*rejected_by_dest, !expected_retryable);
4781 assert_eq!(*error_code, expected_error_code);
4783 panic!("Uexpected event");
4786 let events = nodes[0].node.get_and_clear_pending_msg_events();
4787 if expected_channel_update.is_some() {
4788 assert_eq!(events.len(), 1);
4790 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
4792 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
4793 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
4794 panic!("channel_update not found!");
4797 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
4798 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4799 assert!(*short_channel_id == *expected_short_channel_id);
4800 assert!(*is_permanent == *expected_is_permanent);
4802 panic!("Unexpected message event");
4805 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
4806 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4807 assert!(*node_id == *expected_node_id);
4808 assert!(*is_permanent == *expected_is_permanent);
4810 panic!("Unexpected message event");
4815 _ => panic!("Unexpected message event"),
4818 assert_eq!(events.len(), 0);
4822 impl msgs::ChannelUpdate {
4823 fn dummy() -> msgs::ChannelUpdate {
4824 use secp256k1::ffi::Signature as FFISignature;
4825 use secp256k1::Signature;
4826 msgs::ChannelUpdate {
4827 signature: Signature::from(FFISignature::new()),
4828 contents: msgs::UnsignedChannelUpdate {
4829 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
4830 short_channel_id: 0,
4833 cltv_expiry_delta: 0,
4834 htlc_minimum_msat: 0,
4836 fee_proportional_millionths: 0,
4837 excess_data: vec![],
4844 fn test_onion_failure() {
4845 use ln::msgs::ChannelUpdate;
4846 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
4849 const BADONION: u16 = 0x8000;
4850 const PERM: u16 = 0x4000;
4851 const NODE: u16 = 0x2000;
4852 const UPDATE: u16 = 0x1000;
4854 let mut nodes = create_network(3, &[None, None, None]);
4855 for node in nodes.iter() {
4856 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
4858 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new()), create_announced_chan_between_nodes(&nodes, 1, 2, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new())];
4859 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4860 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
4862 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
4864 // intermediate node failure
4865 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
4866 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4867 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4868 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4869 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4870 onion_payloads[0].realm = 3;
4871 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
4872 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
4874 // final node failure
4875 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
4876 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4877 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4878 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4879 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4880 onion_payloads[1].realm = 3;
4881 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
4882 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4884 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
4885 // receiving simulated fail messages
4886 // intermediate node failure
4887 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4889 msg.amount_msat -= 1;
4891 // and tamper returning error message
4892 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4893 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4894 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
4895 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
4897 // final node failure
4898 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4899 // and tamper returning error message
4900 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4901 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4902 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
4904 nodes[2].node.fail_htlc_backwards(&payment_hash);
4905 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
4907 // intermediate node failure
4908 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4909 msg.amount_msat -= 1;
4911 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4912 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4913 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
4914 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4916 // final node failure
4917 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4918 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4919 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4920 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
4922 nodes[2].node.fail_htlc_backwards(&payment_hash);
4923 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4925 // intermediate node failure
4926 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4927 msg.amount_msat -= 1;
4929 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4930 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4931 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
4933 nodes[2].node.fail_htlc_backwards(&payment_hash);
4934 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4936 // final node failure
4937 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4938 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4939 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4940 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
4942 nodes[2].node.fail_htlc_backwards(&payment_hash);
4943 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4945 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
4946 Some(BADONION|PERM|4), None);
4948 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
4949 Some(BADONION|PERM|5), None);
4951 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
4952 Some(BADONION|PERM|6), None);
4954 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4955 msg.amount_msat -= 1;
4957 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4958 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4959 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
4960 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4962 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4963 msg.amount_msat -= 1;
4965 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4966 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4967 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
4968 // short_channel_id from the processing node
4969 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4971 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4972 msg.amount_msat -= 1;
4974 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4975 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4976 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
4977 // short_channel_id from the processing node
4978 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4980 let mut bogus_route = route.clone();
4981 bogus_route.hops[1].short_channel_id -= 1;
4982 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
4983 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
4985 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
4986 let mut bogus_route = route.clone();
4987 let route_len = bogus_route.hops.len();
4988 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
4989 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4991 //TODO: with new config API, we will be able to generate both valid and
4992 //invalid channel_update cases.
4993 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
4994 msg.amount_msat -= 1;
4995 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4997 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
4998 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
4999 msg.cltv_expiry -= 1;
5000 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5002 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5003 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5004 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5006 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5007 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5009 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5010 nodes[2].node.fail_htlc_backwards(&payment_hash);
5011 }, false, Some(PERM|15), None);
5013 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5014 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5015 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5017 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5018 }, || {}, true, Some(17), None);
5020 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5021 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
5022 for f in pending_forwards.iter_mut() {
5024 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5025 forward_info.outgoing_cltv_value += 1,
5030 }, true, Some(18), None);
5032 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5033 // violate amt_to_forward > msg.amount_msat
5034 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
5035 for f in pending_forwards.iter_mut() {
5037 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5038 forward_info.amt_to_forward -= 1,
5043 }, true, Some(19), None);
5045 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5046 // disconnect event to the channel between nodes[1] ~ nodes[2]
5047 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5048 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5049 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5050 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5052 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5053 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5054 let mut route = route.clone();
5056 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
5057 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5058 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
5059 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5060 msg.cltv_expiry = htlc_cltv;
5061 msg.onion_routing_packet = onion_packet;
5062 }, ||{}, true, Some(21), None);
5067 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5068 let nodes = create_network(2, &[None, None]);
5069 //Force duplicate channel ids
5070 for node in nodes.iter() {
5071 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5074 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5075 let channel_value_satoshis=10000;
5076 let push_msat=10001;
5077 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).unwrap();
5078 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5079 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), Features::<FeatureContextInit>::new(), &node0_to_1_send_open_channel);
5081 //Create a second channel with a channel_id collision
5082 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
5086 fn bolt2_open_channel_sending_node_checks_part2() {
5087 let nodes = create_network(2, &[None, None]);
5089 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5090 let channel_value_satoshis=2^24;
5091 let push_msat=10001;
5092 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
5094 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5095 let channel_value_satoshis=10000;
5096 // Test when push_msat is equal to 1000 * funding_satoshis.
5097 let push_msat=1000*channel_value_satoshis+1;
5098 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
5100 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5101 let channel_value_satoshis=10000;
5102 let push_msat=10001;
5103 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_ok()); //Create a valid channel
5104 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5105 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5107 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5108 // 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
5109 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5111 // 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.
5112 assert!(BREAKDOWN_TIMEOUT>0);
5113 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5115 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5116 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5117 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5119 // 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.
5120 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5121 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5122 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5123 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5124 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5127 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5128 // 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.
5129 //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.
5132 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5133 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5134 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5135 let mut nodes = create_network(2, &[None, None]);
5136 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5137 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5138 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5140 route.hops[0].fee_msat = 0;
5142 let err = nodes[0].node.send_payment(route, our_payment_hash);
5144 if let Err(APIError::ChannelUnavailable{err}) = err {
5145 assert_eq!(err, "Cannot send less than their minimum HTLC value");
5149 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5150 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5154 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5155 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5156 //It is enforced when constructing a route.
5157 let mut nodes = create_network(2, &[None, None]);
5158 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5159 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5160 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5162 let err = nodes[0].node.send_payment(route, our_payment_hash);
5164 if let Err(APIError::RouteError{err}) = err {
5165 assert_eq!(err, "Channel CLTV overflowed?!");
5172 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5173 //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.
5174 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5175 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5176 let mut nodes = create_network(2, &[None, None]);
5177 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5178 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5180 for i in 0..max_accepted_htlcs {
5181 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5182 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5183 let payment_event = {
5184 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5185 check_added_monitors!(nodes[0], 1);
5187 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5188 assert_eq!(events.len(), 1);
5189 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5190 assert_eq!(htlcs[0].htlc_id, i);
5194 SendEvent::from_event(events.remove(0))
5196 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5197 check_added_monitors!(nodes[1], 0);
5198 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5200 expect_pending_htlcs_forwardable!(nodes[1]);
5201 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5203 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5204 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5205 let err = nodes[0].node.send_payment(route, our_payment_hash);
5207 if let Err(APIError::ChannelUnavailable{err}) = err {
5208 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5212 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5213 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5217 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5218 //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.
5219 let mut nodes = create_network(2, &[None, None]);
5220 let channel_value = 100000;
5221 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5222 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5224 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5226 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5227 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5228 let err = nodes[0].node.send_payment(route, our_payment_hash);
5230 if let Err(APIError::ChannelUnavailable{err}) = err {
5231 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5235 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5236 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);
5238 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5241 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5243 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5244 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5245 let mut nodes = create_network(2, &[None, None]);
5246 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5247 let htlc_minimum_msat: u64;
5249 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5250 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5251 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5253 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5254 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5255 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5256 check_added_monitors!(nodes[0], 1);
5257 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5258 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5259 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5260 assert!(nodes[1].node.list_channels().is_empty());
5261 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5262 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5266 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5267 //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
5268 let mut nodes = create_network(2, &[None, None]);
5269 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5271 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5273 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5274 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5275 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5276 check_added_monitors!(nodes[0], 1);
5277 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5279 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5280 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5282 assert!(nodes[1].node.list_channels().is_empty());
5283 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5284 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5288 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5289 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5290 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5291 let mut nodes = create_network(2, &[None, None]);
5292 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5293 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5294 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5296 let session_priv = SecretKey::from_slice(&{
5297 let mut session_key = [0; 32];
5298 let mut rng = thread_rng();
5299 rng.fill_bytes(&mut session_key);
5301 }).expect("RNG is bad!");
5303 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5304 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5305 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5306 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5308 let mut msg = msgs::UpdateAddHTLC {
5312 payment_hash: our_payment_hash,
5313 cltv_expiry: htlc_cltv,
5314 onion_routing_packet: onion_packet.clone(),
5317 for i in 0..super::channel::OUR_MAX_HTLCS {
5318 msg.htlc_id = i as u64;
5319 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5321 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5322 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5324 assert!(nodes[1].node.list_channels().is_empty());
5325 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5326 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5330 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5331 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5332 let mut nodes = create_network(2, &[None, None]);
5333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5334 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5335 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5336 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5337 check_added_monitors!(nodes[0], 1);
5338 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5339 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5340 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5342 assert!(nodes[1].node.list_channels().is_empty());
5343 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5344 assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
5348 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5349 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5350 let mut nodes = create_network(2, &[None, None]);
5351 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5352 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5353 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5354 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5355 check_added_monitors!(nodes[0], 1);
5356 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5357 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5358 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5360 assert!(nodes[1].node.list_channels().is_empty());
5361 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5362 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
5366 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5367 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5368 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5369 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5370 let mut nodes = create_network(2, &[None, None]);
5371 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5372 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5373 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5374 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5375 check_added_monitors!(nodes[0], 1);
5376 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5377 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5379 //Disconnect and Reconnect
5380 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5381 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5382 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5383 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5384 assert_eq!(reestablish_1.len(), 1);
5385 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5386 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5387 assert_eq!(reestablish_2.len(), 1);
5388 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
5389 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5390 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
5391 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5394 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5395 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5396 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
5397 check_added_monitors!(nodes[1], 1);
5398 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5400 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5402 assert!(nodes[1].node.list_channels().is_empty());
5403 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5404 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
5408 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5409 //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.
5411 let mut nodes = create_network(2, &[None, None]);
5412 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5414 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5415 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5416 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5417 check_added_monitors!(nodes[0], 1);
5418 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5419 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5421 let update_msg = msgs::UpdateFulfillHTLC{
5424 payment_preimage: our_payment_preimage,
5427 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5429 assert!(nodes[0].node.list_channels().is_empty());
5430 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5431 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5435 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5436 //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.
5438 let mut nodes = create_network(2, &[None, None]);
5439 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5441 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5442 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5443 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5444 check_added_monitors!(nodes[0], 1);
5445 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5446 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5448 let update_msg = msgs::UpdateFailHTLC{
5451 reason: msgs::OnionErrorPacket { data: Vec::new()},
5454 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5456 assert!(nodes[0].node.list_channels().is_empty());
5457 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5458 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5462 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5463 //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.
5465 let mut nodes = create_network(2, &[None, None]);
5466 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5468 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5469 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5470 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5471 check_added_monitors!(nodes[0], 1);
5472 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5473 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5475 let update_msg = msgs::UpdateFailMalformedHTLC{
5478 sha256_of_onion: [1; 32],
5479 failure_code: 0x8000,
5482 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5484 assert!(nodes[0].node.list_channels().is_empty());
5485 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5486 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5490 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
5491 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
5493 let nodes = create_network(2, &[None, None]);
5494 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5496 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5498 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
5499 check_added_monitors!(nodes[1], 1);
5501 let events = nodes[1].node.get_and_clear_pending_msg_events();
5502 assert_eq!(events.len(), 1);
5503 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5505 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, .. } } => {
5506 assert!(update_add_htlcs.is_empty());
5507 assert_eq!(update_fulfill_htlcs.len(), 1);
5508 assert!(update_fail_htlcs.is_empty());
5509 assert!(update_fail_malformed_htlcs.is_empty());
5510 assert!(update_fee.is_none());
5511 update_fulfill_htlcs[0].clone()
5513 _ => panic!("Unexpected event"),
5517 update_fulfill_msg.htlc_id = 1;
5519 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5521 assert!(nodes[0].node.list_channels().is_empty());
5522 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5523 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
5527 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
5528 //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.
5530 let nodes = create_network(2, &[None, None]);
5531 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5533 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5535 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
5536 check_added_monitors!(nodes[1], 1);
5538 let events = nodes[1].node.get_and_clear_pending_msg_events();
5539 assert_eq!(events.len(), 1);
5540 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5542 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, .. } } => {
5543 assert!(update_add_htlcs.is_empty());
5544 assert_eq!(update_fulfill_htlcs.len(), 1);
5545 assert!(update_fail_htlcs.is_empty());
5546 assert!(update_fail_malformed_htlcs.is_empty());
5547 assert!(update_fee.is_none());
5548 update_fulfill_htlcs[0].clone()
5550 _ => panic!("Unexpected event"),
5554 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
5556 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5558 assert!(nodes[0].node.list_channels().is_empty());
5559 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5560 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
5565 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
5566 //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.
5568 let mut nodes = create_network(2, &[None, None]);
5569 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5570 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5571 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5572 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5573 check_added_monitors!(nodes[0], 1);
5575 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5576 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5578 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5579 check_added_monitors!(nodes[1], 0);
5580 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
5582 let events = nodes[1].node.get_and_clear_pending_msg_events();
5584 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
5586 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, .. } } => {
5587 assert!(update_add_htlcs.is_empty());
5588 assert!(update_fulfill_htlcs.is_empty());
5589 assert!(update_fail_htlcs.is_empty());
5590 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5591 assert!(update_fee.is_none());
5592 update_fail_malformed_htlcs[0].clone()
5594 _ => panic!("Unexpected event"),
5597 update_msg.failure_code &= !0x8000;
5598 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5600 assert!(nodes[0].node.list_channels().is_empty());
5601 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5602 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
5606 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
5607 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
5608 // * 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.
5610 let mut nodes = create_network(3, &[None, None, None]);
5611 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5612 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5614 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
5615 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5618 let mut payment_event = {
5619 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5620 check_added_monitors!(nodes[0], 1);
5621 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5622 assert_eq!(events.len(), 1);
5623 SendEvent::from_event(events.remove(0))
5625 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5626 check_added_monitors!(nodes[1], 0);
5627 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5628 expect_pending_htlcs_forwardable!(nodes[1]);
5629 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
5630 assert_eq!(events_2.len(), 1);
5631 check_added_monitors!(nodes[1], 1);
5632 payment_event = SendEvent::from_event(events_2.remove(0));
5633 assert_eq!(payment_event.msgs.len(), 1);
5636 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5637 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
5638 check_added_monitors!(nodes[2], 0);
5639 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
5641 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
5642 assert_eq!(events_3.len(), 1);
5643 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
5645 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 } } => {
5646 assert!(update_add_htlcs.is_empty());
5647 assert!(update_fulfill_htlcs.is_empty());
5648 assert!(update_fail_htlcs.is_empty());
5649 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5650 assert!(update_fee.is_none());
5651 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
5653 _ => panic!("Unexpected event"),
5657 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
5659 check_added_monitors!(nodes[1], 0);
5660 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
5661 expect_pending_htlcs_forwardable!(nodes[1]);
5662 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
5663 assert_eq!(events_4.len(), 1);
5665 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
5667 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, .. } } => {
5668 assert!(update_add_htlcs.is_empty());
5669 assert!(update_fulfill_htlcs.is_empty());
5670 assert_eq!(update_fail_htlcs.len(), 1);
5671 assert!(update_fail_malformed_htlcs.is_empty());
5672 assert!(update_fee.is_none());
5674 _ => panic!("Unexpected event"),
5677 check_added_monitors!(nodes[1], 1);
5680 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
5681 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
5682 // 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
5683 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
5685 let nodes = create_network(2, &[None, None]);
5686 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5688 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5690 // We route 2 dust-HTLCs between A and B
5691 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5692 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5693 route_payment(&nodes[0], &[&nodes[1]], 1000000);
5695 // Cache one local commitment tx as previous
5696 let as_prev_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
5698 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
5699 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
5700 check_added_monitors!(nodes[1], 0);
5701 expect_pending_htlcs_forwardable!(nodes[1]);
5702 check_added_monitors!(nodes[1], 1);
5704 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5705 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
5706 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
5707 check_added_monitors!(nodes[0], 1);
5709 // Cache one local commitment tx as lastest
5710 let as_last_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
5712 let events = nodes[0].node.get_and_clear_pending_msg_events();
5714 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
5715 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5717 _ => panic!("Unexpected event"),
5720 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
5721 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5723 _ => panic!("Unexpected event"),
5726 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
5727 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
5728 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5730 if announce_latest {
5731 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
5733 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
5736 let events = nodes[0].node.get_and_clear_pending_msg_events();
5737 assert_eq!(events.len(), 1);
5739 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5740 _ => panic!("Unexpected event"),
5743 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5744 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5745 let events = nodes[0].node.get_and_clear_pending_events();
5746 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
5747 assert_eq!(events.len(), 2);
5748 let mut first_failed = false;
5749 for event in events {
5751 Event::PaymentFailed { payment_hash, .. } => {
5752 if payment_hash == payment_hash_1 {
5753 assert!(!first_failed);
5754 first_failed = true;
5756 assert_eq!(payment_hash, payment_hash_2);
5759 _ => panic!("Unexpected event"),
5765 fn test_failure_delay_dust_htlc_local_commitment() {
5766 do_test_failure_delay_dust_htlc_local_commitment(true);
5767 do_test_failure_delay_dust_htlc_local_commitment(false);
5771 fn test_no_failure_dust_htlc_local_commitment() {
5772 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
5773 // prone to error, we test here that a dummy transaction don't fail them.
5775 let nodes = create_network(2, &[None, None]);
5776 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5779 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5781 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5782 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5784 // We route 2 dust-HTLCs between A and B
5785 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5786 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
5788 // Build a dummy invalid transaction trying to spend a commitment tx
5790 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
5791 script_sig: Script::new(),
5793 witness: Vec::new(),
5797 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
5801 let dummy_tx = Transaction {
5808 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5809 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
5810 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5811 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5812 // We broadcast a few more block to check everything is all right
5813 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
5814 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5815 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5817 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
5818 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
5821 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
5822 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
5823 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
5824 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
5825 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
5826 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
5827 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
5829 let nodes = create_network(3, &[None, None, None]);
5830 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
5832 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5834 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5835 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5837 let as_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
5838 let bs_commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
5840 // We revoked bs_commitment_tx
5842 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5843 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
5846 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5847 let mut timeout_tx = Vec::new();
5849 // We fail dust-HTLC 1 by broadcast of local commitment tx
5850 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
5851 let events = nodes[0].node.get_and_clear_pending_msg_events();
5852 assert_eq!(events.len(), 1);
5854 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5855 _ => panic!("Unexpected event"),
5857 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5858 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5859 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5860 let events = nodes[0].node.get_and_clear_pending_events();
5861 assert_eq!(events.len(), 1);
5863 Event::PaymentFailed { payment_hash, .. } => {
5864 assert_eq!(payment_hash, dust_hash);
5866 _ => panic!("Unexpected event"),
5868 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5869 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
5870 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5871 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5872 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
5873 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5874 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5875 let events = nodes[0].node.get_and_clear_pending_events();
5876 assert_eq!(events.len(), 1);
5878 Event::PaymentFailed { payment_hash, .. } => {
5879 assert_eq!(payment_hash, non_dust_hash);
5881 _ => panic!("Unexpected event"),
5884 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
5885 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
5886 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5887 let events = nodes[0].node.get_and_clear_pending_msg_events();
5888 assert_eq!(events.len(), 1);
5890 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5891 _ => panic!("Unexpected event"),
5893 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5894 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5895 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5897 let events = nodes[0].node.get_and_clear_pending_events();
5898 assert_eq!(events.len(), 1);
5900 Event::PaymentFailed { payment_hash, .. } => {
5901 assert_eq!(payment_hash, dust_hash);
5903 _ => panic!("Unexpected event"),
5905 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5906 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
5907 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
5908 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5909 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5910 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5911 let events = nodes[0].node.get_and_clear_pending_events();
5912 assert_eq!(events.len(), 1);
5914 Event::PaymentFailed { payment_hash, .. } => {
5915 assert_eq!(payment_hash, non_dust_hash);
5917 _ => panic!("Unexpected event"),
5920 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
5922 let events = nodes[0].node.get_and_clear_pending_events();
5923 assert_eq!(events.len(), 2);
5926 Event::PaymentFailed { payment_hash, .. } => {
5927 if payment_hash == dust_hash { first = true; }
5928 else { first = false; }
5930 _ => panic!("Unexpected event"),
5933 Event::PaymentFailed { payment_hash, .. } => {
5934 if first { assert_eq!(payment_hash, non_dust_hash); }
5935 else { assert_eq!(payment_hash, dust_hash); }
5937 _ => panic!("Unexpected event"),
5944 fn test_sweep_outbound_htlc_failure_update() {
5945 do_test_sweep_outbound_htlc_failure_update(false, true);
5946 do_test_sweep_outbound_htlc_failure_update(false, false);
5947 do_test_sweep_outbound_htlc_failure_update(true, false);
5951 fn test_upfront_shutdown_script() {
5952 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
5953 // enforce it at shutdown message
5955 let mut config = UserConfig::default();
5956 config.channel_options.announced_channel = true;
5957 config.peer_channel_config_limits.force_announced_channel_preference = false;
5958 config.channel_options.commit_upfront_shutdown_pubkey = false;
5959 let cfgs = [None, Some(config), None];
5960 let nodes = create_network(3, &cfgs);
5962 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
5963 let flags = Features::<FeatureContextInit>::new();
5964 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5965 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5966 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5967 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5968 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
5969 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
5970 let events = nodes[2].node.get_and_clear_pending_msg_events();
5971 assert_eq!(events.len(), 2);
5973 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5974 _ => panic!("Unexpected event"),
5976 if let MessageSendEvent::HandleError { ref action, .. } = events[1] {
5978 &ErrorAction::SendErrorMessage { ref msg } => {
5979 assert_eq!(msg.data,"Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
5981 _ => { assert!(false); }
5983 } else { assert!(false); }
5985 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
5986 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5987 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5988 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5989 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
5990 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
5991 let events = nodes[2].node.get_and_clear_pending_msg_events();
5992 assert_eq!(events.len(), 1);
5994 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5995 _ => panic!("Unexpected event"),
5998 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
5999 let mut flags_no = Features::<FeatureContextInit>::new();
6000 flags_no.unset_upfront_shutdown_script();
6001 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6002 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6003 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6004 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6005 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6006 let events = nodes[1].node.get_and_clear_pending_msg_events();
6007 assert_eq!(events.len(), 1);
6009 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6010 _ => panic!("Unexpected event"),
6013 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6014 // channel smoothly, opt-out is from channel initiator here
6015 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6016 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6017 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6018 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6019 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6020 let events = nodes[0].node.get_and_clear_pending_msg_events();
6021 assert_eq!(events.len(), 1);
6023 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6024 _ => panic!("Unexpected event"),
6027 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6028 //// channel smoothly
6029 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6030 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6031 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6032 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6033 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6034 let events = nodes[0].node.get_and_clear_pending_msg_events();
6035 assert_eq!(events.len(), 2);
6037 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6038 _ => panic!("Unexpected event"),
6041 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6042 _ => panic!("Unexpected event"),
6047 fn test_user_configurable_csv_delay() {
6048 // We test our channel constructors yield errors when we pass them absurd csv delay
6050 let mut low_our_to_self_config = UserConfig::default();
6051 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6052 let mut high_their_to_self_config = UserConfig::default();
6053 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6054 let cfgs = [Some(high_their_to_self_config.clone()), None];
6055 let nodes = create_network(2, &cfgs);
6057 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6058 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())));
6059 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) {
6061 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6062 _ => panic!("Unexpected event"),
6064 } else { assert!(false) }
6066 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6067 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
6068 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6069 open_channel.to_self_delay = 200;
6070 if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), Features::<FeatureContextInit>::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6072 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6073 _ => panic!("Unexpected event"),
6075 } else { assert!(false); }
6077 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6078 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
6079 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), Features::<FeatureContextInit>::new(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6080 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6081 accept_channel.to_self_delay = 200;
6082 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), Features::<FeatureContextInit>::new(), &accept_channel);
6083 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6085 &ErrorAction::SendErrorMessage { ref msg } => {
6086 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6088 _ => { assert!(false); }
6090 } else { assert!(false); }
6092 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6093 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
6094 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6095 open_channel.to_self_delay = 200;
6096 if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), Features::<FeatureContextInit>::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
6098 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6099 _ => panic!("Unexpected event"),
6101 } else { assert!(false); }
6105 fn test_data_loss_protect() {
6106 // We want to be sure that :
6107 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6108 // * we close channel in case of detecting other being fallen behind
6109 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6110 let mut nodes = create_network(2, &[None, None]);
6112 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6114 // Cache node A state before any channel update
6115 let previous_node_state = nodes[0].node.encode();
6116 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6117 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6119 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6120 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6122 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6123 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6125 // Restore node A from previous state
6126 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6127 let mut chan_monitor = <(Sha256dHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6128 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6129 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
6130 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
6131 let monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
6132 let node_state_0 = {
6133 let mut channel_monitors = HashMap::new();
6134 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6135 <(Sha256dHash, ChannelManager<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6136 keys_manager: Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger))),
6137 fee_estimator: feeest.clone(),
6138 monitor: monitor.clone(),
6139 logger: Arc::clone(&logger),
6141 default_config: UserConfig::default(),
6142 channel_monitors: &mut channel_monitors
6145 nodes[0].node = Arc::new(node_state_0);
6146 assert!(monitor.add_update_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor.clone()).is_ok());
6147 nodes[0].chan_monitor = monitor;
6148 nodes[0].chain_monitor = chain_monitor;
6150 let weak_res = Arc::downgrade(&nodes[0].chan_monitor.simple_monitor);
6151 nodes[0].block_notifier.register_listener(weak_res);
6152 let weak_res = Arc::downgrade(&nodes[0].node);
6153 nodes[0].block_notifier.register_listener(weak_res);
6155 check_added_monitors!(nodes[0], 1);
6157 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6158 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6160 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6162 // Check we update monitor following learning of per_commitment_point from B
6163 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6164 check_added_monitors!(nodes[0], 1);
6167 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6168 assert_eq!(node_txn.len(), 0);
6171 let mut reestablish_1 = Vec::with_capacity(1);
6172 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6173 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6174 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6175 reestablish_1.push(msg.clone());
6176 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6177 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6179 &ErrorAction::SendErrorMessage { ref msg } => {
6180 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");
6182 _ => panic!("Unexpected event!"),
6185 panic!("Unexpected event")
6189 // Check we close channel detecting A is fallen-behind
6190 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6191 let events = nodes[1].node.get_and_clear_pending_msg_events();
6192 assert_eq!(events.len(), 2);
6194 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6195 _ => panic!("Unexpected event"),
6198 MessageSendEvent::HandleError { ref action, .. } => {
6200 &ErrorAction::SendErrorMessage { ref msg } => {
6201 assert_eq!(msg.data, "Peer attempted to reestablish channel with a very old local commitment transaction"); },
6202 _ => panic!("Unexpected event!"),
6205 _ => panic!("Unexpected event"),
6208 // Check A is able to claim to_remote output
6209 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6210 assert_eq!(node_txn.len(), 1);
6211 check_spends!(node_txn[0], chan.3.clone());
6212 assert_eq!(node_txn[0].output.len(), 2);
6213 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6214 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6215 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6216 assert_eq!(spend_txn.len(), 1);
6217 check_spends!(spend_txn[0], node_txn[0].clone());
6221 fn test_check_htlc_underpaying() {
6222 // Send payment through A -> B but A is maliciously
6223 // sending a probe payment (i.e less than expected value0
6224 // to B, B should refuse payment.
6226 let nodes = create_network(2, &[None, None, None]);
6228 // Create some initial channels
6229 create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6231 let (payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6233 // Node 3 is expecting payment of 100_000 but receive 10_000,
6234 // fail htlc like we didn't know the preimage.
6235 nodes[1].node.claim_funds(payment_preimage, 100_000);
6236 nodes[1].node.process_pending_htlc_forwards();
6238 let events = nodes[1].node.get_and_clear_pending_msg_events();
6239 assert_eq!(events.len(), 1);
6240 let (update_fail_htlc, commitment_signed) = match events[0] {
6241 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 } } => {
6242 assert!(update_add_htlcs.is_empty());
6243 assert!(update_fulfill_htlcs.is_empty());
6244 assert_eq!(update_fail_htlcs.len(), 1);
6245 assert!(update_fail_malformed_htlcs.is_empty());
6246 assert!(update_fee.is_none());
6247 (update_fail_htlcs[0].clone(), commitment_signed)
6249 _ => panic!("Unexpected event"),
6251 check_added_monitors!(nodes[1], 1);
6253 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6254 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6256 let events = nodes[0].node.get_and_clear_pending_events();
6257 assert_eq!(events.len(), 1);
6258 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6259 assert_eq!(*rejected_by_dest, true);
6260 assert_eq!(error_code.unwrap(), 0x4000|15);
6262 panic!("Unexpected event");
6264 nodes[1].node.get_and_clear_pending_events();
6268 fn test_announce_disable_channels() {
6269 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6270 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6272 let nodes = create_network(2, &[None, None]);
6274 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new()).0.contents.short_channel_id;
6275 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new()).0.contents.short_channel_id;
6276 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new()).0.contents.short_channel_id;
6279 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6280 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6282 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6283 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6284 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6285 assert_eq!(msg_events.len(), 3);
6286 for e in msg_events {
6288 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6289 let short_id = msg.contents.short_channel_id;
6290 // Check generated channel_update match list in PendingChannelUpdate
6291 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6292 panic!("Generated ChannelUpdate for wrong chan!");
6295 _ => panic!("Unexpected event"),
6299 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6300 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6301 assert_eq!(reestablish_1.len(), 3);
6302 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6303 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6304 assert_eq!(reestablish_2.len(), 3);
6306 // Reestablish chan_1
6307 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6308 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6309 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6310 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6311 // Reestablish chan_2
6312 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6313 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6314 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6315 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6316 // Reestablish chan_3
6317 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6318 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6319 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6320 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6322 nodes[0].node.timer_chan_freshness_every_min();
6323 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6327 fn test_bump_penalty_txn_on_revoked_commitment() {
6328 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6329 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6331 let nodes = create_network(2, &[None, None]);
6333 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6334 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6335 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6336 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6338 let revoked_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6339 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6340 assert_eq!(revoked_txn[0].output.len(), 4);
6341 assert_eq!(revoked_txn[0].input.len(), 1);
6342 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6343 let revoked_txid = revoked_txn[0].txid();
6345 let mut penalty_sum = 0;
6346 for outp in revoked_txn[0].output.iter() {
6347 if outp.script_pubkey.is_v0_p2wsh() {
6348 penalty_sum += outp.value;
6352 // Connect blocks to change height_timer range to see if we use right soonest_timelock
6353 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6355 // Actually revoke tx by claiming a HTLC
6356 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6357 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6358 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6360 // One or more justice tx should have been broadcast, check it
6364 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6365 assert_eq!(node_txn.len(), 4); // justice tx (broadcasted from ChannelMonitor) * 2 (block-reparsing) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6366 assert_eq!(node_txn[0], node_txn[3]);
6367 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6368 assert_eq!(node_txn[0].output.len(), 1);
6369 check_spends!(node_txn[0], revoked_txn[0].clone());
6370 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6371 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6372 penalty_1 = node_txn[0].txid();
6376 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
6377 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
6378 let mut penalty_2 = penalty_1;
6379 let mut feerate_2 = 0;
6381 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6382 assert_eq!(node_txn.len(), 1);
6383 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6384 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6385 assert_eq!(node_txn[0].output.len(), 1);
6386 check_spends!(node_txn[0], revoked_txn[0].clone());
6387 penalty_2 = node_txn[0].txid();
6388 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6389 assert_ne!(penalty_2, penalty_1);
6390 let fee_2 = penalty_sum - node_txn[0].output[0].value;
6391 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
6392 // Verify 25% bump heuristic
6393 assert!(feerate_2 * 100 >= feerate_1 * 125);
6397 assert_ne!(feerate_2, 0);
6399 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
6400 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
6402 let mut feerate_3 = 0;
6404 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6405 assert_eq!(node_txn.len(), 1);
6406 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6407 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6408 assert_eq!(node_txn[0].output.len(), 1);
6409 check_spends!(node_txn[0], revoked_txn[0].clone());
6410 penalty_3 = node_txn[0].txid();
6411 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6412 assert_ne!(penalty_3, penalty_2);
6413 let fee_3 = penalty_sum - node_txn[0].output[0].value;
6414 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
6415 // Verify 25% bump heuristic
6416 assert!(feerate_3 * 100 >= feerate_2 * 125);
6420 assert_ne!(feerate_3, 0);
6422 nodes[1].node.get_and_clear_pending_events();
6423 nodes[1].node.get_and_clear_pending_msg_events();
6427 fn test_bump_penalty_txn_on_revoked_htlcs() {
6428 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
6429 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
6431 let nodes = create_network(2, &[None, None]);
6433 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6434 // Lock HTLC in both directions
6435 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
6436 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6438 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6439 assert_eq!(revoked_local_txn[0].input.len(), 1);
6440 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
6442 // Revoke local commitment tx
6443 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6445 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6446 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
6447 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6448 check_closed_broadcast!(nodes[1], false);
6450 let mut received = ::std::usize::MAX;
6451 let mut offered = ::std::usize::MAX;
6452 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6453 assert_eq!(revoked_htlc_txn.len(), 6);
6454 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6455 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6456 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
6457 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6458 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6459 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0].clone());
6462 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6463 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6464 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0].clone());
6465 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6466 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6467 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
6472 // Broadcast set of revoked txn on A
6473 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
6474 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6475 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);
6481 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6482 assert_eq!(node_txn.len(), 9); // 3 penalty txn on revoked commitment tx * 2 (block-rescan) + A commitment tx + 2 penalty tnx on revoked HTLC txn
6483 // Verify claim tx are spending revoked HTLC txn
6484 assert_eq!(node_txn[7].input.len(), 1);
6485 assert_eq!(node_txn[7].output.len(), 1);
6486 check_spends!(node_txn[7], revoked_htlc_txn[0].clone());
6487 first = node_txn[7].txid();
6488 assert_eq!(node_txn[8].input.len(), 1);
6489 assert_eq!(node_txn[8].output.len(), 1);
6490 check_spends!(node_txn[8], revoked_htlc_txn[1].clone());
6491 second = node_txn[8].txid();
6492 // Store both feerates for later comparison
6493 let fee_1 = revoked_htlc_txn[0].output[0].value - node_txn[7].output[0].value;
6494 feerate_1 = fee_1 * 1000 / node_txn[7].get_weight() as u64;
6495 let fee_2 = revoked_htlc_txn[1].output[0].value - node_txn[8].output[0].value;
6496 feerate_2 = fee_2 * 1000 / node_txn[8].get_weight() as u64;
6500 // Connect three more block to see if bumped penalty are issued for HTLC txn
6501 let header_132 = connect_blocks(&nodes[0].block_notifier, 3, 129, true, header_129.bitcoin_hash());
6503 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6504 assert_eq!(node_txn.len(), 5); // 2 bumped penalty txn on offered/received HTLC outputs of revoked commitment tx + 1 penalty tx on to_local of revoked commitment tx + 2 bumped penalty tx on revoked HTLC txn
6506 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6507 check_spends!(node_txn[1], revoked_local_txn[0].clone());
6509 let mut penalty_local = ::std::usize::MAX;
6510 let mut penalty_offered = ::std::usize::MAX;
6511 let mut penalty_received = ::std::usize::MAX;
6514 let iter_txn = node_txn[2..].iter();
6515 for (i, tx) in iter_txn.enumerate() {
6516 if tx.input[0].previous_output.txid == revoked_local_txn[0].txid() {
6517 penalty_local = 2 + i;
6518 } else if tx.input[0].previous_output.txid == revoked_htlc_txn[offered].txid() {
6519 penalty_offered = 2+ i;
6520 } else if tx.input[0].previous_output.txid == revoked_htlc_txn[received].txid() {
6521 penalty_received = 2 + i;
6525 check_spends!(node_txn[penalty_local], revoked_local_txn[0].clone());
6527 assert_eq!(node_txn[penalty_received].input.len(), 1);
6528 assert_eq!(node_txn[penalty_received].output.len(), 1);
6529 assert_eq!(node_txn[penalty_offered].input.len(), 1);
6530 assert_eq!(node_txn[penalty_offered].output.len(), 1);
6531 // Verify bumped tx is different and 25% bump heuristic
6532 check_spends!(node_txn[penalty_offered], revoked_htlc_txn[offered].clone());
6533 assert_ne!(first, node_txn[penalty_offered].txid());
6534 let fee = revoked_htlc_txn[offered].output[0].value - node_txn[penalty_offered].output[0].value;
6535 let new_feerate = fee * 1000 / node_txn[penalty_offered].get_weight() as u64;
6536 assert!(new_feerate * 100 > feerate_1 * 125);
6538 check_spends!(node_txn[penalty_received], revoked_htlc_txn[received].clone());
6539 assert_ne!(second, node_txn[penalty_received].txid());
6540 let fee = revoked_htlc_txn[received].output[0].value - node_txn[penalty_received].output[0].value;
6541 let new_feerate = fee * 1000 / node_txn[penalty_received].get_weight() as u64;
6542 assert!(new_feerate * 100 > feerate_2 * 125);
6543 let txn = vec![node_txn[2].clone(), node_txn[3].clone(), node_txn[4].clone()];
6547 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
6548 let header_133 = BlockHeader { version: 0x20000000, prev_blockhash: header_132, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6549 nodes[0].block_notifier.block_connected(&Block { header: header_133, txdata: node_txn }, 133);
6550 let header_140 = connect_blocks(&nodes[0].block_notifier, 6, 134, true, header_133.bitcoin_hash());
6552 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6556 // Connect few more blocks and check only penalty transaction for to_local output have been issued
6557 connect_blocks(&nodes[0].block_notifier, 7, 140, true, header_140);
6559 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6560 assert_eq!(node_txn.len(), 2); //TODO: should be zero when we fix check_spend_remote_htlc
6563 check_closed_broadcast!(nodes[0], false);
6567 fn test_bump_penalty_txn_on_remote_commitment() {
6568 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
6569 // we're able to claim outputs on remote commitment transaction before timelocks expiration
6572 // Provide preimage for one
6573 // Check aggregation
6575 let nodes = create_network(2, &[None, None]);
6577 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6578 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6579 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
6581 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6582 let remote_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6583 assert_eq!(remote_txn[0].output.len(), 4);
6584 assert_eq!(remote_txn[0].input.len(), 1);
6585 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
6587 // Claim a HTLC without revocation (provide B monitor with preimage)
6588 nodes[1].node.claim_funds(payment_preimage, 3_000_000);
6589 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6590 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
6591 check_added_monitors!(nodes[1], 1);
6593 // One or more claim tx should have been broadcast, check it
6596 let feerate_timeout;
6597 let feerate_preimage;
6599 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6600 assert_eq!(node_txn.len(), 7); // 2 * claim tx (broadcasted from ChannelMonitor) * 2 (block-reparsing) + local commitment tx + local HTLC-timeout + HTLC-success (broadcasted from ChannelManager)
6601 assert_eq!(node_txn[0], node_txn[5]);
6602 assert_eq!(node_txn[1], node_txn[6]);
6603 assert_eq!(node_txn[0].input.len(), 1);
6604 assert_eq!(node_txn[1].input.len(), 1);
6605 check_spends!(node_txn[0], remote_txn[0].clone());
6606 check_spends!(node_txn[1], remote_txn[0].clone());
6607 check_spends!(node_txn[2], chan.3);
6608 check_spends!(node_txn[3], node_txn[2]);
6609 check_spends!(node_txn[4], node_txn[2]);
6610 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6611 timeout = node_txn[0].txid();
6612 let index = node_txn[0].input[0].previous_output.vout;
6613 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
6614 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
6616 preimage = node_txn[1].txid();
6617 let index = node_txn[1].input[0].previous_output.vout;
6618 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
6619 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
6621 timeout = node_txn[1].txid();
6622 let index = node_txn[1].input[0].previous_output.vout;
6623 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
6624 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
6626 preimage = node_txn[0].txid();
6627 let index = node_txn[0].input[0].previous_output.vout;
6628 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
6629 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
6633 assert_ne!(feerate_timeout, 0);
6634 assert_ne!(feerate_preimage, 0);
6636 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
6637 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
6639 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6640 assert_eq!(node_txn.len(), 2);
6641 assert_eq!(node_txn[0].input.len(), 1);
6642 assert_eq!(node_txn[1].input.len(), 1);
6643 check_spends!(node_txn[0], remote_txn[0].clone());
6644 check_spends!(node_txn[1], remote_txn[0].clone());
6645 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6646 let index = node_txn[0].input[0].previous_output.vout;
6647 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
6648 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
6649 assert!(new_feerate * 100 > feerate_timeout * 125);
6650 assert_ne!(timeout, node_txn[0].txid());
6652 let index = node_txn[1].input[0].previous_output.vout;
6653 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
6654 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
6655 assert!(new_feerate * 100 > feerate_preimage * 125);
6656 assert_ne!(preimage, node_txn[1].txid());
6658 let index = node_txn[1].input[0].previous_output.vout;
6659 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
6660 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
6661 assert!(new_feerate * 100 > feerate_timeout * 125);
6662 assert_ne!(timeout, node_txn[1].txid());
6664 let index = node_txn[0].input[0].previous_output.vout;
6665 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
6666 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
6667 assert!(new_feerate * 100 > feerate_preimage * 125);
6668 assert_ne!(preimage, node_txn[0].txid());
6673 nodes[1].node.get_and_clear_pending_events();
6674 nodes[1].node.get_and_clear_pending_msg_events();
6678 fn test_set_outpoints_partial_claiming() {
6679 // - remote party claim tx, new bump tx
6680 // - disconnect remote claiming tx, new bump
6681 // - disconnect tx, see no tx anymore
6682 let nodes = create_network(2, &[None, None]);
6684 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6685 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6686 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6688 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
6689 let remote_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6690 assert_eq!(remote_txn.len(), 3);
6691 assert_eq!(remote_txn[0].output.len(), 4);
6692 assert_eq!(remote_txn[0].input.len(), 1);
6693 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
6694 check_spends!(remote_txn[1], remote_txn[0].clone());
6695 check_spends!(remote_txn[2], remote_txn[0].clone());
6697 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
6698 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
6699 // Provide node A with both preimage
6700 nodes[0].node.claim_funds(payment_preimage_1, 3_000_000);
6701 nodes[0].node.claim_funds(payment_preimage_2, 3_000_000);
6702 check_added_monitors!(nodes[0], 2);
6703 nodes[0].node.get_and_clear_pending_events();
6704 nodes[0].node.get_and_clear_pending_msg_events();
6706 // Connect blocks on node A commitment transaction
6707 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6708 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
6709 // Verify node A broadcast tx claiming both HTLCs
6711 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6712 assert_eq!(node_txn.len(), 5);
6713 assert_eq!(node_txn[0], node_txn[4]);
6714 check_spends!(node_txn[0], remote_txn[0].clone());
6715 check_spends!(node_txn[1], chan.3.clone());
6716 check_spends!(node_txn[2], node_txn[1]);
6717 check_spends!(node_txn[3], node_txn[1]);
6718 assert_eq!(node_txn[0].input.len(), 2);
6721 nodes[0].node.get_and_clear_pending_msg_events();
6723 // Connect blocks on node B
6724 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
6725 // Verify node B broadcast 2 HTLC-timeout txn
6726 let partial_claim_tx = {
6727 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6728 assert_eq!(node_txn.len(), 3);
6729 check_spends!(node_txn[1], node_txn[0].clone());
6730 check_spends!(node_txn[2], node_txn[0].clone());
6731 assert_eq!(node_txn[1].input.len(), 1);
6732 assert_eq!(node_txn[2].input.len(), 1);
6735 nodes[1].node.get_and_clear_pending_msg_events();
6737 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
6738 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6739 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
6741 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6742 assert_eq!(node_txn.len(), 1);
6743 check_spends!(node_txn[0], remote_txn[0].clone());
6744 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
6747 nodes[0].node.get_and_clear_pending_msg_events();
6749 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
6750 nodes[0].block_notifier.block_disconnected(&header, 102);
6752 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6753 assert_eq!(node_txn.len(), 1);
6754 check_spends!(node_txn[0], remote_txn[0].clone());
6755 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
6759 //// Disconnect one more block and then reconnect multiple no transaction should be generated
6760 nodes[0].block_notifier.block_disconnected(&header, 101);
6761 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
6763 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6764 assert_eq!(node_txn.len(), 0);
6770 fn test_bump_txn_sanitize_tracking_maps() {
6771 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
6772 // verify we clean then right after expiration of ANTI_REORG_DELAY.
6774 let nodes = create_network(2, &[None, None]);
6776 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, Features::<FeatureContextInit>::new(), Features::<FeatureContextInit>::new());
6777 // Lock HTLC in both directions
6778 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
6779 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
6781 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6782 assert_eq!(revoked_local_txn[0].input.len(), 1);
6783 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
6785 // Revoke local commitment tx
6786 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
6788 // Broadcast set of revoked txn on A
6789 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
6790 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6791 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
6792 check_closed_broadcast!(nodes[0], false);
6794 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6795 assert_eq!(node_txn.len(), 7);
6796 check_spends!(node_txn[0], revoked_local_txn[0].clone());
6797 check_spends!(node_txn[1], revoked_local_txn[0].clone());
6798 check_spends!(node_txn[2], revoked_local_txn[0].clone());
6799 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
6803 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6804 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
6805 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
6807 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
6808 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
6809 assert!(monitor.pending_claim_requests.is_empty());
6810 assert!(monitor.claimable_outpoints.is_empty());