Do not panic if a peer learns our funding info before we fund
[rust-lightning] / lightning / src / ln / functional_tests.rs
1 // This file is Copyright its original authors, visible in version control
2 // history.
3 //
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
8 // licenses.
9
10 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
11 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
12 //! claim outputs on-chain.
13
14 use crate::chain;
15 use crate::chain::{ChannelMonitorUpdateStatus, Confirm, Listen, Watch};
16 use crate::chain::chaininterface::LowerBoundedFeeEstimator;
17 use crate::chain::channelmonitor;
18 use crate::chain::channelmonitor::{CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
19 use crate::chain::transaction::OutPoint;
20 use crate::sign::{ecdsa::EcdsaChannelSigner, EntropySource, SignerProvider};
21 use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
22 use crate::ln::{ChannelId, PaymentPreimage, PaymentSecret, PaymentHash};
23 use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT, get_holder_selected_channel_reserve_satoshis, OutboundV1Channel, InboundV1Channel, COINBASE_MATURITY, ChannelPhase};
24 use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, ENABLE_GOSSIP_TICKS, DISABLE_GOSSIP_TICKS, MIN_CLTV_EXPIRY_DELTA};
25 use crate::ln::channel::{DISCONNECT_PEER_AWAITING_RESPONSE_TICKS, ChannelError};
26 use crate::ln::{chan_utils, onion_utils};
27 use crate::ln::chan_utils::{OFFERED_HTLC_SCRIPT_WEIGHT, htlc_success_tx_weight, htlc_timeout_tx_weight, HTLCOutputInCommitment};
28 use crate::routing::gossip::{NetworkGraph, NetworkUpdate};
29 use crate::routing::router::{Path, PaymentParameters, Route, RouteHop, get_route, RouteParameters};
30 use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, NodeFeatures};
31 use crate::ln::msgs;
32 use crate::ln::msgs::{ChannelMessageHandler, RoutingMessageHandler, ErrorAction};
33 use crate::util::test_channel_signer::TestChannelSigner;
34 use crate::util::test_utils::{self, WatchtowerPersister};
35 use crate::util::errors::APIError;
36 use crate::util::ser::{Writeable, ReadableArgs};
37 use crate::util::string::UntrustedString;
38 use crate::util::config::{UserConfig, MaxDustHTLCExposure};
39
40 use bitcoin::hash_types::BlockHash;
41 use bitcoin::blockdata::locktime::absolute::LockTime;
42 use bitcoin::blockdata::script::{Builder, ScriptBuf};
43 use bitcoin::blockdata::opcodes;
44 use bitcoin::blockdata::constants::ChainHash;
45 use bitcoin::network::constants::Network;
46 use bitcoin::{Sequence, Transaction, TxIn, TxOut, Witness};
47 use bitcoin::OutPoint as BitcoinOutPoint;
48
49 use bitcoin::secp256k1::Secp256k1;
50 use bitcoin::secp256k1::{PublicKey,SecretKey};
51
52 use regex;
53
54 use crate::io;
55 use crate::prelude::*;
56 use alloc::collections::BTreeSet;
57 use core::default::Default;
58 use core::iter::repeat;
59 use bitcoin::hashes::Hash;
60 use crate::sync::{Arc, Mutex, RwLock};
61
62 use crate::ln::functional_test_utils::*;
63 use crate::ln::chan_utils::CommitmentTransaction;
64
65 use super::channel::UNFUNDED_CHANNEL_AGE_LIMIT_TICKS;
66
67 #[test]
68 fn test_insane_channel_opens() {
69         // Stand up a network of 2 nodes
70         use crate::ln::channel::TOTAL_BITCOIN_SUPPLY_SATOSHIS;
71         let mut cfg = UserConfig::default();
72         cfg.channel_handshake_limits.max_funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1;
73         let chanmon_cfgs = create_chanmon_cfgs(2);
74         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
75         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(cfg)]);
76         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
77
78         // Instantiate channel parameters where we push the maximum msats given our
79         // funding satoshis
80         let channel_value_sat = 31337; // same as funding satoshis
81         let channel_reserve_satoshis = get_holder_selected_channel_reserve_satoshis(channel_value_sat, &cfg);
82         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
83
84         // Have node0 initiate a channel to node1 with aforementioned parameters
85         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None, None).unwrap();
86
87         // Extract the channel open message from node0 to node1
88         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
89
90         // Test helper that asserts we get the correct error string given a mutator
91         // that supposedly makes the channel open message insane
92         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
93                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &message_mutator(open_channel_message.clone()));
94                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
95                 assert_eq!(msg_events.len(), 1);
96                 let expected_regex = regex::Regex::new(expected_error_str).unwrap();
97                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
98                         match action {
99                                 &ErrorAction::SendErrorMessage { .. } => {
100                                         nodes[1].logger.assert_log_regex("lightning::ln::channelmanager", expected_regex, 1);
101                                 },
102                                 _ => panic!("unexpected event!"),
103                         }
104                 } else { assert!(false); }
105         };
106
107         use crate::ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
108
109         // Test all mutations that would make the channel open message insane
110         insane_open_helper(format!("Per our config, funding must be at most {}. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS + 1, TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS + 2; msg });
111         insane_open_helper(format!("Funding must be smaller than the total bitcoin supply. It was {}", TOTAL_BITCOIN_SUPPLY_SATOSHIS).as_str(), |mut msg| { msg.funding_satoshis = TOTAL_BITCOIN_SUPPLY_SATOSHIS; msg });
112
113         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
114
115         insane_open_helper(r"push_msat \d+ was larger than channel amount minus reserve \(\d+\)", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
116
117         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
118
119         insane_open_helper(r"Minimum htlc value \(\d+\) was larger than full channel value \(\d+\)", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
120
121         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 });
122
123         insane_open_helper("0 max_accepted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
124
125         insane_open_helper("max_accepted_htlcs was 484. It must not be larger than 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
126 }
127
128 #[test]
129 fn test_funding_exceeds_no_wumbo_limit() {
130         // Test that if a peer does not support wumbo channels, we'll refuse to open a wumbo channel to
131         // them.
132         use crate::ln::channel::MAX_FUNDING_SATOSHIS_NO_WUMBO;
133         let chanmon_cfgs = create_chanmon_cfgs(2);
134         let mut node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
135         *node_cfgs[1].override_init_features.borrow_mut() = Some(channelmanager::provided_init_features(&test_default_channel_config()).clear_wumbo());
136         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
137         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
138
139         match nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), MAX_FUNDING_SATOSHIS_NO_WUMBO + 1, 0, 42, None, None) {
140                 Err(APIError::APIMisuseError { err }) => {
141                         assert_eq!(format!("funding_value must not exceed {}, it was {}", MAX_FUNDING_SATOSHIS_NO_WUMBO, MAX_FUNDING_SATOSHIS_NO_WUMBO + 1), err);
142                 },
143                 _ => panic!()
144         }
145 }
146
147 fn do_test_counterparty_no_reserve(send_from_initiator: bool) {
148         // A peer providing a channel_reserve_satoshis of 0 (or less than our dust limit) is insecure,
149         // but only for them. Because some LSPs do it with some level of trust of the clients (for a
150         // substantial UX improvement), we explicitly allow it. Because it's unlikely to happen often
151         // in normal testing, we test it explicitly here.
152         let chanmon_cfgs = create_chanmon_cfgs(2);
153         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
154         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
155         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
156         let default_config = UserConfig::default();
157
158         // Have node0 initiate a channel to node1 with aforementioned parameters
159         let mut push_amt = 100_000_000;
160         let feerate_per_kw = 253;
161         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
162         push_amt -= feerate_per_kw as u64 * (commitment_tx_base_weight(&channel_type_features) + 4 * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000 * 1000;
163         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
164
165         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, if send_from_initiator { 0 } else { push_amt }, 42, None, None).unwrap();
166         let mut open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
167         if !send_from_initiator {
168                 open_channel_message.channel_reserve_satoshis = 0;
169                 open_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
170         }
171         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
172
173         // Extract the channel accept message from node1 to node0
174         let mut accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
175         if send_from_initiator {
176                 accept_channel_message.channel_reserve_satoshis = 0;
177                 accept_channel_message.max_htlc_value_in_flight_msat = 100_000_000;
178         }
179         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
180         {
181                 let sender_node = if send_from_initiator { &nodes[1] } else { &nodes[0] };
182                 let counterparty_node = if send_from_initiator { &nodes[0] } else { &nodes[1] };
183                 let mut sender_node_per_peer_lock;
184                 let mut sender_node_peer_state_lock;
185
186                 let channel_phase = get_channel_ref!(sender_node, counterparty_node, sender_node_per_peer_lock, sender_node_peer_state_lock, temp_channel_id);
187                 match channel_phase {
188                         ChannelPhase::UnfundedInboundV1(_) | ChannelPhase::UnfundedOutboundV1(_) => {
189                                 let chan_context = channel_phase.context_mut();
190                                 chan_context.holder_selected_channel_reserve_satoshis = 0;
191                                 chan_context.holder_max_htlc_value_in_flight_msat = 100_000_000;
192                         },
193                         ChannelPhase::Funded(_) => assert!(false),
194                 }
195         }
196
197         let funding_tx = sign_funding_transaction(&nodes[0], &nodes[1], 100_000, temp_channel_id);
198         let funding_msgs = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &funding_tx);
199         create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_msgs.0);
200
201         // nodes[0] should now be able to send the full balance to nodes[1], violating nodes[1]'s
202         // security model if it ever tries to send funds back to nodes[0] (but that's not our problem).
203         if send_from_initiator {
204                 send_payment(&nodes[0], &[&nodes[1]], 100_000_000
205                         // Note that for outbound channels we have to consider the commitment tx fee and the
206                         // "fee spike buffer", which is currently a multiple of the total commitment tx fee as
207                         // well as an additional HTLC.
208                         - FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE * commit_tx_fee_msat(feerate_per_kw, 2, &channel_type_features));
209         } else {
210                 send_payment(&nodes[1], &[&nodes[0]], push_amt);
211         }
212 }
213
214 #[test]
215 fn test_counterparty_no_reserve() {
216         do_test_counterparty_no_reserve(true);
217         do_test_counterparty_no_reserve(false);
218 }
219
220 #[test]
221 fn test_async_inbound_update_fee() {
222         let chanmon_cfgs = create_chanmon_cfgs(2);
223         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
224         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
225         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
226         create_announced_chan_between_nodes(&nodes, 0, 1);
227
228         // balancing
229         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
230
231         // A                                        B
232         // update_fee                            ->
233         // send (1) commitment_signed            -.
234         //                                       <- update_add_htlc/commitment_signed
235         // send (2) RAA (awaiting remote revoke) -.
236         // (1) commitment_signed is delivered    ->
237         //                                       .- send (3) RAA (awaiting remote revoke)
238         // (2) RAA is delivered                  ->
239         //                                       .- send (4) commitment_signed
240         //                                       <- (3) RAA is delivered
241         // send (5) commitment_signed            -.
242         //                                       <- (4) commitment_signed is delivered
243         // send (6) RAA                          -.
244         // (5) commitment_signed is delivered    ->
245         //                                       <- RAA
246         // (6) RAA is delivered                  ->
247
248         // First nodes[0] generates an update_fee
249         {
250                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
251                 *feerate_lock += 20;
252         }
253         nodes[0].node.timer_tick_occurred();
254         check_added_monitors!(nodes[0], 1);
255
256         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
257         assert_eq!(events_0.len(), 1);
258         let (update_msg, commitment_signed) = match events_0[0] { // (1)
259                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
260                         (update_fee.as_ref(), commitment_signed)
261                 },
262                 _ => panic!("Unexpected event"),
263         };
264
265         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
266
267         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
268         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
269         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
270                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
271         check_added_monitors!(nodes[1], 1);
272
273         let payment_event = {
274                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
275                 assert_eq!(events_1.len(), 1);
276                 SendEvent::from_event(events_1.remove(0))
277         };
278         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
279         assert_eq!(payment_event.msgs.len(), 1);
280
281         // ...now when the messages get delivered everyone should be happy
282         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
283         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
284         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
285         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
286         check_added_monitors!(nodes[0], 1);
287
288         // deliver(1), generate (3):
289         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
290         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
291         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
292         check_added_monitors!(nodes[1], 1);
293
294         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
295         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
296         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
297         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
298         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
299         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
300         assert!(bs_update.update_fee.is_none()); // (4)
301         check_added_monitors!(nodes[1], 1);
302
303         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
304         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
305         assert!(as_update.update_add_htlcs.is_empty()); // (5)
306         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
307         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
308         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
309         assert!(as_update.update_fee.is_none()); // (5)
310         check_added_monitors!(nodes[0], 1);
311
312         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
313         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
314         // only (6) so get_event_msg's assert(len == 1) passes
315         check_added_monitors!(nodes[0], 1);
316
317         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
318         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
319         check_added_monitors!(nodes[1], 1);
320
321         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
322         check_added_monitors!(nodes[0], 1);
323
324         let events_2 = nodes[0].node.get_and_clear_pending_events();
325         assert_eq!(events_2.len(), 1);
326         match events_2[0] {
327                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
328                 _ => panic!("Unexpected event"),
329         }
330
331         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
332         check_added_monitors!(nodes[1], 1);
333 }
334
335 #[test]
336 fn test_update_fee_unordered_raa() {
337         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
338         // crash in an earlier version of the update_fee patch)
339         let chanmon_cfgs = create_chanmon_cfgs(2);
340         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
341         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
342         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
343         create_announced_chan_between_nodes(&nodes, 0, 1);
344
345         // balancing
346         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
347
348         // First nodes[0] generates an update_fee
349         {
350                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
351                 *feerate_lock += 20;
352         }
353         nodes[0].node.timer_tick_occurred();
354         check_added_monitors!(nodes[0], 1);
355
356         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
357         assert_eq!(events_0.len(), 1);
358         let update_msg = match events_0[0] { // (1)
359                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
360                         update_fee.as_ref()
361                 },
362                 _ => panic!("Unexpected event"),
363         };
364
365         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
366
367         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
368         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 40000);
369         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
370                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
371         check_added_monitors!(nodes[1], 1);
372
373         let payment_event = {
374                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
375                 assert_eq!(events_1.len(), 1);
376                 SendEvent::from_event(events_1.remove(0))
377         };
378         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
379         assert_eq!(payment_event.msgs.len(), 1);
380
381         // ...now when the messages get delivered everyone should be happy
382         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
383         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
384         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
385         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
386         check_added_monitors!(nodes[0], 1);
387
388         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
389         check_added_monitors!(nodes[1], 1);
390
391         // We can't continue, sadly, because our (1) now has a bogus signature
392 }
393
394 #[test]
395 fn test_multi_flight_update_fee() {
396         let chanmon_cfgs = create_chanmon_cfgs(2);
397         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
398         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
399         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
400         create_announced_chan_between_nodes(&nodes, 0, 1);
401
402         // A                                        B
403         // update_fee/commitment_signed          ->
404         //                                       .- send (1) RAA and (2) commitment_signed
405         // update_fee (never committed)          ->
406         // (3) update_fee                        ->
407         // We have to manually generate the above update_fee, it is allowed by the protocol but we
408         // don't track which updates correspond to which revoke_and_ack responses so we're in
409         // AwaitingRAA mode and will not generate the update_fee yet.
410         //                                       <- (1) RAA delivered
411         // (3) is generated and send (4) CS      -.
412         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
413         // know the per_commitment_point to use for it.
414         //                                       <- (2) commitment_signed delivered
415         // revoke_and_ack                        ->
416         //                                          B should send no response here
417         // (4) commitment_signed delivered       ->
418         //                                       <- RAA/commitment_signed delivered
419         // revoke_and_ack                        ->
420
421         // First nodes[0] generates an update_fee
422         let initial_feerate;
423         {
424                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
425                 initial_feerate = *feerate_lock;
426                 *feerate_lock = initial_feerate + 20;
427         }
428         nodes[0].node.timer_tick_occurred();
429         check_added_monitors!(nodes[0], 1);
430
431         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
432         assert_eq!(events_0.len(), 1);
433         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
434                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
435                         (update_fee.as_ref().unwrap(), commitment_signed)
436                 },
437                 _ => panic!("Unexpected event"),
438         };
439
440         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
441         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
442         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
443         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
444         check_added_monitors!(nodes[1], 1);
445
446         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
447         // transaction:
448         {
449                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
450                 *feerate_lock = initial_feerate + 40;
451         }
452         nodes[0].node.timer_tick_occurred();
453         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
454         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
455
456         // Create the (3) update_fee message that nodes[0] will generate before it does...
457         let mut update_msg_2 = msgs::UpdateFee {
458                 channel_id: update_msg_1.channel_id.clone(),
459                 feerate_per_kw: (initial_feerate + 30) as u32,
460         };
461
462         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
463
464         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
465         // Deliver (3)
466         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
467
468         // Deliver (1), generating (3) and (4)
469         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
470         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
471         check_added_monitors!(nodes[0], 1);
472         assert!(as_second_update.update_add_htlcs.is_empty());
473         assert!(as_second_update.update_fulfill_htlcs.is_empty());
474         assert!(as_second_update.update_fail_htlcs.is_empty());
475         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
476         // Check that the update_fee newly generated matches what we delivered:
477         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
478         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
479
480         // Deliver (2) commitment_signed
481         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
482         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
483         check_added_monitors!(nodes[0], 1);
484         // No commitment_signed so get_event_msg's assert(len == 1) passes
485
486         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
487         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
488         check_added_monitors!(nodes[1], 1);
489
490         // Delever (4)
491         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
492         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
493         check_added_monitors!(nodes[1], 1);
494
495         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
496         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
497         check_added_monitors!(nodes[0], 1);
498
499         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
500         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
501         // No commitment_signed so get_event_msg's assert(len == 1) passes
502         check_added_monitors!(nodes[0], 1);
503
504         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
505         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
506         check_added_monitors!(nodes[1], 1);
507 }
508
509 fn do_test_sanity_on_in_flight_opens(steps: u8) {
510         // Previously, we had issues deserializing channels when we hadn't connected the first block
511         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
512         // serialization round-trips and simply do steps towards opening a channel and then drop the
513         // Node objects.
514
515         let chanmon_cfgs = create_chanmon_cfgs(2);
516         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
517         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
518         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
519
520         if steps & 0b1000_0000 != 0{
521                 let block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
522                 connect_block(&nodes[0], &block);
523                 connect_block(&nodes[1], &block);
524         }
525
526         if steps & 0x0f == 0 { return; }
527         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
528         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
529
530         if steps & 0x0f == 1 { return; }
531         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
532         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
533
534         if steps & 0x0f == 2 { return; }
535         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
536
537         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
538
539         if steps & 0x0f == 3 { return; }
540         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
541         check_added_monitors!(nodes[0], 0);
542         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
543
544         if steps & 0x0f == 4 { return; }
545         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
546         {
547                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
548                 assert_eq!(added_monitors.len(), 1);
549                 assert_eq!(added_monitors[0].0, funding_output);
550                 added_monitors.clear();
551         }
552         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
553
554         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
555
556         if steps & 0x0f == 5 { return; }
557         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
558         {
559                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
560                 assert_eq!(added_monitors.len(), 1);
561                 assert_eq!(added_monitors[0].0, funding_output);
562                 added_monitors.clear();
563         }
564
565         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
566         let events_4 = nodes[0].node.get_and_clear_pending_events();
567         assert_eq!(events_4.len(), 0);
568
569         if steps & 0x0f == 6 { return; }
570         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx, 2);
571
572         if steps & 0x0f == 7 { return; }
573         confirm_transaction_at(&nodes[0], &tx, 2);
574         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
575         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
576         expect_channel_ready_event(&nodes[0], &nodes[1].node.get_our_node_id());
577 }
578
579 #[test]
580 fn test_sanity_on_in_flight_opens() {
581         do_test_sanity_on_in_flight_opens(0);
582         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
583         do_test_sanity_on_in_flight_opens(1);
584         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
585         do_test_sanity_on_in_flight_opens(2);
586         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
587         do_test_sanity_on_in_flight_opens(3);
588         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
589         do_test_sanity_on_in_flight_opens(4);
590         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
591         do_test_sanity_on_in_flight_opens(5);
592         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
593         do_test_sanity_on_in_flight_opens(6);
594         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
595         do_test_sanity_on_in_flight_opens(7);
596         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
597         do_test_sanity_on_in_flight_opens(8);
598         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
599 }
600
601 #[test]
602 fn test_update_fee_vanilla() {
603         let chanmon_cfgs = create_chanmon_cfgs(2);
604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
607         create_announced_chan_between_nodes(&nodes, 0, 1);
608
609         {
610                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
611                 *feerate_lock += 25;
612         }
613         nodes[0].node.timer_tick_occurred();
614         check_added_monitors!(nodes[0], 1);
615
616         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
617         assert_eq!(events_0.len(), 1);
618         let (update_msg, commitment_signed) = match events_0[0] {
619                         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 } } => {
620                         (update_fee.as_ref(), commitment_signed)
621                 },
622                 _ => panic!("Unexpected event"),
623         };
624         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
625
626         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
627         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
628         check_added_monitors!(nodes[1], 1);
629
630         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
631         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
632         check_added_monitors!(nodes[0], 1);
633
634         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
635         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
636         // No commitment_signed so get_event_msg's assert(len == 1) passes
637         check_added_monitors!(nodes[0], 1);
638
639         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
640         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
641         check_added_monitors!(nodes[1], 1);
642 }
643
644 #[test]
645 fn test_update_fee_that_funder_cannot_afford() {
646         let chanmon_cfgs = create_chanmon_cfgs(2);
647         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
648         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
649         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
650         let channel_value = 5000;
651         let push_sats = 700;
652         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, push_sats * 1000);
653         let channel_id = chan.2;
654         let secp_ctx = Secp256k1::new();
655         let default_config = UserConfig::default();
656         let bs_channel_reserve_sats = get_holder_selected_channel_reserve_satoshis(channel_value, &default_config);
657
658         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
659
660         // Calculate the maximum feerate that A can afford. Note that we don't send an update_fee
661         // CONCURRENT_INBOUND_HTLC_FEE_BUFFER HTLCs before actually running out of local balance, so we
662         // calculate two different feerates here - the expected local limit as well as the expected
663         // remote limit.
664         let feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / (commitment_tx_base_weight(&channel_type_features) + CONCURRENT_INBOUND_HTLC_FEE_BUFFER as u64 * COMMITMENT_TX_WEIGHT_PER_HTLC)) as u32;
665         let non_buffer_feerate = ((channel_value - bs_channel_reserve_sats - push_sats) * 1000 / commitment_tx_base_weight(&channel_type_features)) as u32;
666         {
667                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
668                 *feerate_lock = feerate;
669         }
670         nodes[0].node.timer_tick_occurred();
671         check_added_monitors!(nodes[0], 1);
672         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
673
674         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
675
676         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
677
678         // Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate set above.
679         {
680                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
681
682                 //We made sure neither party's funds are below the dust limit and there are no HTLCs here
683                 assert_eq!(commitment_tx.output.len(), 2);
684                 let total_fee: u64 = commit_tx_fee_msat(feerate, 0, &channel_type_features) / 1000;
685                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
686                 actual_fee = channel_value - actual_fee;
687                 assert_eq!(total_fee, actual_fee);
688         }
689
690         {
691                 // Increment the feerate by a small constant, accounting for rounding errors
692                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
693                 *feerate_lock += 4;
694         }
695         nodes[0].node.timer_tick_occurred();
696         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot afford to send new feerate at {}", feerate + 4), 1);
697         check_added_monitors!(nodes[0], 0);
698
699         const INITIAL_COMMITMENT_NUMBER: u64 = 281474976710654;
700
701         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
702         // needed to sign the new commitment tx and (2) sign the new commitment tx.
703         let (local_revocation_basepoint, local_htlc_basepoint, local_funding) = {
704                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
705                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
706                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
707                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
708                 ).flatten().unwrap();
709                 let chan_signer = local_chan.get_signer();
710                 let pubkeys = chan_signer.as_ref().pubkeys();
711                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
712                  pubkeys.funding_pubkey)
713         };
714         let (remote_delayed_payment_basepoint, remote_htlc_basepoint,remote_point, remote_funding) = {
715                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
716                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
717                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
718                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
719                 ).flatten().unwrap();
720                 let chan_signer = remote_chan.get_signer();
721                 let pubkeys = chan_signer.as_ref().pubkeys();
722                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
723                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
724                  pubkeys.funding_pubkey)
725         };
726
727         // Assemble the set of keys we can use for signatures for our commitment_signed message.
728         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
729                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
730
731         let res = {
732                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
733                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
734                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
735                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
736                 ).flatten().unwrap();
737                 let local_chan_signer = local_chan.get_signer();
738                 let mut htlcs: Vec<(HTLCOutputInCommitment, ())> = vec![];
739                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
740                         INITIAL_COMMITMENT_NUMBER - 1,
741                         push_sats,
742                         channel_value - push_sats - commit_tx_fee_msat(non_buffer_feerate + 4, 0, &channel_type_features) / 1000,
743                         local_funding, remote_funding,
744                         commit_tx_keys.clone(),
745                         non_buffer_feerate + 4,
746                         &mut htlcs,
747                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
748                 );
749                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
750         };
751
752         let commit_signed_msg = msgs::CommitmentSigned {
753                 channel_id: chan.2,
754                 signature: res.0,
755                 htlc_signatures: res.1,
756                 #[cfg(taproot)]
757                 partial_signature_with_nonce: None,
758         };
759
760         let update_fee = msgs::UpdateFee {
761                 channel_id: chan.2,
762                 feerate_per_kw: non_buffer_feerate + 4,
763         };
764
765         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_fee);
766
767         //While producing the commitment_signed response after handling a received update_fee request the
768         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
769         //Should produce and error.
770         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
771         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Funding remote cannot afford proposed new fee", 3);
772         check_added_monitors!(nodes[1], 1);
773         check_closed_broadcast!(nodes[1], true);
774         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: String::from("Funding remote cannot afford proposed new fee") },
775                 [nodes[0].node.get_our_node_id()], channel_value);
776 }
777
778 #[test]
779 fn test_update_fee_with_fundee_update_add_htlc() {
780         let chanmon_cfgs = create_chanmon_cfgs(2);
781         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
782         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
783         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
784         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
785
786         // balancing
787         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
788
789         {
790                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
791                 *feerate_lock += 20;
792         }
793         nodes[0].node.timer_tick_occurred();
794         check_added_monitors!(nodes[0], 1);
795
796         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
797         assert_eq!(events_0.len(), 1);
798         let (update_msg, commitment_signed) = match events_0[0] {
799                         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 } } => {
800                         (update_fee.as_ref(), commitment_signed)
801                 },
802                 _ => panic!("Unexpected event"),
803         };
804         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
805         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
806         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
807         check_added_monitors!(nodes[1], 1);
808
809         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 800000);
810
811         // nothing happens since node[1] is in AwaitingRemoteRevoke
812         nodes[1].node.send_payment_with_route(&route, our_payment_hash,
813                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
814         {
815                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
816                 assert_eq!(added_monitors.len(), 0);
817                 added_monitors.clear();
818         }
819         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
820         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
821         // node[1] has nothing to do
822
823         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
824         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
825         check_added_monitors!(nodes[0], 1);
826
827         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
828         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
829         // No commitment_signed so get_event_msg's assert(len == 1) passes
830         check_added_monitors!(nodes[0], 1);
831         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
832         check_added_monitors!(nodes[1], 1);
833         // AwaitingRemoteRevoke ends here
834
835         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
837         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
838         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
839         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
840         assert_eq!(commitment_update.update_fee.is_none(), true);
841
842         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
843         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
844         check_added_monitors!(nodes[0], 1);
845         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
846
847         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
848         check_added_monitors!(nodes[1], 1);
849         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
850
851         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
852         check_added_monitors!(nodes[1], 1);
853         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
854         // No commitment_signed so get_event_msg's assert(len == 1) passes
855
856         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
857         check_added_monitors!(nodes[0], 1);
858         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
859
860         expect_pending_htlcs_forwardable!(nodes[0]);
861
862         let events = nodes[0].node.get_and_clear_pending_events();
863         assert_eq!(events.len(), 1);
864         match events[0] {
865                 Event::PaymentClaimable { .. } => { },
866                 _ => panic!("Unexpected event"),
867         };
868
869         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
870
871         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
872         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
873         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
874         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
875         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
876 }
877
878 #[test]
879 fn test_update_fee() {
880         let chanmon_cfgs = create_chanmon_cfgs(2);
881         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
882         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
883         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
884         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
885         let channel_id = chan.2;
886
887         // A                                        B
888         // (1) update_fee/commitment_signed      ->
889         //                                       <- (2) revoke_and_ack
890         //                                       .- send (3) commitment_signed
891         // (4) update_fee/commitment_signed      ->
892         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
893         //                                       <- (3) commitment_signed delivered
894         // send (6) revoke_and_ack               -.
895         //                                       <- (5) deliver revoke_and_ack
896         // (6) deliver revoke_and_ack            ->
897         //                                       .- send (7) commitment_signed in response to (4)
898         //                                       <- (7) deliver commitment_signed
899         // revoke_and_ack                        ->
900
901         // Create and deliver (1)...
902         let feerate;
903         {
904                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
905                 feerate = *feerate_lock;
906                 *feerate_lock = feerate + 20;
907         }
908         nodes[0].node.timer_tick_occurred();
909         check_added_monitors!(nodes[0], 1);
910
911         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
912         assert_eq!(events_0.len(), 1);
913         let (update_msg, commitment_signed) = match events_0[0] {
914                         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 } } => {
915                         (update_fee.as_ref(), commitment_signed)
916                 },
917                 _ => panic!("Unexpected event"),
918         };
919         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
920
921         // Generate (2) and (3):
922         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
923         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
924         check_added_monitors!(nodes[1], 1);
925
926         // Deliver (2):
927         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
928         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
929         check_added_monitors!(nodes[0], 1);
930
931         // Create and deliver (4)...
932         {
933                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
934                 *feerate_lock = feerate + 30;
935         }
936         nodes[0].node.timer_tick_occurred();
937         check_added_monitors!(nodes[0], 1);
938         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
939         assert_eq!(events_0.len(), 1);
940         let (update_msg, commitment_signed) = match events_0[0] {
941                         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 } } => {
942                         (update_fee.as_ref(), commitment_signed)
943                 },
944                 _ => panic!("Unexpected event"),
945         };
946
947         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
948         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
949         check_added_monitors!(nodes[1], 1);
950         // ... creating (5)
951         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
952         // No commitment_signed so get_event_msg's assert(len == 1) passes
953
954         // Handle (3), creating (6):
955         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
956         check_added_monitors!(nodes[0], 1);
957         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
958         // No commitment_signed so get_event_msg's assert(len == 1) passes
959
960         // Deliver (5):
961         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
962         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
963         check_added_monitors!(nodes[0], 1);
964
965         // Deliver (6), creating (7):
966         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
967         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
968         assert!(commitment_update.update_add_htlcs.is_empty());
969         assert!(commitment_update.update_fulfill_htlcs.is_empty());
970         assert!(commitment_update.update_fail_htlcs.is_empty());
971         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
972         assert!(commitment_update.update_fee.is_none());
973         check_added_monitors!(nodes[1], 1);
974
975         // Deliver (7)
976         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
977         check_added_monitors!(nodes[0], 1);
978         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
979         // No commitment_signed so get_event_msg's assert(len == 1) passes
980
981         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
982         check_added_monitors!(nodes[1], 1);
983         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
984
985         assert_eq!(get_feerate!(nodes[0], nodes[1], channel_id), feerate + 30);
986         assert_eq!(get_feerate!(nodes[1], nodes[0], channel_id), feerate + 30);
987         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
988         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
989         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
990 }
991
992 #[test]
993 fn fake_network_test() {
994         // Simple test which builds a network of ChannelManagers, connects them to each other, and
995         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
996         let chanmon_cfgs = create_chanmon_cfgs(4);
997         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
998         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
999         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1000
1001         // Create some initial channels
1002         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1003         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1004         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1005
1006         // Rebalance the network a bit by relaying one payment through all the channels...
1007         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1008         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1009         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1010         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
1011
1012         // Send some more payments
1013         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1014         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1015         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1016
1017         // Test failure packets
1018         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1019         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1020
1021         // Add a new channel that skips 3
1022         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
1023
1024         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1025         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1026         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1027         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1028         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1029         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1030         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1031
1032         // Do some rebalance loop payments, simultaneously
1033         let mut hops = Vec::with_capacity(3);
1034         hops.push(RouteHop {
1035                 pubkey: nodes[2].node.get_our_node_id(),
1036                 node_features: NodeFeatures::empty(),
1037                 short_channel_id: chan_2.0.contents.short_channel_id,
1038                 channel_features: ChannelFeatures::empty(),
1039                 fee_msat: 0,
1040                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32,
1041                 maybe_announced_channel: true,
1042         });
1043         hops.push(RouteHop {
1044                 pubkey: nodes[3].node.get_our_node_id(),
1045                 node_features: NodeFeatures::empty(),
1046                 short_channel_id: chan_3.0.contents.short_channel_id,
1047                 channel_features: ChannelFeatures::empty(),
1048                 fee_msat: 0,
1049                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32,
1050                 maybe_announced_channel: true,
1051         });
1052         hops.push(RouteHop {
1053                 pubkey: nodes[1].node.get_our_node_id(),
1054                 node_features: nodes[1].node.node_features(),
1055                 short_channel_id: chan_4.0.contents.short_channel_id,
1056                 channel_features: nodes[1].node.channel_features(),
1057                 fee_msat: 1000000,
1058                 cltv_expiry_delta: TEST_FINAL_CLTV,
1059                 maybe_announced_channel: true,
1060         });
1061         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;
1062         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;
1063         let payment_preimage_1 = send_along_route(&nodes[1],
1064                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1065                         &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1066
1067         let mut hops = Vec::with_capacity(3);
1068         hops.push(RouteHop {
1069                 pubkey: nodes[3].node.get_our_node_id(),
1070                 node_features: NodeFeatures::empty(),
1071                 short_channel_id: chan_4.0.contents.short_channel_id,
1072                 channel_features: ChannelFeatures::empty(),
1073                 fee_msat: 0,
1074                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32,
1075                 maybe_announced_channel: true,
1076         });
1077         hops.push(RouteHop {
1078                 pubkey: nodes[2].node.get_our_node_id(),
1079                 node_features: NodeFeatures::empty(),
1080                 short_channel_id: chan_3.0.contents.short_channel_id,
1081                 channel_features: ChannelFeatures::empty(),
1082                 fee_msat: 0,
1083                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32,
1084                 maybe_announced_channel: true,
1085         });
1086         hops.push(RouteHop {
1087                 pubkey: nodes[1].node.get_our_node_id(),
1088                 node_features: nodes[1].node.node_features(),
1089                 short_channel_id: chan_2.0.contents.short_channel_id,
1090                 channel_features: nodes[1].node.channel_features(),
1091                 fee_msat: 1000000,
1092                 cltv_expiry_delta: TEST_FINAL_CLTV,
1093                 maybe_announced_channel: true,
1094         });
1095         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;
1096         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;
1097         let payment_hash_2 = send_along_route(&nodes[1],
1098                 Route { paths: vec![Path { hops, blinded_tail: None }], route_params: None },
1099                         &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1100
1101         // Claim the rebalances...
1102         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1103         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1104
1105         // Close down the channels...
1106         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1107         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1108         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
1109         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1110         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1111         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1112         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1113         check_closed_event!(nodes[2], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1114         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[2].node.get_our_node_id()], 100000);
1115         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1116         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[3].node.get_our_node_id()], 100000);
1117         check_closed_event!(nodes[3], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
1118 }
1119
1120 #[test]
1121 fn holding_cell_htlc_counting() {
1122         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1123         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1124         // commitment dance rounds.
1125         let chanmon_cfgs = create_chanmon_cfgs(3);
1126         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1127         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1128         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1129         create_announced_chan_between_nodes(&nodes, 0, 1);
1130         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1131
1132         // Fetch a route in advance as we will be unable to once we're unable to send.
1133         let (route, payment_hash_1, _, payment_secret_1) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1134
1135         let mut payments = Vec::new();
1136         for _ in 0..50 {
1137                 let (route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
1138                 nodes[1].node.send_payment_with_route(&route, payment_hash,
1139                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
1140                 payments.push((payment_preimage, payment_hash));
1141         }
1142         check_added_monitors!(nodes[1], 1);
1143
1144         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1145         assert_eq!(events.len(), 1);
1146         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1147         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1148
1149         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1150         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1151         // another HTLC.
1152         {
1153                 unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, payment_hash_1,
1154                                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)
1155                         ), true, APIError::ChannelUnavailable { .. }, {});
1156                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1157         }
1158
1159         // This should also be true if we try to forward a payment.
1160         let (route, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
1161         {
1162                 nodes[0].node.send_payment_with_route(&route, payment_hash_2,
1163                         RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
1164                 check_added_monitors!(nodes[0], 1);
1165         }
1166
1167         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1168         assert_eq!(events.len(), 1);
1169         let payment_event = SendEvent::from_event(events.pop().unwrap());
1170         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1171
1172         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1173         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1174         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1175         // fails), the second will process the resulting failure and fail the HTLC backward.
1176         expect_pending_htlcs_forwardable!(nodes[1]);
1177         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
1178         check_added_monitors!(nodes[1], 1);
1179
1180         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1181         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1182         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1183
1184         expect_payment_failed_with_update!(nodes[0], payment_hash_2, false, chan_2.0.contents.short_channel_id, false);
1185
1186         // Now forward all the pending HTLCs and claim them back
1187         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1188         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1189         check_added_monitors!(nodes[2], 1);
1190
1191         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1192         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1193         check_added_monitors!(nodes[1], 1);
1194         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1195
1196         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1197         check_added_monitors!(nodes[1], 1);
1198         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1199
1200         for ref update in as_updates.update_add_htlcs.iter() {
1201                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1202         }
1203         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1204         check_added_monitors!(nodes[2], 1);
1205         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1206         check_added_monitors!(nodes[2], 1);
1207         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1208
1209         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1210         check_added_monitors!(nodes[1], 1);
1211         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1212         check_added_monitors!(nodes[1], 1);
1213         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1214
1215         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1216         check_added_monitors!(nodes[2], 1);
1217
1218         expect_pending_htlcs_forwardable!(nodes[2]);
1219
1220         let events = nodes[2].node.get_and_clear_pending_events();
1221         assert_eq!(events.len(), payments.len());
1222         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1223                 match event {
1224                         &Event::PaymentClaimable { ref payment_hash, .. } => {
1225                                 assert_eq!(*payment_hash, *hash);
1226                         },
1227                         _ => panic!("Unexpected event"),
1228                 };
1229         }
1230
1231         for (preimage, _) in payments.drain(..) {
1232                 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1233         }
1234
1235         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1236 }
1237
1238 #[test]
1239 fn duplicate_htlc_test() {
1240         // Test that we accept duplicate payment_hash HTLCs across the network and that
1241         // claiming/failing them are all separate and don't affect each other
1242         let chanmon_cfgs = create_chanmon_cfgs(6);
1243         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1244         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1245         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1246
1247         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1248         create_announced_chan_between_nodes(&nodes, 0, 3);
1249         create_announced_chan_between_nodes(&nodes, 1, 3);
1250         create_announced_chan_between_nodes(&nodes, 2, 3);
1251         create_announced_chan_between_nodes(&nodes, 3, 4);
1252         create_announced_chan_between_nodes(&nodes, 3, 5);
1253
1254         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1255
1256         *nodes[0].network_payment_count.borrow_mut() -= 1;
1257         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1258
1259         *nodes[0].network_payment_count.borrow_mut() -= 1;
1260         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1261
1262         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1263         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1264         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1265 }
1266
1267 #[test]
1268 fn test_duplicate_htlc_different_direction_onchain() {
1269         // Test that ChannelMonitor doesn't generate 2 preimage txn
1270         // when we have 2 HTLCs with same preimage that go across a node
1271         // in opposite directions, even with the same payment secret.
1272         let chanmon_cfgs = create_chanmon_cfgs(2);
1273         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1274         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1275         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1276
1277         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1278
1279         // balancing
1280         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1281
1282         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1283
1284         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], 800_000);
1285         let node_a_payment_secret = nodes[0].node.create_inbound_payment_for_hash(payment_hash, None, 7200, None).unwrap();
1286         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[0]]], 800_000, payment_hash, node_a_payment_secret);
1287
1288         // Provide preimage to node 0 by claiming payment
1289         nodes[0].node.claim_funds(payment_preimage);
1290         expect_payment_claimed!(nodes[0], payment_hash, 800_000);
1291         check_added_monitors!(nodes[0], 1);
1292
1293         // Broadcast node 1 commitment txn
1294         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1295
1296         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1297         let mut has_both_htlcs = 0; // check htlcs match ones committed
1298         for outp in remote_txn[0].output.iter() {
1299                 if outp.value == 800_000 / 1000 {
1300                         has_both_htlcs += 1;
1301                 } else if outp.value == 900_000 / 1000 {
1302                         has_both_htlcs += 1;
1303                 }
1304         }
1305         assert_eq!(has_both_htlcs, 2);
1306
1307         mine_transaction(&nodes[0], &remote_txn[0]);
1308         check_added_monitors!(nodes[0], 1);
1309         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
1310         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
1311
1312         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1313         assert_eq!(claim_txn.len(), 3);
1314
1315         check_spends!(claim_txn[0], remote_txn[0]); // Immediate HTLC claim with preimage
1316         check_spends!(claim_txn[1], remote_txn[0]);
1317         check_spends!(claim_txn[2], remote_txn[0]);
1318         let preimage_tx = &claim_txn[0];
1319         let (preimage_bump_tx, timeout_tx) = if claim_txn[1].input[0].previous_output == preimage_tx.input[0].previous_output {
1320                 (&claim_txn[1], &claim_txn[2])
1321         } else {
1322                 (&claim_txn[2], &claim_txn[1])
1323         };
1324
1325         assert_eq!(preimage_tx.input.len(), 1);
1326         assert_eq!(preimage_bump_tx.input.len(), 1);
1327
1328         assert_eq!(preimage_tx.input.len(), 1);
1329         assert_eq!(preimage_tx.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1330         assert_eq!(remote_txn[0].output[preimage_tx.input[0].previous_output.vout as usize].value, 800);
1331
1332         assert_eq!(timeout_tx.input.len(), 1);
1333         assert_eq!(timeout_tx.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1334         check_spends!(timeout_tx, remote_txn[0]);
1335         assert_eq!(remote_txn[0].output[timeout_tx.input[0].previous_output.vout as usize].value, 900);
1336
1337         let events = nodes[0].node.get_and_clear_pending_msg_events();
1338         assert_eq!(events.len(), 3);
1339         for e in events {
1340                 match e {
1341                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1342                         MessageSendEvent::HandleError { node_id, action: msgs::ErrorAction::DisconnectPeer { ref msg } } => {
1343                                 assert_eq!(node_id, nodes[1].node.get_our_node_id());
1344                                 assert_eq!(msg.as_ref().unwrap().data, "Channel closed because commitment or closing transaction was confirmed on chain.");
1345                         },
1346                         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, .. } } => {
1347                                 assert!(update_add_htlcs.is_empty());
1348                                 assert!(update_fail_htlcs.is_empty());
1349                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1350                                 assert!(update_fail_malformed_htlcs.is_empty());
1351                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1352                         },
1353                         _ => panic!("Unexpected event"),
1354                 }
1355         }
1356 }
1357
1358 #[test]
1359 fn test_basic_channel_reserve() {
1360         let chanmon_cfgs = create_chanmon_cfgs(2);
1361         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1362         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1363         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1364         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1365
1366         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1367         let channel_reserve = chan_stat.channel_reserve_msat;
1368
1369         // The 2* and +1 are for the fee spike reserve.
1370         let commit_tx_fee = 2 * commit_tx_fee_msat(get_feerate!(nodes[0], nodes[1], chan.2), 1 + 1, &get_channel_type_features!(nodes[0], nodes[1], chan.2));
1371         let max_can_send = 5000000 - channel_reserve - commit_tx_fee;
1372         let (mut route, our_payment_hash, _, our_payment_secret) =
1373                 get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
1374         route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1375         let err = nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1376                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).err().unwrap();
1377         match err {
1378                 PaymentSendFailure::AllFailedResendSafe(ref fails) => {
1379                         if let &APIError::ChannelUnavailable { .. } = &fails[0] {}
1380                         else { panic!("Unexpected error variant"); }
1381                 },
1382                 _ => panic!("Unexpected error variant"),
1383         }
1384         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1385
1386         send_payment(&nodes[0], &vec![&nodes[1]], max_can_send);
1387 }
1388
1389 #[test]
1390 fn test_fee_spike_violation_fails_htlc() {
1391         let chanmon_cfgs = create_chanmon_cfgs(2);
1392         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1393         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1394         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1395         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1396
1397         let (mut route, payment_hash, _, payment_secret) =
1398                 get_route_and_payment_hash!(nodes[0], nodes[1], 3460000);
1399         route.paths[0].hops[0].fee_msat += 1;
1400         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1401         let secp_ctx = Secp256k1::new();
1402         let session_priv = SecretKey::from_slice(&[42; 32]).expect("RNG is bad!");
1403
1404         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1405
1406         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1407         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1408                 3460001, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1409         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1410         let msg = msgs::UpdateAddHTLC {
1411                 channel_id: chan.2,
1412                 htlc_id: 0,
1413                 amount_msat: htlc_msat,
1414                 payment_hash: payment_hash,
1415                 cltv_expiry: htlc_cltv,
1416                 onion_routing_packet: onion_packet,
1417                 skimmed_fee_msat: None,
1418                 blinding_point: None,
1419         };
1420
1421         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1422
1423         // Now manually create the commitment_signed message corresponding to the update_add
1424         // nodes[0] just sent. In the code for construction of this message, "local" refers
1425         // to the sender of the message, and "remote" refers to the receiver.
1426
1427         let feerate_per_kw = get_feerate!(nodes[0], nodes[1], chan.2);
1428
1429         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
1430
1431         // Get the TestChannelSigner for each channel, which will be used to (1) get the keys
1432         // needed to sign the new commitment tx and (2) sign the new commitment tx.
1433         let (local_revocation_basepoint, local_htlc_basepoint, local_secret, next_local_point, local_funding) = {
1434                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1435                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1436                 let local_chan = chan_lock.channel_by_id.get(&chan.2).map(
1437                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1438                 ).flatten().unwrap();
1439                 let chan_signer = local_chan.get_signer();
1440                 // Make the signer believe we validated another commitment, so we can release the secret
1441                 chan_signer.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
1442
1443                 let pubkeys = chan_signer.as_ref().pubkeys();
1444                 (pubkeys.revocation_basepoint, pubkeys.htlc_basepoint,
1445                  chan_signer.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER),
1446                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 2, &secp_ctx),
1447                  chan_signer.as_ref().pubkeys().funding_pubkey)
1448         };
1449         let (remote_delayed_payment_basepoint, remote_htlc_basepoint, remote_point, remote_funding) = {
1450                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
1451                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
1452                 let remote_chan = chan_lock.channel_by_id.get(&chan.2).map(
1453                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1454                 ).flatten().unwrap();
1455                 let chan_signer = remote_chan.get_signer();
1456                 let pubkeys = chan_signer.as_ref().pubkeys();
1457                 (pubkeys.delayed_payment_basepoint, pubkeys.htlc_basepoint,
1458                  chan_signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, &secp_ctx),
1459                  chan_signer.as_ref().pubkeys().funding_pubkey)
1460         };
1461
1462         // Assemble the set of keys we can use for signatures for our commitment_signed message.
1463         let commit_tx_keys = chan_utils::TxCreationKeys::derive_new(&secp_ctx, &remote_point, &remote_delayed_payment_basepoint,
1464                 &remote_htlc_basepoint, &local_revocation_basepoint, &local_htlc_basepoint);
1465
1466         // Build the remote commitment transaction so we can sign it, and then later use the
1467         // signature for the commitment_signed message.
1468         let local_chan_balance = 1313;
1469
1470         let accepted_htlc_info = chan_utils::HTLCOutputInCommitment {
1471                 offered: false,
1472                 amount_msat: 3460001,
1473                 cltv_expiry: htlc_cltv,
1474                 payment_hash,
1475                 transaction_output_index: Some(1),
1476         };
1477
1478         let commitment_number = INITIAL_COMMITMENT_NUMBER - 1;
1479
1480         let res = {
1481                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
1482                 let local_chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
1483                 let local_chan = local_chan_lock.channel_by_id.get(&chan.2).map(
1484                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
1485                 ).flatten().unwrap();
1486                 let local_chan_signer = local_chan.get_signer();
1487                 let commitment_tx = CommitmentTransaction::new_with_auxiliary_htlc_data(
1488                         commitment_number,
1489                         95000,
1490                         local_chan_balance,
1491                         local_funding, remote_funding,
1492                         commit_tx_keys.clone(),
1493                         feerate_per_kw,
1494                         &mut vec![(accepted_htlc_info, ())],
1495                         &local_chan.context.channel_transaction_parameters.as_counterparty_broadcastable()
1496                 );
1497                 local_chan_signer.as_ecdsa().unwrap().sign_counterparty_commitment(&commitment_tx, Vec::new(), Vec::new(), &secp_ctx).unwrap()
1498         };
1499
1500         let commit_signed_msg = msgs::CommitmentSigned {
1501                 channel_id: chan.2,
1502                 signature: res.0,
1503                 htlc_signatures: res.1,
1504                 #[cfg(taproot)]
1505                 partial_signature_with_nonce: None,
1506         };
1507
1508         // Send the commitment_signed message to the nodes[1].
1509         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commit_signed_msg);
1510         let _ = nodes[1].node.get_and_clear_pending_msg_events();
1511
1512         // Send the RAA to nodes[1].
1513         let raa_msg = msgs::RevokeAndACK {
1514                 channel_id: chan.2,
1515                 per_commitment_secret: local_secret,
1516                 next_per_commitment_point: next_local_point,
1517                 #[cfg(taproot)]
1518                 next_local_nonce: None,
1519         };
1520         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa_msg);
1521
1522         let events = nodes[1].node.get_and_clear_pending_msg_events();
1523         assert_eq!(events.len(), 1);
1524         // Make sure the HTLC failed in the way we expect.
1525         match events[0] {
1526                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, .. }, .. } => {
1527                         assert_eq!(update_fail_htlcs.len(), 1);
1528                         update_fail_htlcs[0].clone()
1529                 },
1530                 _ => panic!("Unexpected event"),
1531         };
1532         nodes[1].logger.assert_log("lightning::ln::channel",
1533                 format!("Attempting to fail HTLC due to fee spike buffer violation in channel {}. Rebalancing is required.", raa_msg.channel_id), 1);
1534
1535         check_added_monitors!(nodes[1], 2);
1536 }
1537
1538 #[test]
1539 fn test_chan_reserve_violation_outbound_htlc_inbound_chan() {
1540         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1541         // Set the fee rate for the channel very high, to the point where the fundee
1542         // sending any above-dust amount would result in a channel reserve violation.
1543         // In this test we check that we would be prevented from sending an HTLC in
1544         // this situation.
1545         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1546         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1547         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1548         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1549         let default_config = UserConfig::default();
1550         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1551
1552         let mut push_amt = 100_000_000;
1553         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1554
1555         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1556
1557         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1558
1559         // Fetch a route in advance as we will be unable to once we're unable to send.
1560         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 1_000_000);
1561         // Sending exactly enough to hit the reserve amount should be accepted
1562         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1563                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1564         }
1565
1566         // However one more HTLC should be significantly over the reserve amount and fail.
1567         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1568                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1569                 ), true, APIError::ChannelUnavailable { .. }, {});
1570         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1571 }
1572
1573 #[test]
1574 fn test_chan_reserve_violation_inbound_htlc_outbound_channel() {
1575         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1576         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1577         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1578         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1579         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1580         let default_config = UserConfig::default();
1581         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1582
1583         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1584         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1585         // transaction fee with 0 HTLCs (183 sats)).
1586         let mut push_amt = 100_000_000;
1587         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1588         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1589         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, push_amt);
1590
1591         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1592         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1593                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1594         }
1595
1596         let (mut route, payment_hash, _, payment_secret) =
1597                 get_route_and_payment_hash!(nodes[1], nodes[0], 1000);
1598         route.paths[0].hops[0].fee_msat = 700_000;
1599         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1600         let secp_ctx = Secp256k1::new();
1601         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1602         let cur_height = nodes[1].node.best_block.read().unwrap().height() + 1;
1603         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1604         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0],
1605                 700_000, RecipientOnionFields::secret_only(payment_secret), cur_height, &None).unwrap();
1606         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
1607         let msg = msgs::UpdateAddHTLC {
1608                 channel_id: chan.2,
1609                 htlc_id: MIN_AFFORDABLE_HTLC_COUNT as u64,
1610                 amount_msat: htlc_msat,
1611                 payment_hash: payment_hash,
1612                 cltv_expiry: htlc_cltv,
1613                 onion_routing_packet: onion_packet,
1614                 skimmed_fee_msat: None,
1615                 blinding_point: None,
1616         };
1617
1618         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &msg);
1619         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1620         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value", 3);
1621         assert_eq!(nodes[0].node.list_channels().len(), 0);
1622         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
1623         assert_eq!(err_msg.data, "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value");
1624         check_added_monitors!(nodes[0], 1);
1625         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: "Cannot accept HTLC that would put our balance under counterparty-announced channel reserve value".to_string() },
1626                 [nodes[1].node.get_our_node_id()], 100000);
1627 }
1628
1629 #[test]
1630 fn test_chan_reserve_dust_inbound_htlcs_outbound_chan() {
1631         // Test that if we receive many dust HTLCs over an outbound channel, they don't count when
1632         // calculating our commitment transaction fee (this was previously broken).
1633         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1634         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1635
1636         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1637         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1638         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1639         let default_config = UserConfig::default();
1640         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1641
1642         // Set nodes[0]'s balance such that they will consider any above-dust received HTLC to be a
1643         // channel reserve violation (so their balance is channel reserve (1000 sats) + commitment
1644         // transaction fee with 0 HTLCs (183 sats)).
1645         let mut push_amt = 100_000_000;
1646         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1647         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1648         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, push_amt);
1649
1650         let dust_amt = crate::ln::channel::MIN_CHAN_DUST_LIMIT_SATOSHIS * 1000
1651                 + feerate_per_kw as u64 * htlc_success_tx_weight(&channel_type_features) / 1000 * 1000 - 1;
1652         // In the previous code, routing this dust payment would cause nodes[0] to perceive a channel
1653         // reserve violation even though it's a dust HTLC and therefore shouldn't count towards the
1654         // commitment transaction fee.
1655         route_payment(&nodes[1], &[&nodes[0]], dust_amt);
1656
1657         // Send four HTLCs to cover the initial push_msat buffer we're required to include
1658         for _ in 0..MIN_AFFORDABLE_HTLC_COUNT {
1659                 route_payment(&nodes[1], &[&nodes[0]], 1_000_000);
1660         }
1661
1662         // One more than the dust amt should fail, however.
1663         let (mut route, our_payment_hash, _, our_payment_secret) =
1664                 get_route_and_payment_hash!(nodes[1], nodes[0], dust_amt);
1665         route.paths[0].hops[0].fee_msat += 1;
1666         unwrap_send_err!(nodes[1].node.send_payment_with_route(&route, our_payment_hash,
1667                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1668                 ), true, APIError::ChannelUnavailable { .. }, {});
1669 }
1670
1671 #[test]
1672 fn test_chan_init_feerate_unaffordability() {
1673         // Test that we will reject channel opens which do not leave enough to pay for any HTLCs due to
1674         // channel reserve and feerate requirements.
1675         let mut chanmon_cfgs = create_chanmon_cfgs(2);
1676         let feerate_per_kw = *chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
1677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1680         let default_config = UserConfig::default();
1681         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
1682
1683         // Set the push_msat amount such that nodes[0] will not be able to afford to add even a single
1684         // HTLC.
1685         let mut push_amt = 100_000_000;
1686         push_amt -= commit_tx_fee_msat(feerate_per_kw, MIN_AFFORDABLE_HTLC_COUNT as u64, &channel_type_features);
1687         assert_eq!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt + 1, 42, None, None).unwrap_err(),
1688                 APIError::APIMisuseError { err: "Funding amount (356) can't even pay fee for initial commitment transaction fee of 357.".to_string() });
1689
1690         // During open, we don't have a "counterparty channel reserve" to check against, so that
1691         // requirement only comes into play on the open_channel handling side.
1692         push_amt -= get_holder_selected_channel_reserve_satoshis(100_000, &default_config) * 1000;
1693         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, push_amt, 42, None, None).unwrap();
1694         let mut open_channel_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
1695         open_channel_msg.push_msat += 1;
1696         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_msg);
1697
1698         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1699         assert_eq!(msg_events.len(), 1);
1700         match msg_events[0] {
1701                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
1702                         assert_eq!(msg.data, "Insufficient funding amount for initial reserve");
1703                 },
1704                 _ => panic!("Unexpected event"),
1705         }
1706 }
1707
1708 #[test]
1709 fn test_chan_reserve_dust_inbound_htlcs_inbound_chan() {
1710         // Test that if we receive many dust HTLCs over an inbound channel, they don't count when
1711         // calculating our counterparty's commitment transaction fee (this was previously broken).
1712         let chanmon_cfgs = create_chanmon_cfgs(2);
1713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None, None]);
1715         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1716         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 98000000);
1717
1718         let payment_amt = 46000; // Dust amount
1719         // In the previous code, these first four payments would succeed.
1720         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1721         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1722         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1723         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1724
1725         // Then these next 5 would be interpreted by nodes[1] as violating the fee spike buffer.
1726         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1727         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1728         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1729         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1730         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1731
1732         // And this last payment previously resulted in nodes[1] closing on its inbound-channel
1733         // counterparty, because it counted all the previous dust HTLCs against nodes[0]'s commitment
1734         // transaction fee and therefore perceived this next payment as a channel reserve violation.
1735         route_payment(&nodes[0], &[&nodes[1]], payment_amt);
1736 }
1737
1738 #[test]
1739 fn test_chan_reserve_violation_inbound_htlc_inbound_chan() {
1740         let chanmon_cfgs = create_chanmon_cfgs(3);
1741         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1742         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1743         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1744         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1745         let _ = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
1746
1747         let feemsat = 239;
1748         let total_routing_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1749         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
1750         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
1751         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
1752
1753         // Add a 2* and +1 for the fee spike reserve.
1754         let commit_tx_fee_2_htlc = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1755         let recv_value_1 = (chan_stat.value_to_self_msat - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlc)/2;
1756         let amt_msat_1 = recv_value_1 + total_routing_fee_msat;
1757
1758         // Add a pending HTLC.
1759         let (route_1, our_payment_hash_1, _, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], amt_msat_1);
1760         let payment_event_1 = {
1761                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1762                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1763                 check_added_monitors!(nodes[0], 1);
1764
1765                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1766                 assert_eq!(events.len(), 1);
1767                 SendEvent::from_event(events.remove(0))
1768         };
1769         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1770
1771         // Attempt to trigger a channel reserve violation --> payment failure.
1772         let commit_tx_fee_2_htlcs = commit_tx_fee_msat(feerate, 2, &channel_type_features);
1773         let recv_value_2 = chan_stat.value_to_self_msat - amt_msat_1 - chan_stat.channel_reserve_msat - total_routing_fee_msat - commit_tx_fee_2_htlcs + 1;
1774         let amt_msat_2 = recv_value_2 + total_routing_fee_msat;
1775         let mut route_2 = route_1.clone();
1776         route_2.paths[0].hops.last_mut().unwrap().fee_msat = amt_msat_2;
1777
1778         // Need to manually create the update_add_htlc message to go around the channel reserve check in send_htlc()
1779         let secp_ctx = Secp256k1::new();
1780         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
1781         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
1782         let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route_2.paths[0], &session_priv).unwrap();
1783         let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
1784                 &route_2.paths[0], recv_value_2, RecipientOnionFields::spontaneous_empty(), cur_height, &None).unwrap();
1785         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash_1).unwrap();
1786         let msg = msgs::UpdateAddHTLC {
1787                 channel_id: chan.2,
1788                 htlc_id: 1,
1789                 amount_msat: htlc_msat + 1,
1790                 payment_hash: our_payment_hash_1,
1791                 cltv_expiry: htlc_cltv,
1792                 onion_routing_packet: onion_packet,
1793                 skimmed_fee_msat: None,
1794                 blinding_point: None,
1795         };
1796
1797         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1798         // Check that the payment failed and the channel is closed in response to the malicious UpdateAdd.
1799         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote HTLC add would put them under remote reserve value", 3);
1800         assert_eq!(nodes[1].node.list_channels().len(), 1);
1801         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1802         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
1803         check_added_monitors!(nodes[1], 1);
1804         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote HTLC add would put them under remote reserve value".to_string() },
1805                 [nodes[0].node.get_our_node_id()], 100000);
1806 }
1807
1808 #[test]
1809 fn test_inbound_outbound_capacity_is_not_zero() {
1810         let chanmon_cfgs = create_chanmon_cfgs(2);
1811         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1812         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1813         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1814         let _ = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
1815         let channels0 = node_chanmgrs[0].list_channels();
1816         let channels1 = node_chanmgrs[1].list_channels();
1817         let default_config = UserConfig::default();
1818         assert_eq!(channels0.len(), 1);
1819         assert_eq!(channels1.len(), 1);
1820
1821         let reserve = get_holder_selected_channel_reserve_satoshis(100_000, &default_config);
1822         assert_eq!(channels0[0].inbound_capacity_msat, 95000000 - reserve*1000);
1823         assert_eq!(channels1[0].outbound_capacity_msat, 95000000 - reserve*1000);
1824
1825         assert_eq!(channels0[0].outbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1826         assert_eq!(channels1[0].inbound_capacity_msat, 100000 * 1000 - 95000000 - reserve*1000);
1827 }
1828
1829 fn commit_tx_fee_msat(feerate: u32, num_htlcs: u64, channel_type_features: &ChannelTypeFeatures) -> u64 {
1830         (commitment_tx_base_weight(channel_type_features) + num_htlcs * COMMITMENT_TX_WEIGHT_PER_HTLC) * feerate as u64 / 1000 * 1000
1831 }
1832
1833 #[test]
1834 fn test_channel_reserve_holding_cell_htlcs() {
1835         let chanmon_cfgs = create_chanmon_cfgs(3);
1836         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1837         // When this test was written, the default base fee floated based on the HTLC count.
1838         // It is now fixed, so we simply set the fee to the expected value here.
1839         let mut config = test_default_channel_config();
1840         config.channel_config.forwarding_fee_base_msat = 239;
1841         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
1842         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1843         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 190000, 1001);
1844         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 190000, 1001);
1845
1846         let mut stat01 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1847         let mut stat11 = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
1848
1849         let mut stat12 = get_channel_value_stat!(nodes[1], nodes[2], chan_2.2);
1850         let mut stat22 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
1851
1852         macro_rules! expect_forward {
1853                 ($node: expr) => {{
1854                         let mut events = $node.node.get_and_clear_pending_msg_events();
1855                         assert_eq!(events.len(), 1);
1856                         check_added_monitors!($node, 1);
1857                         let payment_event = SendEvent::from_event(events.remove(0));
1858                         payment_event
1859                 }}
1860         }
1861
1862         let feemsat = 239; // set above
1863         let total_fee_msat = (nodes.len() - 2) as u64 * feemsat;
1864         let feerate = get_feerate!(nodes[0], nodes[1], chan_1.2);
1865         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_1.2);
1866
1867         let recv_value_0 = stat01.counterparty_max_htlc_value_in_flight_msat - total_fee_msat;
1868
1869         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1870         {
1871                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1872                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1873                 let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], payment_params, recv_value_0);
1874                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1875                 assert!(route.paths[0].hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1876
1877                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1878                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1879                         ), true, APIError::ChannelUnavailable { .. }, {});
1880                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1881         }
1882
1883         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1884         // nodes[0]'s wealth
1885         loop {
1886                 let amt_msat = recv_value_0 + total_fee_msat;
1887                 // 3 for the 3 HTLCs that will be sent, 2* and +1 for the fee spike reserve.
1888                 // Also, ensure that each payment has enough to be over the dust limit to
1889                 // ensure it'll be included in each commit tx fee calculation.
1890                 let commit_tx_fee_all_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1891                 let ensure_htlc_amounts_above_dust_buffer = 3 * (stat01.counterparty_dust_limit_msat + 1000);
1892                 if stat01.value_to_self_msat < stat01.channel_reserve_msat + commit_tx_fee_all_htlcs + ensure_htlc_amounts_above_dust_buffer + amt_msat {
1893                         break;
1894                 }
1895
1896                 let payment_params = PaymentParameters::from_node_id(nodes[2].node.get_our_node_id(), TEST_FINAL_CLTV)
1897                         .with_bolt11_features(nodes[2].node.bolt11_invoice_features()).unwrap().with_max_channel_saturation_power_of_half(0);
1898                 let route = get_route!(nodes[0], payment_params, recv_value_0).unwrap();
1899                 let (payment_preimage, ..) = send_along_route(&nodes[0], route, &[&nodes[1], &nodes[2]], recv_value_0);
1900                 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
1901
1902                 let (stat01_, stat11_, stat12_, stat22_) = (
1903                         get_channel_value_stat!(nodes[0], nodes[1], chan_1.2),
1904                         get_channel_value_stat!(nodes[1], nodes[0], chan_1.2),
1905                         get_channel_value_stat!(nodes[1], nodes[2], chan_2.2),
1906                         get_channel_value_stat!(nodes[2], nodes[1], chan_2.2),
1907                 );
1908
1909                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1910                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1911                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1912                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1913                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1914         }
1915
1916         // adding pending output.
1917         // 2* and +1 HTLCs on the commit tx fee for the fee spike reserve.
1918         // The reason we're dividing by two here is as follows: the dividend is the total outbound liquidity
1919         // after fees, the channel reserve, and the fee spike buffer are removed. We eventually want to
1920         // divide this quantity into 3 portions, that will each be sent in an HTLC. This allows us
1921         // to test channel channel reserve policy at the edges of what amount is sendable, i.e.
1922         // cases where 1 msat over X amount will cause a payment failure, but anything less than
1923         // that can be sent successfully. So, dividing by two is a somewhat arbitrary way of getting
1924         // the amount of the first of these aforementioned 3 payments. The reason we split into 3 payments
1925         // is to test the behavior of the holding cell with respect to channel reserve and commit tx fee
1926         // policy.
1927         let commit_tx_fee_2_htlcs = 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features);
1928         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs)/2;
1929         let amt_msat_1 = recv_value_1 + total_fee_msat;
1930
1931         let (route_1, our_payment_hash_1, our_payment_preimage_1, our_payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_1);
1932         let payment_event_1 = {
1933                 nodes[0].node.send_payment_with_route(&route_1, our_payment_hash_1,
1934                         RecipientOnionFields::secret_only(our_payment_secret_1), PaymentId(our_payment_hash_1.0)).unwrap();
1935                 check_added_monitors!(nodes[0], 1);
1936
1937                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1938                 assert_eq!(events.len(), 1);
1939                 SendEvent::from_event(events.remove(0))
1940         };
1941         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1942
1943         // channel reserve test with htlc pending output > 0
1944         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat - commit_tx_fee_2_htlcs;
1945         {
1946                 let mut route = route_1.clone();
1947                 route.paths[0].hops.last_mut().unwrap().fee_msat = recv_value_2 + 1;
1948                 let (_, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(nodes[2]);
1949                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1950                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1951                         ), true, APIError::ChannelUnavailable { .. }, {});
1952                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1953         }
1954
1955         // split the rest to test holding cell
1956         let commit_tx_fee_3_htlcs = 2*commit_tx_fee_msat(feerate, 3 + 1, &channel_type_features);
1957         let additional_htlc_cost_msat = commit_tx_fee_3_htlcs - commit_tx_fee_2_htlcs;
1958         let recv_value_21 = recv_value_2/2 - additional_htlc_cost_msat/2;
1959         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat - additional_htlc_cost_msat;
1960         {
1961                 let stat = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
1962                 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat + commit_tx_fee_3_htlcs), stat.channel_reserve_msat);
1963         }
1964
1965         // now see if they go through on both sides
1966         let (route_21, our_payment_hash_21, our_payment_preimage_21, our_payment_secret_21) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_21);
1967         // but this will stuck in the holding cell
1968         nodes[0].node.send_payment_with_route(&route_21, our_payment_hash_21,
1969                 RecipientOnionFields::secret_only(our_payment_secret_21), PaymentId(our_payment_hash_21.0)).unwrap();
1970         check_added_monitors!(nodes[0], 0);
1971         let events = nodes[0].node.get_and_clear_pending_events();
1972         assert_eq!(events.len(), 0);
1973
1974         // test with outbound holding cell amount > 0
1975         {
1976                 let (mut route, our_payment_hash, _, our_payment_secret) =
1977                         get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1978                 route.paths[0].hops.last_mut().unwrap().fee_msat += 1;
1979                 unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
1980                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
1981                         ), true, APIError::ChannelUnavailable { .. }, {});
1982                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1983         }
1984
1985         let (route_22, our_payment_hash_22, our_payment_preimage_22, our_payment_secret_22) = get_route_and_payment_hash!(nodes[0], nodes[2], recv_value_22);
1986         // this will also stuck in the holding cell
1987         nodes[0].node.send_payment_with_route(&route_22, our_payment_hash_22,
1988                 RecipientOnionFields::secret_only(our_payment_secret_22), PaymentId(our_payment_hash_22.0)).unwrap();
1989         check_added_monitors!(nodes[0], 0);
1990         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1991         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1992
1993         // flush the pending htlc
1994         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1995         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1996         check_added_monitors!(nodes[1], 1);
1997
1998         // the pending htlc should be promoted to committed
1999         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
2000         check_added_monitors!(nodes[0], 1);
2001         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2002
2003         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
2004         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2005         // No commitment_signed so get_event_msg's assert(len == 1) passes
2006         check_added_monitors!(nodes[0], 1);
2007
2008         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
2009         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2010         check_added_monitors!(nodes[1], 1);
2011
2012         expect_pending_htlcs_forwardable!(nodes[1]);
2013
2014         let ref payment_event_11 = expect_forward!(nodes[1]);
2015         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
2016         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
2017
2018         expect_pending_htlcs_forwardable!(nodes[2]);
2019         expect_payment_claimable!(nodes[2], our_payment_hash_1, our_payment_secret_1, recv_value_1);
2020
2021         // flush the htlcs in the holding cell
2022         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
2023         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
2024         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
2025         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
2026         expect_pending_htlcs_forwardable!(nodes[1]);
2027
2028         let ref payment_event_3 = expect_forward!(nodes[1]);
2029         assert_eq!(payment_event_3.msgs.len(), 2);
2030         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
2031         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
2032
2033         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
2034         expect_pending_htlcs_forwardable!(nodes[2]);
2035
2036         let events = nodes[2].node.get_and_clear_pending_events();
2037         assert_eq!(events.len(), 2);
2038         match events[0] {
2039                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2040                         assert_eq!(our_payment_hash_21, *payment_hash);
2041                         assert_eq!(recv_value_21, amount_msat);
2042                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2043                         assert_eq!(via_channel_id, Some(chan_2.2));
2044                         match &purpose {
2045                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2046                                         assert!(payment_preimage.is_none());
2047                                         assert_eq!(our_payment_secret_21, *payment_secret);
2048                                 },
2049                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2050                         }
2051                 },
2052                 _ => panic!("Unexpected event"),
2053         }
2054         match events[1] {
2055                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
2056                         assert_eq!(our_payment_hash_22, *payment_hash);
2057                         assert_eq!(recv_value_22, amount_msat);
2058                         assert_eq!(nodes[2].node.get_our_node_id(), receiver_node_id.unwrap());
2059                         assert_eq!(via_channel_id, Some(chan_2.2));
2060                         match &purpose {
2061                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
2062                                         assert!(payment_preimage.is_none());
2063                                         assert_eq!(our_payment_secret_22, *payment_secret);
2064                                 },
2065                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
2066                         }
2067                 },
2068                 _ => panic!("Unexpected event"),
2069         }
2070
2071         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
2072         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
2073         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
2074
2075         let commit_tx_fee_0_htlcs = 2*commit_tx_fee_msat(feerate, 1, &channel_type_features);
2076         let recv_value_3 = commit_tx_fee_2_htlcs - commit_tx_fee_0_htlcs - total_fee_msat;
2077         send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_3);
2078
2079         let commit_tx_fee_1_htlc = 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
2080         let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat) - (recv_value_3 + total_fee_msat);
2081         let stat0 = get_channel_value_stat!(nodes[0], nodes[1], chan_1.2);
2082         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
2083         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat + commit_tx_fee_1_htlc);
2084
2085         let stat2 = get_channel_value_stat!(nodes[2], nodes[1], chan_2.2);
2086         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22 + recv_value_3);
2087 }
2088
2089 #[test]
2090 fn channel_reserve_in_flight_removes() {
2091         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
2092         // can send to its counterparty, but due to update ordering, the other side may not yet have
2093         // considered those HTLCs fully removed.
2094         // This tests that we don't count HTLCs which will not be included in the next remote
2095         // commitment transaction towards the reserve value (as it implies no commitment transaction
2096         // will be generated which violates the remote reserve value).
2097         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
2098         // To test this we:
2099         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
2100         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
2101         //    you only consider the value of the first HTLC, it may not),
2102         //  * start routing a third HTLC from A to B,
2103         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
2104         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
2105         //  * deliver the first fulfill from B
2106         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
2107         //    claim,
2108         //  * deliver A's response CS and RAA.
2109         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
2110         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
2111         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
2112         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
2113         let chanmon_cfgs = create_chanmon_cfgs(2);
2114         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2115         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2116         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2117         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2118
2119         let b_chan_values = get_channel_value_stat!(nodes[1], nodes[0], chan_1.2);
2120         // Route the first two HTLCs.
2121         let payment_value_1 = b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000;
2122         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], payment_value_1);
2123         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], 20_000);
2124
2125         // Start routing the third HTLC (this is just used to get everyone in the right state).
2126         let (route, payment_hash_3, payment_preimage_3, payment_secret_3) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
2127         let send_1 = {
2128                 nodes[0].node.send_payment_with_route(&route, payment_hash_3,
2129                         RecipientOnionFields::secret_only(payment_secret_3), PaymentId(payment_hash_3.0)).unwrap();
2130                 check_added_monitors!(nodes[0], 1);
2131                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2132                 assert_eq!(events.len(), 1);
2133                 SendEvent::from_event(events.remove(0))
2134         };
2135
2136         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
2137         // initial fulfill/CS.
2138         nodes[1].node.claim_funds(payment_preimage_1);
2139         expect_payment_claimed!(nodes[1], payment_hash_1, payment_value_1);
2140         check_added_monitors!(nodes[1], 1);
2141         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2142
2143         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
2144         // remove the second HTLC when we send the HTLC back from B to A.
2145         nodes[1].node.claim_funds(payment_preimage_2);
2146         expect_payment_claimed!(nodes[1], payment_hash_2, 20_000);
2147         check_added_monitors!(nodes[1], 1);
2148         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2149
2150         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
2151         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
2152         check_added_monitors!(nodes[0], 1);
2153         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2154         expect_payment_sent(&nodes[0], payment_preimage_1, None, false, false);
2155
2156         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
2157         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
2158         check_added_monitors!(nodes[1], 1);
2159         // B is already AwaitingRAA, so cant generate a CS here
2160         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2161
2162         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2163         check_added_monitors!(nodes[1], 1);
2164         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2165
2166         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2167         check_added_monitors!(nodes[0], 1);
2168         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2169
2170         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2171         check_added_monitors!(nodes[1], 1);
2172         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2173
2174         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
2175         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
2176         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
2177         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
2178         // on-chain as necessary).
2179         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
2180         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
2181         check_added_monitors!(nodes[0], 1);
2182         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2183         expect_payment_sent(&nodes[0], payment_preimage_2, None, false, false);
2184
2185         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2186         check_added_monitors!(nodes[1], 1);
2187         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2188
2189         expect_pending_htlcs_forwardable!(nodes[1]);
2190         expect_payment_claimable!(nodes[1], payment_hash_3, payment_secret_3, 100000);
2191
2192         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
2193         // resolve the second HTLC from A's point of view.
2194         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2195         check_added_monitors!(nodes[0], 1);
2196         expect_payment_path_successful!(nodes[0]);
2197         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2198
2199         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
2200         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
2201         let (route, payment_hash_4, payment_preimage_4, payment_secret_4) = get_route_and_payment_hash!(nodes[1], nodes[0], 10000);
2202         let send_2 = {
2203                 nodes[1].node.send_payment_with_route(&route, payment_hash_4,
2204                         RecipientOnionFields::secret_only(payment_secret_4), PaymentId(payment_hash_4.0)).unwrap();
2205                 check_added_monitors!(nodes[1], 1);
2206                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2207                 assert_eq!(events.len(), 1);
2208                 SendEvent::from_event(events.remove(0))
2209         };
2210
2211         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
2212         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
2213         check_added_monitors!(nodes[0], 1);
2214         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2215
2216         // Now just resolve all the outstanding messages/HTLCs for completeness...
2217
2218         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2219         check_added_monitors!(nodes[1], 1);
2220         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2221
2222         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
2223         check_added_monitors!(nodes[1], 1);
2224
2225         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2226         check_added_monitors!(nodes[0], 1);
2227         expect_payment_path_successful!(nodes[0]);
2228         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2229
2230         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
2231         check_added_monitors!(nodes[1], 1);
2232         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2233
2234         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
2235         check_added_monitors!(nodes[0], 1);
2236
2237         expect_pending_htlcs_forwardable!(nodes[0]);
2238         expect_payment_claimable!(nodes[0], payment_hash_4, payment_secret_4, 10000);
2239
2240         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
2241         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
2242 }
2243
2244 #[test]
2245 fn channel_monitor_network_test() {
2246         // Simple test which builds a network of ChannelManagers, connects them to each other, and
2247         // tests that ChannelMonitor is able to recover from various states.
2248         let chanmon_cfgs = create_chanmon_cfgs(5);
2249         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
2250         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
2251         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
2252
2253         // Create some initial channels
2254         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2255         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2256         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
2257         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
2258
2259         // Make sure all nodes are at the same starting height
2260         connect_blocks(&nodes[0], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
2261         connect_blocks(&nodes[1], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
2262         connect_blocks(&nodes[2], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
2263         connect_blocks(&nodes[3], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[3].best_block_info().1);
2264         connect_blocks(&nodes[4], 4*CHAN_CONFIRM_DEPTH + 1 - nodes[4].best_block_info().1);
2265
2266         // Rebalance the network a bit by relaying one payment through all the channels...
2267         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2268         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2269         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2270         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
2271
2272         // Simple case with no pending HTLCs:
2273         nodes[1].node.force_close_broadcasting_latest_txn(&chan_1.2, &nodes[0].node.get_our_node_id()).unwrap();
2274         check_added_monitors!(nodes[1], 1);
2275         check_closed_broadcast!(nodes[1], true);
2276         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
2277         {
2278                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
2279                 assert_eq!(node_txn.len(), 1);
2280                 mine_transaction(&nodes[1], &node_txn[0]);
2281                 if nodes[1].connect_style.borrow().updates_best_block_first() {
2282                         let _ = nodes[1].tx_broadcaster.txn_broadcast();
2283                 }
2284
2285                 mine_transaction(&nodes[0], &node_txn[0]);
2286                 check_added_monitors!(nodes[0], 1);
2287                 test_txn_broadcast(&nodes[0], &chan_1, Some(node_txn[0].clone()), HTLCType::NONE);
2288         }
2289         check_closed_broadcast!(nodes[0], true);
2290         assert_eq!(nodes[0].node.list_channels().len(), 0);
2291         assert_eq!(nodes[1].node.list_channels().len(), 1);
2292         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2293
2294         // One pending HTLC is discarded by the force-close:
2295         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[1], &[&nodes[2], &nodes[3]], 3_000_000);
2296
2297         // Simple case of one pending HTLC to HTLC-Timeout (note that the HTLC-Timeout is not
2298         // broadcasted until we reach the timelock time).
2299         nodes[1].node.force_close_broadcasting_latest_txn(&chan_2.2, &nodes[2].node.get_our_node_id()).unwrap();
2300         check_closed_broadcast!(nodes[1], true);
2301         check_added_monitors!(nodes[1], 1);
2302         {
2303                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::NONE);
2304                 connect_blocks(&nodes[1], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2305                 test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
2306                 mine_transaction(&nodes[2], &node_txn[0]);
2307                 check_added_monitors!(nodes[2], 1);
2308                 test_txn_broadcast(&nodes[2], &chan_2, Some(node_txn[0].clone()), HTLCType::NONE);
2309         }
2310         check_closed_broadcast!(nodes[2], true);
2311         assert_eq!(nodes[1].node.list_channels().len(), 0);
2312         assert_eq!(nodes[2].node.list_channels().len(), 1);
2313         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
2314         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2315
2316         macro_rules! claim_funds {
2317                 ($node: expr, $prev_node: expr, $preimage: expr, $payment_hash: expr) => {
2318                         {
2319                                 $node.node.claim_funds($preimage);
2320                                 expect_payment_claimed!($node, $payment_hash, 3_000_000);
2321                                 check_added_monitors!($node, 1);
2322
2323                                 let events = $node.node.get_and_clear_pending_msg_events();
2324                                 assert_eq!(events.len(), 1);
2325                                 match events[0] {
2326                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2327                                                 assert!(update_add_htlcs.is_empty());
2328                                                 assert!(update_fail_htlcs.is_empty());
2329                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2330                                         },
2331                                         _ => panic!("Unexpected event"),
2332                                 };
2333                         }
2334                 }
2335         }
2336
2337         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2338         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2339         nodes[2].node.force_close_broadcasting_latest_txn(&chan_3.2, &nodes[3].node.get_our_node_id()).unwrap();
2340         check_added_monitors!(nodes[2], 1);
2341         check_closed_broadcast!(nodes[2], true);
2342         let node2_commitment_txid;
2343         {
2344                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::NONE);
2345                 connect_blocks(&nodes[2], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + MIN_CLTV_EXPIRY_DELTA as u32 + 1);
2346                 test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2347                 node2_commitment_txid = node_txn[0].txid();
2348
2349                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2350                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, payment_hash_1);
2351                 mine_transaction(&nodes[3], &node_txn[0]);
2352                 check_added_monitors!(nodes[3], 1);
2353                 check_preimage_claim(&nodes[3], &node_txn);
2354         }
2355         check_closed_broadcast!(nodes[3], true);
2356         assert_eq!(nodes[2].node.list_channels().len(), 0);
2357         assert_eq!(nodes[3].node.list_channels().len(), 1);
2358         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2359         check_closed_event!(nodes[3], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
2360
2361         // Drop the ChannelMonitor for the previous channel to avoid it broadcasting transactions and
2362         // confusing us in the following tests.
2363         let chan_3_mon = nodes[3].chain_monitor.chain_monitor.remove_monitor(&OutPoint { txid: chan_3.3.txid(), index: 0 });
2364
2365         // One pending HTLC to time out:
2366         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[3], &[&nodes[4]], 3_000_000);
2367         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2368         // buffer space).
2369
2370         let (close_chan_update_1, close_chan_update_2) = {
2371                 connect_blocks(&nodes[3], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
2372                 let events = nodes[3].node.get_and_clear_pending_msg_events();
2373                 assert_eq!(events.len(), 2);
2374                 let close_chan_update_1 = match events[0] {
2375                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2376                                 msg.clone()
2377                         },
2378                         _ => panic!("Unexpected event"),
2379                 };
2380                 match events[1] {
2381                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2382                                 assert_eq!(node_id, nodes[4].node.get_our_node_id());
2383                         },
2384                         _ => panic!("Unexpected event"),
2385                 }
2386                 check_added_monitors!(nodes[3], 1);
2387
2388                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2389                 {
2390                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2391                         node_txn.retain(|tx| {
2392                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2393                                         false
2394                                 } else { true }
2395                         });
2396                 }
2397
2398                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2399
2400                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2401                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, payment_hash_2);
2402
2403                 connect_blocks(&nodes[4], TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + 2);
2404                 let events = nodes[4].node.get_and_clear_pending_msg_events();
2405                 assert_eq!(events.len(), 2);
2406                 let close_chan_update_2 = match events[0] {
2407                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
2408                                 msg.clone()
2409                         },
2410                         _ => panic!("Unexpected event"),
2411                 };
2412                 match events[1] {
2413                         MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id } => {
2414                                 assert_eq!(node_id, nodes[3].node.get_our_node_id());
2415                         },
2416                         _ => panic!("Unexpected event"),
2417                 }
2418                 check_added_monitors!(nodes[4], 1);
2419                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2420                 check_closed_event!(nodes[4], 1, ClosureReason::HolderForceClosed, [nodes[3].node.get_our_node_id()], 100000);
2421
2422                 mine_transaction(&nodes[4], &node_txn[0]);
2423                 check_preimage_claim(&nodes[4], &node_txn);
2424                 (close_chan_update_1, close_chan_update_2)
2425         };
2426         nodes[3].gossip_sync.handle_channel_update(&close_chan_update_2).unwrap();
2427         nodes[4].gossip_sync.handle_channel_update(&close_chan_update_1).unwrap();
2428         assert_eq!(nodes[3].node.list_channels().len(), 0);
2429         assert_eq!(nodes[4].node.list_channels().len(), 0);
2430
2431         assert_eq!(nodes[3].chain_monitor.chain_monitor.watch_channel(OutPoint { txid: chan_3.3.txid(), index: 0 }, chan_3_mon),
2432                 Ok(ChannelMonitorUpdateStatus::Completed));
2433         check_closed_event!(nodes[3], 1, ClosureReason::HolderForceClosed, [nodes[4].node.get_our_node_id()], 100000);
2434 }
2435
2436 #[test]
2437 fn test_justice_tx_htlc_timeout() {
2438         // Test justice txn built on revoked HTLC-Timeout tx, against both sides
2439         let mut alice_config = UserConfig::default();
2440         alice_config.channel_handshake_config.announced_channel = true;
2441         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2442         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2443         let mut bob_config = UserConfig::default();
2444         bob_config.channel_handshake_config.announced_channel = true;
2445         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2446         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2447         let user_cfgs = [Some(alice_config), Some(bob_config)];
2448         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2449         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2450         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2451         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2452         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2453         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2454         // Create some new channels:
2455         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
2456
2457         // A pending HTLC which will be revoked:
2458         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2459         // Get the will-be-revoked local txn from nodes[0]
2460         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2461         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2462         assert_eq!(revoked_local_txn[0].input.len(), 1);
2463         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2464         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2465         assert_eq!(revoked_local_txn[1].input.len(), 1);
2466         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2467         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2468         // Revoke the old state
2469         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
2470
2471         {
2472                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2473                 {
2474                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2475                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2476                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2477                         check_spends!(node_txn[0], revoked_local_txn[0]);
2478                         node_txn.swap_remove(0);
2479                 }
2480                 check_added_monitors!(nodes[1], 1);
2481                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2482                 test_txn_broadcast(&nodes[1], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2483
2484                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2485                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2486                 // Verify broadcast of revoked HTLC-timeout
2487                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2488                 check_added_monitors!(nodes[0], 1);
2489                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2490                 // Broadcast revoked HTLC-timeout on node 1
2491                 mine_transaction(&nodes[1], &node_txn[1]);
2492                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2493         }
2494         get_announce_close_broadcast_events(&nodes, 0, 1);
2495         assert_eq!(nodes[0].node.list_channels().len(), 0);
2496         assert_eq!(nodes[1].node.list_channels().len(), 0);
2497 }
2498
2499 #[test]
2500 fn test_justice_tx_htlc_success() {
2501         // Test justice txn built on revoked HTLC-Success tx, against both sides
2502         let mut alice_config = UserConfig::default();
2503         alice_config.channel_handshake_config.announced_channel = true;
2504         alice_config.channel_handshake_limits.force_announced_channel_preference = false;
2505         alice_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 5;
2506         let mut bob_config = UserConfig::default();
2507         bob_config.channel_handshake_config.announced_channel = true;
2508         bob_config.channel_handshake_limits.force_announced_channel_preference = false;
2509         bob_config.channel_handshake_config.our_to_self_delay = 6 * 24 * 3;
2510         let user_cfgs = [Some(alice_config), Some(bob_config)];
2511         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2512         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2513         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
2514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2516         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2517         // Create some new channels:
2518         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
2519
2520         // A pending HTLC which will be revoked:
2521         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2522         // Get the will-be-revoked local txn from B
2523         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2524         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2525         assert_eq!(revoked_local_txn[0].input.len(), 1);
2526         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2527         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2528         // Revoke the old state
2529         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
2530         {
2531                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2532                 {
2533                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2534                         assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2535                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2536
2537                         check_spends!(node_txn[0], revoked_local_txn[0]);
2538                         node_txn.swap_remove(0);
2539                 }
2540                 check_added_monitors!(nodes[0], 1);
2541                 test_txn_broadcast(&nodes[0], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::NONE);
2542
2543                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2544                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2545                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2546                 check_added_monitors!(nodes[1], 1);
2547                 mine_transaction(&nodes[0], &node_txn[1]);
2548                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2549                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2550         }
2551         get_announce_close_broadcast_events(&nodes, 0, 1);
2552         assert_eq!(nodes[0].node.list_channels().len(), 0);
2553         assert_eq!(nodes[1].node.list_channels().len(), 0);
2554 }
2555
2556 #[test]
2557 fn revoked_output_claim() {
2558         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2559         // transaction is broadcast by its counterparty
2560         let chanmon_cfgs = create_chanmon_cfgs(2);
2561         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2562         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2563         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2564         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2565         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2566         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2567         assert_eq!(revoked_local_txn.len(), 1);
2568         // Only output is the full channel value back to nodes[0]:
2569         assert_eq!(revoked_local_txn[0].output.len(), 1);
2570         // Send a payment through, updating everyone's latest commitment txn
2571         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
2572
2573         // Inform nodes[1] that nodes[0] broadcast a stale tx
2574         mine_transaction(&nodes[1], &revoked_local_txn[0]);
2575         check_added_monitors!(nodes[1], 1);
2576         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2577         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2578         assert_eq!(node_txn.len(), 1); // ChannelMonitor: justice tx against revoked to_local output
2579
2580         check_spends!(node_txn[0], revoked_local_txn[0]);
2581
2582         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2583         mine_transaction(&nodes[0], &revoked_local_txn[0]);
2584         get_announce_close_broadcast_events(&nodes, 0, 1);
2585         check_added_monitors!(nodes[0], 1);
2586         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2587 }
2588
2589 #[test]
2590 fn test_forming_justice_tx_from_monitor_updates() {
2591         do_test_forming_justice_tx_from_monitor_updates(true);
2592         do_test_forming_justice_tx_from_monitor_updates(false);
2593 }
2594
2595 fn do_test_forming_justice_tx_from_monitor_updates(broadcast_initial_commitment: bool) {
2596         // Simple test to make sure that the justice tx formed in WatchtowerPersister
2597         // is properly formed and can be broadcasted/confirmed successfully in the event
2598         // that a revoked commitment transaction is broadcasted
2599         // (Similar to `revoked_output_claim` test but we get the justice tx + broadcast manually)
2600         let chanmon_cfgs = create_chanmon_cfgs(2);
2601         let destination_script0 = chanmon_cfgs[0].keys_manager.get_destination_script([0; 32]).unwrap();
2602         let destination_script1 = chanmon_cfgs[1].keys_manager.get_destination_script([0; 32]).unwrap();
2603         let persisters = vec![WatchtowerPersister::new(destination_script0),
2604                 WatchtowerPersister::new(destination_script1)];
2605         let node_cfgs = create_node_cfgs_with_persisters(2, &chanmon_cfgs, persisters.iter().collect());
2606         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2607         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2608         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 1);
2609         let funding_txo = OutPoint { txid: funding_tx.txid(), index: 0 };
2610
2611         if !broadcast_initial_commitment {
2612                 // Send a payment to move the channel forward
2613                 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2614         }
2615
2616         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output.
2617         // We'll keep this commitment transaction to broadcast once it's revoked.
2618         let revoked_local_txn = get_local_commitment_txn!(nodes[0], channel_id);
2619         assert_eq!(revoked_local_txn.len(), 1);
2620         let revoked_commitment_tx = &revoked_local_txn[0];
2621
2622         // Send another payment, now revoking the previous commitment tx
2623         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5_000_000);
2624
2625         let justice_tx = persisters[1].justice_tx(funding_txo, &revoked_commitment_tx.txid()).unwrap();
2626         check_spends!(justice_tx, revoked_commitment_tx);
2627
2628         mine_transactions(&nodes[1], &[revoked_commitment_tx, &justice_tx]);
2629         mine_transactions(&nodes[0], &[revoked_commitment_tx, &justice_tx]);
2630
2631         check_added_monitors!(nodes[1], 1);
2632         check_closed_event(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false,
2633                 &[nodes[0].node.get_our_node_id()], 100_000);
2634         get_announce_close_broadcast_events(&nodes, 1, 0);
2635
2636         check_added_monitors!(nodes[0], 1);
2637         check_closed_event(&nodes[0], 1, ClosureReason::CommitmentTxConfirmed, false,
2638                 &[nodes[1].node.get_our_node_id()], 100_000);
2639
2640         // Check that the justice tx has sent the revoked output value to nodes[1]
2641         let monitor = get_monitor!(nodes[1], channel_id);
2642         let total_claimable_balance = monitor.get_claimable_balances().iter().fold(0, |sum, balance| {
2643                 match balance {
2644                         channelmonitor::Balance::ClaimableAwaitingConfirmations { amount_satoshis, .. } => sum + amount_satoshis,
2645                         _ => panic!("Unexpected balance type"),
2646                 }
2647         });
2648         // On the first commitment, node[1]'s balance was below dust so it didn't have an output
2649         let node1_channel_balance = if broadcast_initial_commitment { 0 } else { revoked_commitment_tx.output[0].value };
2650         let expected_claimable_balance = node1_channel_balance + justice_tx.output[0].value;
2651         assert_eq!(total_claimable_balance, expected_claimable_balance);
2652 }
2653
2654
2655 #[test]
2656 fn claim_htlc_outputs_shared_tx() {
2657         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2658         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2659         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2660         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2661         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2662         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2663
2664         // Create some new channel:
2665         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2666
2667         // Rebalance the network to generate htlc in the two directions
2668         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2669         // 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
2670         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2671         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2672
2673         // Get the will-be-revoked local txn from node[0]
2674         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2675         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2676         assert_eq!(revoked_local_txn[0].input.len(), 1);
2677         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2678         assert_eq!(revoked_local_txn[1].input.len(), 1);
2679         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2680         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2681         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2682
2683         //Revoke the old state
2684         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2685
2686         {
2687                 mine_transaction(&nodes[0], &revoked_local_txn[0]);
2688                 check_added_monitors!(nodes[0], 1);
2689                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2690                 mine_transaction(&nodes[1], &revoked_local_txn[0]);
2691                 check_added_monitors!(nodes[1], 1);
2692                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2693                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2694                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2695
2696                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
2697                 assert_eq!(node_txn.len(), 1); // ChannelMonitor: penalty tx
2698
2699                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2700                 check_spends!(node_txn[0], revoked_local_txn[0]);
2701
2702                 let mut witness_lens = BTreeSet::new();
2703                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2704                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2705                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2706                 assert_eq!(witness_lens.len(), 3);
2707                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2708                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2709                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2710
2711                 // Finally, mine the penalty transaction and check that we get an HTLC failure after
2712                 // ANTI_REORG_DELAY confirmations.
2713                 mine_transaction(&nodes[1], &node_txn[0]);
2714                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2715                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2716         }
2717         get_announce_close_broadcast_events(&nodes, 0, 1);
2718         assert_eq!(nodes[0].node.list_channels().len(), 0);
2719         assert_eq!(nodes[1].node.list_channels().len(), 0);
2720 }
2721
2722 #[test]
2723 fn claim_htlc_outputs_single_tx() {
2724         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2725         let mut chanmon_cfgs = create_chanmon_cfgs(2);
2726         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
2727         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2728         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2729         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2730
2731         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2732
2733         // Rebalance the network to generate htlc in the two directions
2734         send_payment(&nodes[0], &[&nodes[1]], 8_000_000);
2735         // 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
2736         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2737         let payment_preimage_1 = route_payment(&nodes[0], &[&nodes[1]], 3_000_000).0;
2738         let (_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[1], &[&nodes[0]], 3_000_000);
2739
2740         // Get the will-be-revoked local txn from node[0]
2741         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2742
2743         //Revoke the old state
2744         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
2745
2746         {
2747                 confirm_transaction_at(&nodes[0], &revoked_local_txn[0], 100);
2748                 check_added_monitors!(nodes[0], 1);
2749                 confirm_transaction_at(&nodes[1], &revoked_local_txn[0], 100);
2750                 check_added_monitors!(nodes[1], 1);
2751                 check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2752                 let mut events = nodes[0].node.get_and_clear_pending_events();
2753                 expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
2754                 match events.last().unwrap() {
2755                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2756                         _ => panic!("Unexpected event"),
2757                 }
2758
2759                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2760                 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2761
2762                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcast();
2763
2764                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2765                 assert_eq!(node_txn[0].input.len(), 1);
2766                 check_spends!(node_txn[0], chan_1.3);
2767                 assert_eq!(node_txn[1].input.len(), 1);
2768                 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2769                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2770                 check_spends!(node_txn[1], node_txn[0]);
2771
2772                 // Filter out any non justice transactions.
2773                 node_txn.retain(|tx| tx.input[0].previous_output.txid == revoked_local_txn[0].txid());
2774                 assert!(node_txn.len() > 3);
2775
2776                 assert_eq!(node_txn[0].input.len(), 1);
2777                 assert_eq!(node_txn[1].input.len(), 1);
2778                 assert_eq!(node_txn[2].input.len(), 1);
2779
2780                 check_spends!(node_txn[0], revoked_local_txn[0]);
2781                 check_spends!(node_txn[1], revoked_local_txn[0]);
2782                 check_spends!(node_txn[2], revoked_local_txn[0]);
2783
2784                 let mut witness_lens = BTreeSet::new();
2785                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2786                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2787                 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2788                 assert_eq!(witness_lens.len(), 3);
2789                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2790                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2791                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2792
2793                 // Finally, mine the penalty transactions and check that we get an HTLC failure after
2794                 // ANTI_REORG_DELAY confirmations.
2795                 mine_transaction(&nodes[1], &node_txn[0]);
2796                 mine_transaction(&nodes[1], &node_txn[1]);
2797                 mine_transaction(&nodes[1], &node_txn[2]);
2798                 connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
2799                 expect_payment_failed!(nodes[1], payment_hash_2, false);
2800         }
2801         get_announce_close_broadcast_events(&nodes, 0, 1);
2802         assert_eq!(nodes[0].node.list_channels().len(), 0);
2803         assert_eq!(nodes[1].node.list_channels().len(), 0);
2804 }
2805
2806 #[test]
2807 fn test_htlc_on_chain_success() {
2808         // Test that in case of a unilateral close onchain, we detect the state of output and pass
2809         // the preimage backward accordingly. So here we test that ChannelManager is
2810         // broadcasting the right event to other nodes in payment path.
2811         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2812         // A --------------------> B ----------------------> C (preimage)
2813         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2814         // commitment transaction was broadcast.
2815         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2816         // towards B.
2817         // B should be able to claim via preimage if A then broadcasts its local tx.
2818         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2819         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2820         // PaymentSent event).
2821
2822         let chanmon_cfgs = create_chanmon_cfgs(3);
2823         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2824         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2825         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2826
2827         // Create some initial channels
2828         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2829         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2830
2831         // Ensure all nodes are at the same height
2832         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
2833         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
2834         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
2835         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
2836
2837         // Rebalance the network a bit by relaying one payment through all the channels...
2838         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2839         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2840
2841         let (our_payment_preimage, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2842         let (our_payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
2843
2844         // Broadcast legit commitment tx from C on B's chain
2845         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2846         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2847         assert_eq!(commitment_tx.len(), 1);
2848         check_spends!(commitment_tx[0], chan_2.3);
2849         nodes[2].node.claim_funds(our_payment_preimage);
2850         expect_payment_claimed!(nodes[2], payment_hash_1, 3_000_000);
2851         nodes[2].node.claim_funds(our_payment_preimage_2);
2852         expect_payment_claimed!(nodes[2], payment_hash_2, 3_000_000);
2853         check_added_monitors!(nodes[2], 2);
2854         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2855         assert!(updates.update_add_htlcs.is_empty());
2856         assert!(updates.update_fail_htlcs.is_empty());
2857         assert!(updates.update_fail_malformed_htlcs.is_empty());
2858         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2859
2860         mine_transaction(&nodes[2], &commitment_tx[0]);
2861         check_closed_broadcast!(nodes[2], true);
2862         check_added_monitors!(nodes[2], 1);
2863         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
2864         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 2 (2 * HTLC-Success tx)
2865         assert_eq!(node_txn.len(), 2);
2866         check_spends!(node_txn[0], commitment_tx[0]);
2867         check_spends!(node_txn[1], commitment_tx[0]);
2868         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2869         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2870         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2871         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2872         assert_eq!(node_txn[0].lock_time, LockTime::ZERO);
2873         assert_eq!(node_txn[1].lock_time, LockTime::ZERO);
2874
2875         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2876         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), node_txn[0].clone(), node_txn[1].clone()]));
2877         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
2878         {
2879                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2880                 assert_eq!(added_monitors.len(), 1);
2881                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2882                 added_monitors.clear();
2883         }
2884         let forwarded_events = nodes[1].node.get_and_clear_pending_events();
2885         assert_eq!(forwarded_events.len(), 3);
2886         match forwarded_events[0] {
2887                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
2888                 _ => panic!("Unexpected event"),
2889         }
2890         let chan_id = Some(chan_1.2);
2891         match forwarded_events[1] {
2892                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2893                         assert_eq!(fee_earned_msat, Some(1000));
2894                         assert_eq!(prev_channel_id, chan_id);
2895                         assert_eq!(claim_from_onchain_tx, true);
2896                         assert_eq!(next_channel_id, Some(chan_2.2));
2897                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2898                 },
2899                 _ => panic!()
2900         }
2901         match forwarded_events[2] {
2902                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
2903                         assert_eq!(fee_earned_msat, Some(1000));
2904                         assert_eq!(prev_channel_id, chan_id);
2905                         assert_eq!(claim_from_onchain_tx, true);
2906                         assert_eq!(next_channel_id, Some(chan_2.2));
2907                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
2908                 },
2909                 _ => panic!()
2910         }
2911         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
2912         {
2913                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
2914                 assert_eq!(added_monitors.len(), 2);
2915                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2916                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2917                 added_monitors.clear();
2918         }
2919         assert_eq!(events.len(), 3);
2920
2921         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
2922         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
2923
2924         match nodes_2_event {
2925                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
2926                 _ => panic!("Unexpected event"),
2927         }
2928
2929         match nodes_0_event {
2930                 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, .. } } => {
2931                         assert!(update_add_htlcs.is_empty());
2932                         assert!(update_fail_htlcs.is_empty());
2933                         assert_eq!(update_fulfill_htlcs.len(), 1);
2934                         assert!(update_fail_malformed_htlcs.is_empty());
2935                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2936                 },
2937                 _ => panic!("Unexpected event"),
2938         };
2939
2940         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
2941         match events[0] {
2942                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2943                 _ => panic!("Unexpected event"),
2944         }
2945
2946         macro_rules! check_tx_local_broadcast {
2947                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr) => { {
2948                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2949                         assert_eq!(node_txn.len(), 2);
2950                         // Node[1]: 2 * HTLC-timeout tx
2951                         // Node[0]: 2 * HTLC-timeout tx
2952                         check_spends!(node_txn[0], $commitment_tx);
2953                         check_spends!(node_txn[1], $commitment_tx);
2954                         assert_ne!(node_txn[0].lock_time, LockTime::ZERO);
2955                         assert_ne!(node_txn[1].lock_time, LockTime::ZERO);
2956                         if $htlc_offered {
2957                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2958                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2959                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2960                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2961                         } else {
2962                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2963                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2964                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2965                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2966                         }
2967                         node_txn.clear();
2968                 } }
2969         }
2970         // nodes[1] now broadcasts its own timeout-claim of the output that nodes[2] just claimed via success.
2971         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0]);
2972
2973         // Broadcast legit commitment tx from A on B's chain
2974         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2975         let node_a_commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2976         check_spends!(node_a_commitment_tx[0], chan_1.3);
2977         mine_transaction(&nodes[1], &node_a_commitment_tx[0]);
2978         check_closed_broadcast!(nodes[1], true);
2979         check_added_monitors!(nodes[1], 1);
2980         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
2981         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
2982         assert!(node_txn.len() == 1 || node_txn.len() == 3); // HTLC-Success, 2* RBF bumps of above HTLC txn
2983         let commitment_spend =
2984                 if node_txn.len() == 1 {
2985                         &node_txn[0]
2986                 } else {
2987                         // Certain `ConnectStyle`s will cause RBF bumps of the previous HTLC transaction to be broadcast.
2988                         // FullBlockViaListen
2989                         if node_txn[0].input[0].previous_output.txid == node_a_commitment_tx[0].txid() {
2990                                 check_spends!(node_txn[1], commitment_tx[0]);
2991                                 check_spends!(node_txn[2], commitment_tx[0]);
2992                                 assert_ne!(node_txn[1].input[0].previous_output.vout, node_txn[2].input[0].previous_output.vout);
2993                                 &node_txn[0]
2994                         } else {
2995                                 check_spends!(node_txn[0], commitment_tx[0]);
2996                                 check_spends!(node_txn[1], commitment_tx[0]);
2997                                 assert_ne!(node_txn[0].input[0].previous_output.vout, node_txn[1].input[0].previous_output.vout);
2998                                 &node_txn[2]
2999                         }
3000                 };
3001
3002         check_spends!(commitment_spend, node_a_commitment_tx[0]);
3003         assert_eq!(commitment_spend.input.len(), 2);
3004         assert_eq!(commitment_spend.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3005         assert_eq!(commitment_spend.input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3006         assert_eq!(commitment_spend.lock_time.to_consensus_u32(), nodes[1].best_block_info().1);
3007         assert!(commitment_spend.output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3008         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
3009         // we already checked the same situation with A.
3010
3011         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
3012         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![node_a_commitment_tx[0].clone(), commitment_spend.clone()]));
3013         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3014         check_closed_broadcast!(nodes[0], true);
3015         check_added_monitors!(nodes[0], 1);
3016         let events = nodes[0].node.get_and_clear_pending_events();
3017         assert_eq!(events.len(), 5);
3018         let mut first_claimed = false;
3019         for event in events {
3020                 match event {
3021                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3022                                 if payment_preimage == our_payment_preimage && payment_hash == payment_hash_1 {
3023                                         assert!(!first_claimed);
3024                                         first_claimed = true;
3025                                 } else {
3026                                         assert_eq!(payment_preimage, our_payment_preimage_2);
3027                                         assert_eq!(payment_hash, payment_hash_2);
3028                                 }
3029                         },
3030                         Event::PaymentPathSuccessful { .. } => {},
3031                         Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {},
3032                         _ => panic!("Unexpected event"),
3033                 }
3034         }
3035         check_tx_local_broadcast!(nodes[0], true, node_a_commitment_tx[0]);
3036 }
3037
3038 fn do_test_htlc_on_chain_timeout(connect_style: ConnectStyle) {
3039         // Test that in case of a unilateral close onchain, we detect the state of output and
3040         // timeout the HTLC backward accordingly. So here we test that ChannelManager is
3041         // broadcasting the right event to other nodes in payment path.
3042         // A ------------------> B ----------------------> C (timeout)
3043         //    B's commitment tx                 C's commitment tx
3044         //            \                                  \
3045         //         B's HTLC timeout tx               B's timeout tx
3046
3047         let chanmon_cfgs = create_chanmon_cfgs(3);
3048         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3049         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3050         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3051         *nodes[0].connect_style.borrow_mut() = connect_style;
3052         *nodes[1].connect_style.borrow_mut() = connect_style;
3053         *nodes[2].connect_style.borrow_mut() = connect_style;
3054
3055         // Create some intial channels
3056         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3057         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3058
3059         // Rebalance the network a bit by relaying one payment thorugh all the channels...
3060         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3061         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3062
3063         let (_payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3064
3065         // Broadcast legit commitment tx from C on B's chain
3066         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
3067         check_spends!(commitment_tx[0], chan_2.3);
3068         nodes[2].node.fail_htlc_backwards(&payment_hash);
3069         check_added_monitors!(nodes[2], 0);
3070         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash.clone() }]);
3071         check_added_monitors!(nodes[2], 1);
3072
3073         let events = nodes[2].node.get_and_clear_pending_msg_events();
3074         assert_eq!(events.len(), 1);
3075         match events[0] {
3076                 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, .. } } => {
3077                         assert!(update_add_htlcs.is_empty());
3078                         assert!(!update_fail_htlcs.is_empty());
3079                         assert!(update_fulfill_htlcs.is_empty());
3080                         assert!(update_fail_malformed_htlcs.is_empty());
3081                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
3082                 },
3083                 _ => panic!("Unexpected event"),
3084         };
3085         mine_transaction(&nodes[2], &commitment_tx[0]);
3086         check_closed_broadcast!(nodes[2], true);
3087         check_added_monitors!(nodes[2], 1);
3088         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3089         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3090         assert_eq!(node_txn.len(), 0);
3091
3092         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
3093         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
3094         mine_transaction(&nodes[1], &commitment_tx[0]);
3095         check_closed_event!(&nodes[1], 1, ClosureReason::CommitmentTxConfirmed, false
3096                 , [nodes[2].node.get_our_node_id()], 100000);
3097         connect_blocks(&nodes[1], 200 - nodes[2].best_block_info().1);
3098         let timeout_tx = {
3099                 let mut txn = nodes[1].tx_broadcaster.txn_broadcast();
3100                 if nodes[1].connect_style.borrow().skips_blocks() {
3101                         assert_eq!(txn.len(), 1);
3102                 } else {
3103                         assert_eq!(txn.len(), 3); // Two extra fee bumps for timeout transaction
3104                 }
3105                 txn.iter().for_each(|tx| check_spends!(tx, commitment_tx[0]));
3106                 assert_eq!(txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3107                 txn.remove(0)
3108         };
3109
3110         mine_transaction(&nodes[1], &timeout_tx);
3111         check_added_monitors!(nodes[1], 1);
3112         check_closed_broadcast!(nodes[1], true);
3113
3114         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3115
3116         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3117         check_added_monitors!(nodes[1], 1);
3118         let events = nodes[1].node.get_and_clear_pending_msg_events();
3119         assert_eq!(events.len(), 1);
3120         match events[0] {
3121                 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, .. } } => {
3122                         assert!(update_add_htlcs.is_empty());
3123                         assert!(!update_fail_htlcs.is_empty());
3124                         assert!(update_fulfill_htlcs.is_empty());
3125                         assert!(update_fail_malformed_htlcs.is_empty());
3126                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3127                 },
3128                 _ => panic!("Unexpected event"),
3129         };
3130
3131         // Broadcast legit commitment tx from B on A's chain
3132         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
3133         check_spends!(commitment_tx[0], chan_1.3);
3134
3135         mine_transaction(&nodes[0], &commitment_tx[0]);
3136         connect_blocks(&nodes[0], TEST_FINAL_CLTV + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
3137
3138         check_closed_broadcast!(nodes[0], true);
3139         check_added_monitors!(nodes[0], 1);
3140         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
3141         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // 1 timeout tx
3142         assert_eq!(node_txn.len(), 1);
3143         check_spends!(node_txn[0], commitment_tx[0]);
3144         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3145 }
3146
3147 #[test]
3148 fn test_htlc_on_chain_timeout() {
3149         do_test_htlc_on_chain_timeout(ConnectStyle::BestBlockFirstSkippingBlocks);
3150         do_test_htlc_on_chain_timeout(ConnectStyle::TransactionsFirstSkippingBlocks);
3151         do_test_htlc_on_chain_timeout(ConnectStyle::FullBlockViaListen);
3152 }
3153
3154 #[test]
3155 fn test_simple_commitment_revoked_fail_backward() {
3156         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
3157         // and fail backward accordingly.
3158
3159         let chanmon_cfgs = create_chanmon_cfgs(3);
3160         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3161         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3162         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3163
3164         // Create some initial channels
3165         create_announced_chan_between_nodes(&nodes, 0, 1);
3166         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3167
3168         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3169         // Get the will-be-revoked local txn from nodes[2]
3170         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3171         // Revoke the old state
3172         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3173
3174         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
3175
3176         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3177         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3178         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3179         check_added_monitors!(nodes[1], 1);
3180         check_closed_broadcast!(nodes[1], true);
3181
3182         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
3183         check_added_monitors!(nodes[1], 1);
3184         let events = nodes[1].node.get_and_clear_pending_msg_events();
3185         assert_eq!(events.len(), 1);
3186         match events[0] {
3187                 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, .. } } => {
3188                         assert!(update_add_htlcs.is_empty());
3189                         assert_eq!(update_fail_htlcs.len(), 1);
3190                         assert!(update_fulfill_htlcs.is_empty());
3191                         assert!(update_fail_malformed_htlcs.is_empty());
3192                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3193
3194                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3195                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3196                         expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_2.0.contents.short_channel_id, true);
3197                 },
3198                 _ => panic!("Unexpected event"),
3199         }
3200 }
3201
3202 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
3203         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
3204         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
3205         // commitment transaction anymore.
3206         // To do this, we have the peer which will broadcast a revoked commitment transaction send
3207         // a number of update_fail/commitment_signed updates without ever sending the RAA in
3208         // response to our commitment_signed. This is somewhat misbehavior-y, though not
3209         // technically disallowed and we should probably handle it reasonably.
3210         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
3211         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
3212         // transactions:
3213         // * Once we move it out of our holding cell/add it, we will immediately include it in a
3214         //   commitment_signed (implying it will be in the latest remote commitment transaction).
3215         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
3216         //   and once they revoke the previous commitment transaction (allowing us to send a new
3217         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
3218         let chanmon_cfgs = create_chanmon_cfgs(3);
3219         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3220         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3221         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3222
3223         // Create some initial channels
3224         create_announced_chan_between_nodes(&nodes, 0, 1);
3225         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3226
3227         let (payment_preimage, _payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
3228         // Get the will-be-revoked local txn from nodes[2]
3229         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
3230         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
3231         // Revoke the old state
3232         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
3233
3234         let value = if use_dust {
3235                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
3236                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
3237                 nodes[2].node.per_peer_state.read().unwrap().get(&nodes[1].node.get_our_node_id())
3238                         .unwrap().lock().unwrap().channel_by_id.get(&chan_2.2).unwrap().context().holder_dust_limit_satoshis * 1000
3239         } else { 3000000 };
3240
3241         let (_, first_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3242         let (_, second_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3243         let (_, third_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
3244
3245         nodes[2].node.fail_htlc_backwards(&first_payment_hash);
3246         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: first_payment_hash }]);
3247         check_added_monitors!(nodes[2], 1);
3248         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3249         assert!(updates.update_add_htlcs.is_empty());
3250         assert!(updates.update_fulfill_htlcs.is_empty());
3251         assert!(updates.update_fail_malformed_htlcs.is_empty());
3252         assert_eq!(updates.update_fail_htlcs.len(), 1);
3253         assert!(updates.update_fee.is_none());
3254         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3255         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
3256         // Drop the last RAA from 3 -> 2
3257
3258         nodes[2].node.fail_htlc_backwards(&second_payment_hash);
3259         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: second_payment_hash }]);
3260         check_added_monitors!(nodes[2], 1);
3261         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3262         assert!(updates.update_add_htlcs.is_empty());
3263         assert!(updates.update_fulfill_htlcs.is_empty());
3264         assert!(updates.update_fail_malformed_htlcs.is_empty());
3265         assert_eq!(updates.update_fail_htlcs.len(), 1);
3266         assert!(updates.update_fee.is_none());
3267         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3268         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3269         check_added_monitors!(nodes[1], 1);
3270         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
3271         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3272         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3273         check_added_monitors!(nodes[2], 1);
3274
3275         nodes[2].node.fail_htlc_backwards(&third_payment_hash);
3276         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::FailedPayment { payment_hash: third_payment_hash }]);
3277         check_added_monitors!(nodes[2], 1);
3278         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3279         assert!(updates.update_add_htlcs.is_empty());
3280         assert!(updates.update_fulfill_htlcs.is_empty());
3281         assert!(updates.update_fail_malformed_htlcs.is_empty());
3282         assert_eq!(updates.update_fail_htlcs.len(), 1);
3283         assert!(updates.update_fee.is_none());
3284         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
3285         // At this point first_payment_hash has dropped out of the latest two commitment
3286         // transactions that nodes[1] is tracking...
3287         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
3288         check_added_monitors!(nodes[1], 1);
3289         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
3290         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
3291         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
3292         check_added_monitors!(nodes[2], 1);
3293
3294         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
3295         // on nodes[2]'s RAA.
3296         let (route, fourth_payment_hash, _, fourth_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 1000000);
3297         nodes[1].node.send_payment_with_route(&route, fourth_payment_hash,
3298                 RecipientOnionFields::secret_only(fourth_payment_secret), PaymentId(fourth_payment_hash.0)).unwrap();
3299         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3300         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3301         check_added_monitors!(nodes[1], 0);
3302
3303         if deliver_bs_raa {
3304                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
3305                 // One monitor for the new revocation preimage, no second on as we won't generate a new
3306                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
3307                 check_added_monitors!(nodes[1], 1);
3308                 let events = nodes[1].node.get_and_clear_pending_events();
3309                 assert_eq!(events.len(), 2);
3310                 match events[0] {
3311                         Event::PendingHTLCsForwardable { .. } => { },
3312                         _ => panic!("Unexpected event"),
3313                 };
3314                 match events[1] {
3315                         Event::HTLCHandlingFailed { .. } => { },
3316                         _ => panic!("Unexpected event"),
3317                 }
3318                 // Deliberately don't process the pending fail-back so they all fail back at once after
3319                 // block connection just like the !deliver_bs_raa case
3320         }
3321
3322         let mut failed_htlcs = HashSet::new();
3323         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3324
3325         mine_transaction(&nodes[1], &revoked_local_txn[0]);
3326         check_added_monitors!(nodes[1], 1);
3327         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
3328
3329         let events = nodes[1].node.get_and_clear_pending_events();
3330         assert_eq!(events.len(), if deliver_bs_raa { 3 + nodes.len() - 1 } else { 4 + nodes.len() });
3331         assert!(events.iter().any(|ev| matches!(
3332                 ev,
3333                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. }
3334         )));
3335         assert!(events.iter().any(|ev| matches!(
3336                 ev,
3337                 Event::PaymentPathFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3338         )));
3339         assert!(events.iter().any(|ev| matches!(
3340                 ev,
3341                 Event::PaymentFailed { ref payment_hash, .. } if *payment_hash == fourth_payment_hash
3342         )));
3343
3344         nodes[1].node.process_pending_htlc_forwards();
3345         check_added_monitors!(nodes[1], 1);
3346
3347         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
3348         assert_eq!(events.len(), if deliver_bs_raa { 4 } else { 3 });
3349
3350         if deliver_bs_raa {
3351                 let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3352                 match nodes_2_event {
3353                         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, .. } } => {
3354                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
3355                                 assert_eq!(update_add_htlcs.len(), 1);
3356                                 assert!(update_fulfill_htlcs.is_empty());
3357                                 assert!(update_fail_htlcs.is_empty());
3358                                 assert!(update_fail_malformed_htlcs.is_empty());
3359                         },
3360                         _ => panic!("Unexpected event"),
3361                 }
3362         }
3363
3364         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut events);
3365         match nodes_2_event {
3366                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { msg: Some(msgs::ErrorMessage { channel_id, ref data }) }, node_id: _ } => {
3367                         assert_eq!(channel_id, chan_2.2);
3368                         assert_eq!(data.as_str(), "Channel closed because commitment or closing transaction was confirmed on chain.");
3369                 },
3370                 _ => panic!("Unexpected event"),
3371         }
3372
3373         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut events);
3374         match nodes_0_event {
3375                 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, .. } } => {
3376                         assert!(update_add_htlcs.is_empty());
3377                         assert_eq!(update_fail_htlcs.len(), 3);
3378                         assert!(update_fulfill_htlcs.is_empty());
3379                         assert!(update_fail_malformed_htlcs.is_empty());
3380                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3381
3382                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3383                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
3384                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
3385
3386                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
3387
3388                         let events = nodes[0].node.get_and_clear_pending_events();
3389                         assert_eq!(events.len(), 6);
3390                         match events[0] {
3391                                 Event::PaymentPathFailed { ref payment_hash, ref failure, .. } => {
3392                                         assert!(failed_htlcs.insert(payment_hash.0));
3393                                         // If we delivered B's RAA we got an unknown preimage error, not something
3394                                         // that we should update our routing table for.
3395                                         if !deliver_bs_raa {
3396                                                 if let PathFailure::OnPath { network_update: Some(_) } = failure { } else { panic!("Unexpected path failure") }
3397                                         }
3398                                 },
3399                                 _ => panic!("Unexpected event"),
3400                         }
3401                         match events[1] {
3402                                 Event::PaymentFailed { ref payment_hash, .. } => {
3403                                         assert_eq!(*payment_hash, first_payment_hash);
3404                                 },
3405                                 _ => panic!("Unexpected event"),
3406                         }
3407                         match events[2] {
3408                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3409                                         assert!(failed_htlcs.insert(payment_hash.0));
3410                                 },
3411                                 _ => panic!("Unexpected event"),
3412                         }
3413                         match events[3] {
3414                                 Event::PaymentFailed { ref payment_hash, .. } => {
3415                                         assert_eq!(*payment_hash, second_payment_hash);
3416                                 },
3417                                 _ => panic!("Unexpected event"),
3418                         }
3419                         match events[4] {
3420                                 Event::PaymentPathFailed { ref payment_hash, failure: PathFailure::OnPath { network_update: Some(_) }, .. } => {
3421                                         assert!(failed_htlcs.insert(payment_hash.0));
3422                                 },
3423                                 _ => panic!("Unexpected event"),
3424                         }
3425                         match events[5] {
3426                                 Event::PaymentFailed { ref payment_hash, .. } => {
3427                                         assert_eq!(*payment_hash, third_payment_hash);
3428                                 },
3429                                 _ => panic!("Unexpected event"),
3430                         }
3431                 },
3432                 _ => panic!("Unexpected event"),
3433         }
3434
3435         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
3436         match events[0] {
3437                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
3438                 _ => panic!("Unexpected event"),
3439         }
3440
3441         assert!(failed_htlcs.contains(&first_payment_hash.0));
3442         assert!(failed_htlcs.contains(&second_payment_hash.0));
3443         assert!(failed_htlcs.contains(&third_payment_hash.0));
3444 }
3445
3446 #[test]
3447 fn test_commitment_revoked_fail_backward_exhaustive_a() {
3448         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
3449         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
3450         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
3451         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
3452 }
3453
3454 #[test]
3455 fn test_commitment_revoked_fail_backward_exhaustive_b() {
3456         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
3457         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
3458         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
3459         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
3460 }
3461
3462 #[test]
3463 fn fail_backward_pending_htlc_upon_channel_failure() {
3464         let chanmon_cfgs = create_chanmon_cfgs(2);
3465         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3466         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3467         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3468         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000);
3469
3470         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
3471         {
3472                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3473                 nodes[0].node.send_payment_with_route(&route, payment_hash, RecipientOnionFields::secret_only(payment_secret),
3474                         PaymentId(payment_hash.0)).unwrap();
3475                 check_added_monitors!(nodes[0], 1);
3476
3477                 let payment_event = {
3478                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3479                         assert_eq!(events.len(), 1);
3480                         SendEvent::from_event(events.remove(0))
3481                 };
3482                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
3483                 assert_eq!(payment_event.msgs.len(), 1);
3484         }
3485
3486         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
3487         let (route, failed_payment_hash, _, failed_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 50_000);
3488         {
3489                 nodes[0].node.send_payment_with_route(&route, failed_payment_hash,
3490                         RecipientOnionFields::secret_only(failed_payment_secret), PaymentId(failed_payment_hash.0)).unwrap();
3491                 check_added_monitors!(nodes[0], 0);
3492
3493                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3494         }
3495
3496         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
3497         {
3498                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 50_000);
3499
3500                 let secp_ctx = Secp256k1::new();
3501                 let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
3502                 let current_height = nodes[1].node.best_block.read().unwrap().height() + 1;
3503                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(
3504                         &route.paths[0], 50_000, RecipientOnionFields::secret_only(payment_secret), current_height, &None).unwrap();
3505                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3506                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash).unwrap();
3507
3508                 // Send a 0-msat update_add_htlc to fail the channel.
3509                 let update_add_htlc = msgs::UpdateAddHTLC {
3510                         channel_id: chan.2,
3511                         htlc_id: 0,
3512                         amount_msat: 0,
3513                         payment_hash,
3514                         cltv_expiry,
3515                         onion_routing_packet,
3516                         skimmed_fee_msat: None,
3517                         blinding_point: None,
3518                 };
3519                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3520         }
3521         let events = nodes[0].node.get_and_clear_pending_events();
3522         assert_eq!(events.len(), 3);
3523         // Check that Alice fails backward the pending HTLC from the second payment.
3524         match events[0] {
3525                 Event::PaymentPathFailed { payment_hash, .. } => {
3526                         assert_eq!(payment_hash, failed_payment_hash);
3527                 },
3528                 _ => panic!("Unexpected event"),
3529         }
3530         match events[1] {
3531                 Event::PaymentFailed { payment_hash, .. } => {
3532                         assert_eq!(payment_hash, failed_payment_hash);
3533                 },
3534                 _ => panic!("Unexpected event"),
3535         }
3536         match events[2] {
3537                 Event::ChannelClosed { reason: ClosureReason::ProcessingError { ref err }, .. } => {
3538                         assert_eq!(err, "Remote side tried to send a 0-msat HTLC");
3539                 },
3540                 _ => panic!("Unexpected event {:?}", events[1]),
3541         }
3542         check_closed_broadcast!(nodes[0], true);
3543         check_added_monitors!(nodes[0], 1);
3544 }
3545
3546 #[test]
3547 fn test_htlc_ignore_latest_remote_commitment() {
3548         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3549         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3550         let chanmon_cfgs = create_chanmon_cfgs(2);
3551         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3552         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3553         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3554         if *nodes[1].connect_style.borrow() == ConnectStyle::FullBlockViaListen {
3555                 // We rely on the ability to connect a block redundantly, which isn't allowed via
3556                 // `chain::Listen`, so we never run the test if we randomly get assigned that
3557                 // connect_style.
3558                 return;
3559         }
3560         let funding_tx = create_announced_chan_between_nodes(&nodes, 0, 1).3;
3561
3562         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3563         nodes[0].node.force_close_broadcasting_latest_txn(&nodes[0].node.list_channels()[0].channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3564         connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + 1);
3565         check_closed_broadcast!(nodes[0], true);
3566         check_added_monitors!(nodes[0], 1);
3567         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3568
3569         let node_txn = nodes[0].tx_broadcaster.unique_txn_broadcast();
3570         assert_eq!(node_txn.len(), 2);
3571         check_spends!(node_txn[0], funding_tx);
3572         check_spends!(node_txn[1], node_txn[0]);
3573
3574         let block = create_dummy_block(nodes[1].best_block_hash(), 42, vec![node_txn[0].clone()]);
3575         connect_block(&nodes[1], &block);
3576         check_closed_broadcast!(nodes[1], true);
3577         check_added_monitors!(nodes[1], 1);
3578         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
3579
3580         // Duplicate the connect_block call since this may happen due to other listeners
3581         // registering new transactions
3582         connect_block(&nodes[1], &block);
3583 }
3584
3585 #[test]
3586 fn test_force_close_fail_back() {
3587         // Check which HTLCs are failed-backwards on channel force-closure
3588         let chanmon_cfgs = create_chanmon_cfgs(3);
3589         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3590         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3591         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3592         create_announced_chan_between_nodes(&nodes, 0, 1);
3593         create_announced_chan_between_nodes(&nodes, 1, 2);
3594
3595         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 1000000);
3596
3597         let mut payment_event = {
3598                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
3599                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
3600                 check_added_monitors!(nodes[0], 1);
3601
3602                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3603                 assert_eq!(events.len(), 1);
3604                 SendEvent::from_event(events.remove(0))
3605         };
3606
3607         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3608         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3609
3610         expect_pending_htlcs_forwardable!(nodes[1]);
3611
3612         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3613         assert_eq!(events_2.len(), 1);
3614         payment_event = SendEvent::from_event(events_2.remove(0));
3615         assert_eq!(payment_event.msgs.len(), 1);
3616
3617         check_added_monitors!(nodes[1], 1);
3618         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3619         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3620         check_added_monitors!(nodes[2], 1);
3621         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3622
3623         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3624         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3625         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3626
3627         nodes[2].node.force_close_broadcasting_latest_txn(&payment_event.commitment_msg.channel_id, &nodes[1].node.get_our_node_id()).unwrap();
3628         check_closed_broadcast!(nodes[2], true);
3629         check_added_monitors!(nodes[2], 1);
3630         check_closed_event!(nodes[2], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
3631         let commitment_tx = {
3632                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3633                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3634                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3635                 // back to nodes[1] upon timeout otherwise.
3636                 assert_eq!(node_txn.len(), 1);
3637                 node_txn.remove(0)
3638         };
3639
3640         mine_transaction(&nodes[1], &commitment_tx);
3641
3642         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3643         check_closed_broadcast!(nodes[1], true);
3644         check_added_monitors!(nodes[1], 1);
3645         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
3646
3647         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3648         {
3649                 get_monitor!(nodes[2], payment_event.commitment_msg.channel_id)
3650                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage, &node_cfgs[2].tx_broadcaster, &LowerBoundedFeeEstimator::new(node_cfgs[2].fee_estimator), &node_cfgs[2].logger);
3651         }
3652         mine_transaction(&nodes[2], &commitment_tx);
3653         let mut node_txn = nodes[2].tx_broadcaster.txn_broadcast();
3654         assert_eq!(node_txn.len(), if nodes[2].connect_style.borrow().updates_best_block_first() { 2 } else { 1 });
3655         let htlc_tx = node_txn.pop().unwrap();
3656         assert_eq!(htlc_tx.input.len(), 1);
3657         assert_eq!(htlc_tx.input[0].previous_output.txid, commitment_tx.txid());
3658         assert_eq!(htlc_tx.lock_time, LockTime::ZERO); // Must be an HTLC-Success
3659         assert_eq!(htlc_tx.input[0].witness.len(), 5); // Must be an HTLC-Success
3660
3661         check_spends!(htlc_tx, commitment_tx);
3662 }
3663
3664 #[test]
3665 fn test_dup_events_on_peer_disconnect() {
3666         // Test that if we receive a duplicative update_fulfill_htlc message after a reconnect we do
3667         // not generate a corresponding duplicative PaymentSent event. This did not use to be the case
3668         // as we used to generate the event immediately upon receipt of the payment preimage in the
3669         // update_fulfill_htlc message.
3670
3671         let chanmon_cfgs = create_chanmon_cfgs(2);
3672         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3673         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3674         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3675         create_announced_chan_between_nodes(&nodes, 0, 1);
3676
3677         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
3678
3679         nodes[1].node.claim_funds(payment_preimage);
3680         expect_payment_claimed!(nodes[1], payment_hash, 1_000_000);
3681         check_added_monitors!(nodes[1], 1);
3682         let claim_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3683         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &claim_msgs.update_fulfill_htlcs[0]);
3684         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
3685
3686         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3687         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3688
3689         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3690         reconnect_args.pending_htlc_claims.0 = 1;
3691         reconnect_nodes(reconnect_args);
3692         expect_payment_path_successful!(nodes[0]);
3693 }
3694
3695 #[test]
3696 fn test_peer_disconnected_before_funding_broadcasted() {
3697         // Test that channels are closed with `ClosureReason::DisconnectedPeer` if the peer disconnects
3698         // before the funding transaction has been broadcasted.
3699         let chanmon_cfgs = create_chanmon_cfgs(2);
3700         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3701         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3702         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3703
3704         // Open a channel between `nodes[0]` and `nodes[1]`, for which the funding transaction is never
3705         // broadcasted, even though it's created by `nodes[0]`.
3706         let expected_temporary_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
3707         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
3708         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
3709         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
3710         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
3711
3712         let (temporary_channel_id, tx, _funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
3713         assert_eq!(temporary_channel_id, expected_temporary_channel_id);
3714
3715         assert!(nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
3716
3717         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
3718         assert_eq!(funding_created_msg.temporary_channel_id, expected_temporary_channel_id);
3719
3720         // Even though the funding transaction is created by `nodes[0]`, the `FundingCreated` msg is
3721         // never sent to `nodes[1]`, and therefore the tx is never signed by either party nor
3722         // broadcasted.
3723         {
3724                 assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
3725         }
3726
3727         // Ensure that the channel is closed with `ClosureReason::DisconnectedPeer` when the peers are
3728         // disconnected before the funding transaction was broadcasted.
3729         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3730         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3731
3732         check_closed_event!(&nodes[0], 2, ClosureReason::DisconnectedPeer, true
3733                 , [nodes[1].node.get_our_node_id()], 1000000);
3734         check_closed_event!(&nodes[1], 1, ClosureReason::DisconnectedPeer, false
3735                 , [nodes[0].node.get_our_node_id()], 1000000);
3736 }
3737
3738 #[test]
3739 fn test_simple_peer_disconnect() {
3740         // Test that we can reconnect when there are no lost messages
3741         let chanmon_cfgs = create_chanmon_cfgs(3);
3742         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3743         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3744         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3745         create_announced_chan_between_nodes(&nodes, 0, 1);
3746         create_announced_chan_between_nodes(&nodes, 1, 2);
3747
3748         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3749         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3750         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3751         reconnect_args.send_channel_ready = (true, true);
3752         reconnect_nodes(reconnect_args);
3753
3754         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3755         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3756         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3757         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
3758
3759         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3760         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3761         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3762
3763         let (payment_preimage_3, payment_hash_3, ..) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000);
3764         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3765         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3766         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3767
3768         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3769         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3770
3771         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_preimage_3);
3772         fail_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[2]]], true, payment_hash_5);
3773
3774         let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3775         reconnect_args.pending_cell_htlc_fails.0 = 1;
3776         reconnect_args.pending_cell_htlc_claims.0 = 1;
3777         reconnect_nodes(reconnect_args);
3778         {
3779                 let events = nodes[0].node.get_and_clear_pending_events();
3780                 assert_eq!(events.len(), 4);
3781                 match events[0] {
3782                         Event::PaymentSent { payment_preimage, payment_hash, .. } => {
3783                                 assert_eq!(payment_preimage, payment_preimage_3);
3784                                 assert_eq!(payment_hash, payment_hash_3);
3785                         },
3786                         _ => panic!("Unexpected event"),
3787                 }
3788                 match events[1] {
3789                         Event::PaymentPathSuccessful { .. } => {},
3790                         _ => panic!("Unexpected event"),
3791                 }
3792                 match events[2] {
3793                         Event::PaymentPathFailed { payment_hash, payment_failed_permanently, .. } => {
3794                                 assert_eq!(payment_hash, payment_hash_5);
3795                                 assert!(payment_failed_permanently);
3796                         },
3797                         _ => panic!("Unexpected event"),
3798                 }
3799                 match events[3] {
3800                         Event::PaymentFailed { payment_hash, .. } => {
3801                                 assert_eq!(payment_hash, payment_hash_5);
3802                         },
3803                         _ => panic!("Unexpected event"),
3804                 }
3805         }
3806         check_added_monitors(&nodes[0], 1);
3807
3808         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
3809         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3810 }
3811
3812 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8, simulate_broken_lnd: bool) {
3813         // Test that we can reconnect when in-flight HTLC updates get dropped
3814         let chanmon_cfgs = create_chanmon_cfgs(2);
3815         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3816         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3817         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3818
3819         let mut as_channel_ready = None;
3820         let channel_id = if messages_delivered == 0 {
3821                 let (channel_ready, chan_id, _) = create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
3822                 as_channel_ready = Some(channel_ready);
3823                 // nodes[1] doesn't receive the channel_ready message (it'll be re-sent on reconnect)
3824                 // Note that we store it so that if we're running with `simulate_broken_lnd` we can deliver
3825                 // it before the channel_reestablish message.
3826                 chan_id
3827         } else {
3828                 create_announced_chan_between_nodes(&nodes, 0, 1).2
3829         };
3830
3831         let (route, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], 1_000_000);
3832
3833         let payment_event = {
3834                 nodes[0].node.send_payment_with_route(&route, payment_hash_1,
3835                         RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
3836                 check_added_monitors!(nodes[0], 1);
3837
3838                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3839                 assert_eq!(events.len(), 1);
3840                 SendEvent::from_event(events.remove(0))
3841         };
3842         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3843
3844         if messages_delivered < 2 {
3845                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3846         } else {
3847                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3848                 if messages_delivered >= 3 {
3849                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3850                         check_added_monitors!(nodes[1], 1);
3851                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3852
3853                         if messages_delivered >= 4 {
3854                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3855                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3856                                 check_added_monitors!(nodes[0], 1);
3857
3858                                 if messages_delivered >= 5 {
3859                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3860                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3861                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3862                                         check_added_monitors!(nodes[0], 1);
3863
3864                                         if messages_delivered >= 6 {
3865                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3866                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3867                                                 check_added_monitors!(nodes[1], 1);
3868                                         }
3869                                 }
3870                         }
3871                 }
3872         }
3873
3874         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3875         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3876         if messages_delivered < 3 {
3877                 if simulate_broken_lnd {
3878                         // lnd has a long-standing bug where they send a channel_ready prior to a
3879                         // channel_reestablish if you reconnect prior to channel_ready time.
3880                         //
3881                         // Here we simulate that behavior, delivering a channel_ready immediately on
3882                         // reconnect. Note that we don't bother skipping the now-duplicate channel_ready sent
3883                         // in `reconnect_nodes` but we currently don't fail based on that.
3884                         //
3885                         // See-also <https://github.com/lightningnetwork/lnd/issues/4006>
3886                         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready.as_ref().unwrap().0);
3887                 }
3888                 // Even if the channel_ready messages get exchanged, as long as nothing further was
3889                 // received on either side, both sides will need to resend them.
3890                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3891                 reconnect_args.send_channel_ready = (true, true);
3892                 reconnect_args.pending_htlc_adds.1 = 1;
3893                 reconnect_nodes(reconnect_args);
3894         } else if messages_delivered == 3 {
3895                 // nodes[0] still wants its RAA + commitment_signed
3896                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3897                 reconnect_args.pending_responding_commitment_signed.0 = true;
3898                 reconnect_args.pending_raa.0 = true;
3899                 reconnect_nodes(reconnect_args);
3900         } else if messages_delivered == 4 {
3901                 // nodes[0] still wants its commitment_signed
3902                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3903                 reconnect_args.pending_responding_commitment_signed.0 = true;
3904                 reconnect_nodes(reconnect_args);
3905         } else if messages_delivered == 5 {
3906                 // nodes[1] still wants its final RAA
3907                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
3908                 reconnect_args.pending_raa.1 = true;
3909                 reconnect_nodes(reconnect_args);
3910         } else if messages_delivered == 6 {
3911                 // Everything was delivered...
3912                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3913         }
3914
3915         let events_1 = nodes[1].node.get_and_clear_pending_events();
3916         if messages_delivered == 0 {
3917                 assert_eq!(events_1.len(), 2);
3918                 match events_1[0] {
3919                         Event::ChannelReady { .. } => { },
3920                         _ => panic!("Unexpected event"),
3921                 };
3922                 match events_1[1] {
3923                         Event::PendingHTLCsForwardable { .. } => { },
3924                         _ => panic!("Unexpected event"),
3925                 };
3926         } else {
3927                 assert_eq!(events_1.len(), 1);
3928                 match events_1[0] {
3929                         Event::PendingHTLCsForwardable { .. } => { },
3930                         _ => panic!("Unexpected event"),
3931                 };
3932         }
3933
3934         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
3935         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
3936         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
3937
3938         nodes[1].node.process_pending_htlc_forwards();
3939
3940         let events_2 = nodes[1].node.get_and_clear_pending_events();
3941         assert_eq!(events_2.len(), 1);
3942         match events_2[0] {
3943                 Event::PaymentClaimable { ref payment_hash, ref purpose, amount_msat, receiver_node_id, via_channel_id, .. } => {
3944                         assert_eq!(payment_hash_1, *payment_hash);
3945                         assert_eq!(amount_msat, 1_000_000);
3946                         assert_eq!(receiver_node_id.unwrap(), nodes[1].node.get_our_node_id());
3947                         assert_eq!(via_channel_id, Some(channel_id));
3948                         match &purpose {
3949                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
3950                                         assert!(payment_preimage.is_none());
3951                                         assert_eq!(payment_secret_1, *payment_secret);
3952                                 },
3953                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
3954                         }
3955                 },
3956                 _ => panic!("Unexpected event"),
3957         }
3958
3959         nodes[1].node.claim_funds(payment_preimage_1);
3960         check_added_monitors!(nodes[1], 1);
3961         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
3962
3963         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3964         assert_eq!(events_3.len(), 1);
3965         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3966                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3967                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3968                         assert!(updates.update_add_htlcs.is_empty());
3969                         assert!(updates.update_fail_htlcs.is_empty());
3970                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3971                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3972                         assert!(updates.update_fee.is_none());
3973                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3974                 },
3975                 _ => panic!("Unexpected event"),
3976         };
3977
3978         if messages_delivered >= 1 {
3979                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3980
3981                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3982                 assert_eq!(events_4.len(), 1);
3983                 match events_4[0] {
3984                         Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
3985                                 assert_eq!(payment_preimage_1, *payment_preimage);
3986                                 assert_eq!(payment_hash_1, *payment_hash);
3987                         },
3988                         _ => panic!("Unexpected event"),
3989                 }
3990
3991                 if messages_delivered >= 2 {
3992                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3993                         check_added_monitors!(nodes[0], 1);
3994                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3995
3996                         if messages_delivered >= 3 {
3997                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3998                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3999                                 check_added_monitors!(nodes[1], 1);
4000
4001                                 if messages_delivered >= 4 {
4002                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
4003                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4004                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4005                                         check_added_monitors!(nodes[1], 1);
4006
4007                                         if messages_delivered >= 5 {
4008                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4009                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4010                                                 check_added_monitors!(nodes[0], 1);
4011                                         }
4012                                 }
4013                         }
4014                 }
4015         }
4016
4017         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4018         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4019         if messages_delivered < 2 {
4020                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4021                 reconnect_args.pending_htlc_claims.0 = 1;
4022                 reconnect_nodes(reconnect_args);
4023                 if messages_delivered < 1 {
4024                         expect_payment_sent!(nodes[0], payment_preimage_1);
4025                 } else {
4026                         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4027                 }
4028         } else if messages_delivered == 2 {
4029                 // nodes[0] still wants its RAA + commitment_signed
4030                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4031                 reconnect_args.pending_responding_commitment_signed.1 = true;
4032                 reconnect_args.pending_raa.1 = true;
4033                 reconnect_nodes(reconnect_args);
4034         } else if messages_delivered == 3 {
4035                 // nodes[0] still wants its commitment_signed
4036                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4037                 reconnect_args.pending_responding_commitment_signed.1 = true;
4038                 reconnect_nodes(reconnect_args);
4039         } else if messages_delivered == 4 {
4040                 // nodes[1] still wants its final RAA
4041                 let mut reconnect_args = ReconnectArgs::new(&nodes[0], &nodes[1]);
4042                 reconnect_args.pending_raa.0 = true;
4043                 reconnect_nodes(reconnect_args);
4044         } else if messages_delivered == 5 {
4045                 // Everything was delivered...
4046                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4047         }
4048
4049         if messages_delivered == 1 || messages_delivered == 2 {
4050                 expect_payment_path_successful!(nodes[0]);
4051         }
4052         if messages_delivered <= 5 {
4053                 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4054                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4055         }
4056         reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
4057
4058         if messages_delivered > 2 {
4059                 expect_payment_path_successful!(nodes[0]);
4060         }
4061
4062         // Channel should still work fine...
4063         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4064         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
4065         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4066 }
4067
4068 #[test]
4069 fn test_drop_messages_peer_disconnect_a() {
4070         do_test_drop_messages_peer_disconnect(0, true);
4071         do_test_drop_messages_peer_disconnect(0, false);
4072         do_test_drop_messages_peer_disconnect(1, false);
4073         do_test_drop_messages_peer_disconnect(2, false);
4074 }
4075
4076 #[test]
4077 fn test_drop_messages_peer_disconnect_b() {
4078         do_test_drop_messages_peer_disconnect(3, false);
4079         do_test_drop_messages_peer_disconnect(4, false);
4080         do_test_drop_messages_peer_disconnect(5, false);
4081         do_test_drop_messages_peer_disconnect(6, false);
4082 }
4083
4084 #[test]
4085 fn test_channel_ready_without_best_block_updated() {
4086         // Previously, if we were offline when a funding transaction was locked in, and then we came
4087         // back online, calling best_block_updated once followed by transactions_confirmed, we'd not
4088         // generate a channel_ready until a later best_block_updated. This tests that we generate the
4089         // channel_ready immediately instead.
4090         let chanmon_cfgs = create_chanmon_cfgs(2);
4091         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4092         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4093         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4094         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
4095
4096         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4097
4098         let conf_height = nodes[0].best_block_info().1 + 1;
4099         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4100         let block_txn = [funding_tx];
4101         let conf_txn: Vec<_> = block_txn.iter().enumerate().collect();
4102         let conf_block_header = nodes[0].get_block_header(conf_height);
4103         nodes[0].node.transactions_confirmed(&conf_block_header, &conf_txn[..], conf_height);
4104
4105         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4106         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4107         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4108 }
4109
4110 #[test]
4111 fn test_channel_monitor_skipping_block_when_channel_manager_is_leading() {
4112         let chanmon_cfgs = create_chanmon_cfgs(2);
4113         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4114         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4115         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4116
4117         // Let channel_manager get ahead of chain_monitor by 1 block.
4118         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4119         // in case where client calls block_connect on channel_manager first and then on chain_monitor.
4120         let height_1 = nodes[0].best_block_info().1 + 1;
4121         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4122
4123         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4124         nodes[0].node.block_connected(&block_1, height_1);
4125
4126         // Create channel, and it gets added to chain_monitor in funding_created.
4127         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4128
4129         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1,
4130         // but it's best_block is block_1, since that was populated by channel_manager, and channel_manager
4131         // was running ahead of chain_monitor at the time of funding_created.
4132         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4133         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4134         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4135         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4136
4137         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4138         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4139         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4140 }
4141
4142 #[test]
4143 fn test_channel_monitor_skipping_block_when_channel_manager_is_lagging() {
4144         let chanmon_cfgs = create_chanmon_cfgs(2);
4145         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4146         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4147         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4148
4149         // Let chain_monitor get ahead of channel_manager by 1 block.
4150         // This is to emulate race-condition where newly added channel_monitor skips processing 1 block,
4151         // in case where client calls block_connect on chain_monitor first and then on channel_manager.
4152         let height_1 = nodes[0].best_block_info().1 + 1;
4153         let mut block_1 = create_dummy_block(nodes[0].best_block_hash(), height_1, Vec::new());
4154
4155         nodes[0].blocks.lock().unwrap().push((block_1.clone(), height_1));
4156         nodes[0].chain_monitor.chain_monitor.block_connected(&block_1, height_1);
4157
4158         // Create channel, and it gets added to chain_monitor in funding_created.
4159         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
4160
4161         // channel_manager can't really skip block_1, it should get it eventually.
4162         nodes[0].node.block_connected(&block_1, height_1);
4163
4164         // Now, newly added channel_monitor in chain_monitor hasn't processed block_1, it's best_block is
4165         // the block before block_1, since that was populated by channel_manager, and channel_manager was
4166         // running behind at the time of funding_created.
4167         // Later on, subsequent blocks are connected to both channel_manager and chain_monitor.
4168         // Hence, this channel's channel_monitor skipped block_1, directly tries to process subsequent blocks.
4169         confirm_transaction_at(&nodes[0], &funding_tx, nodes[0].best_block_info().1 + 1);
4170         connect_blocks(&nodes[0], CHAN_CONFIRM_DEPTH);
4171
4172         // Ensure nodes[0] generates a channel_ready after the transactions_confirmed
4173         let as_channel_ready = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id());
4174         nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &as_channel_ready);
4175 }
4176
4177 #[test]
4178 fn test_drop_messages_peer_disconnect_dual_htlc() {
4179         // Test that we can handle reconnecting when both sides of a channel have pending
4180         // commitment_updates when we disconnect.
4181         let chanmon_cfgs = create_chanmon_cfgs(2);
4182         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4183         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4184         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4185         create_announced_chan_between_nodes(&nodes, 0, 1);
4186
4187         let (payment_preimage_1, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
4188
4189         // Now try to send a second payment which will fail to send
4190         let (route, payment_hash_2, payment_preimage_2, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
4191         nodes[0].node.send_payment_with_route(&route, payment_hash_2,
4192                 RecipientOnionFields::secret_only(payment_secret_2), PaymentId(payment_hash_2.0)).unwrap();
4193         check_added_monitors!(nodes[0], 1);
4194
4195         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
4196         assert_eq!(events_1.len(), 1);
4197         match events_1[0] {
4198                 MessageSendEvent::UpdateHTLCs { .. } => {},
4199                 _ => panic!("Unexpected event"),
4200         }
4201
4202         nodes[1].node.claim_funds(payment_preimage_1);
4203         expect_payment_claimed!(nodes[1], payment_hash_1, 1_000_000);
4204         check_added_monitors!(nodes[1], 1);
4205
4206         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
4207         assert_eq!(events_2.len(), 1);
4208         match events_2[0] {
4209                 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 } } => {
4210                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
4211                         assert!(update_add_htlcs.is_empty());
4212                         assert_eq!(update_fulfill_htlcs.len(), 1);
4213                         assert!(update_fail_htlcs.is_empty());
4214                         assert!(update_fail_malformed_htlcs.is_empty());
4215                         assert!(update_fee.is_none());
4216
4217                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
4218                         let events_3 = nodes[0].node.get_and_clear_pending_events();
4219                         assert_eq!(events_3.len(), 1);
4220                         match events_3[0] {
4221                                 Event::PaymentSent { ref payment_preimage, ref payment_hash, .. } => {
4222                                         assert_eq!(*payment_preimage, payment_preimage_1);
4223                                         assert_eq!(*payment_hash, payment_hash_1);
4224                                 },
4225                                 _ => panic!("Unexpected event"),
4226                         }
4227
4228                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
4229                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4230                         // No commitment_signed so get_event_msg's assert(len == 1) passes
4231                         check_added_monitors!(nodes[0], 1);
4232                 },
4233                 _ => panic!("Unexpected event"),
4234         }
4235
4236         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
4237         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
4238
4239         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
4240                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
4241         }, true).unwrap();
4242         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4243         assert_eq!(reestablish_1.len(), 1);
4244         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
4245                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
4246         }, false).unwrap();
4247         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4248         assert_eq!(reestablish_2.len(), 1);
4249
4250         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4251         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
4252         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4253         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
4254
4255         assert!(as_resp.0.is_none());
4256         assert!(bs_resp.0.is_none());
4257
4258         assert!(bs_resp.1.is_none());
4259         assert!(bs_resp.2.is_none());
4260
4261         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
4262
4263         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
4264         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
4265         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
4266         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
4267         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
4268         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
4269         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
4270         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4271         // No commitment_signed so get_event_msg's assert(len == 1) passes
4272         check_added_monitors!(nodes[1], 1);
4273
4274         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
4275         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4276         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
4277         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
4278         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
4279         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
4280         assert!(bs_second_commitment_signed.update_fee.is_none());
4281         check_added_monitors!(nodes[1], 1);
4282
4283         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4284         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4285         assert!(as_commitment_signed.update_add_htlcs.is_empty());
4286         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
4287         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
4288         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
4289         assert!(as_commitment_signed.update_fee.is_none());
4290         check_added_monitors!(nodes[0], 1);
4291
4292         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
4293         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
4294         // No commitment_signed so get_event_msg's assert(len == 1) passes
4295         check_added_monitors!(nodes[0], 1);
4296
4297         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
4298         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4299         // No commitment_signed so get_event_msg's assert(len == 1) passes
4300         check_added_monitors!(nodes[1], 1);
4301
4302         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
4303         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4304         check_added_monitors!(nodes[1], 1);
4305
4306         expect_pending_htlcs_forwardable!(nodes[1]);
4307
4308         let events_5 = nodes[1].node.get_and_clear_pending_events();
4309         assert_eq!(events_5.len(), 1);
4310         match events_5[0] {
4311                 Event::PaymentClaimable { ref payment_hash, ref purpose, .. } => {
4312                         assert_eq!(payment_hash_2, *payment_hash);
4313                         match &purpose {
4314                                 PaymentPurpose::InvoicePayment { payment_preimage, payment_secret, .. } => {
4315                                         assert!(payment_preimage.is_none());
4316                                         assert_eq!(payment_secret_2, *payment_secret);
4317                                 },
4318                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
4319                         }
4320                 },
4321                 _ => panic!("Unexpected event"),
4322         }
4323
4324         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
4325         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4326         check_added_monitors!(nodes[0], 1);
4327
4328         expect_payment_path_successful!(nodes[0]);
4329         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
4330 }
4331
4332 fn do_test_htlc_timeout(send_partial_mpp: bool) {
4333         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
4334         // to avoid our counterparty failing the channel.
4335         let chanmon_cfgs = create_chanmon_cfgs(2);
4336         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4337         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4338         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4339
4340         create_announced_chan_between_nodes(&nodes, 0, 1);
4341
4342         let our_payment_hash = if send_partial_mpp {
4343                 let (route, our_payment_hash, _, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[1], 100000);
4344                 // Use the utility function send_payment_along_path to send the payment with MPP data which
4345                 // indicates there are more HTLCs coming.
4346                 let cur_height = CHAN_CONFIRM_DEPTH + 1; // route_payment calls send_payment, which adds 1 to the current height. So we do the same here to match.
4347                 let payment_id = PaymentId([42; 32]);
4348                 let session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
4349                         RecipientOnionFields::secret_only(payment_secret), payment_id, &route).unwrap();
4350                 nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
4351                         RecipientOnionFields::secret_only(payment_secret), 200_000, cur_height, payment_id,
4352                         &None, session_privs[0]).unwrap();
4353                 check_added_monitors!(nodes[0], 1);
4354                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4355                 assert_eq!(events.len(), 1);
4356                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
4357                 // hop should *not* yet generate any PaymentClaimable event(s).
4358                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false, None);
4359                 our_payment_hash
4360         } else {
4361                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
4362         };
4363
4364         let mut block = create_dummy_block(nodes[0].best_block_hash(), 42, Vec::new());
4365         connect_block(&nodes[0], &block);
4366         connect_block(&nodes[1], &block);
4367         let block_count = TEST_FINAL_CLTV + CHAN_CONFIRM_DEPTH + 2 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS;
4368         for _ in CHAN_CONFIRM_DEPTH + 2..block_count {
4369                 block.header.prev_blockhash = block.block_hash();
4370                 connect_block(&nodes[0], &block);
4371                 connect_block(&nodes[1], &block);
4372         }
4373
4374         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
4375
4376         check_added_monitors!(nodes[1], 1);
4377         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4378         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
4379         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
4380         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
4381         assert!(htlc_timeout_updates.update_fee.is_none());
4382
4383         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
4384         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
4385         // 100_000 msat as u64, followed by the height at which we failed back above
4386         let mut expected_failure_data = (100_000 as u64).to_be_bytes().to_vec();
4387         expected_failure_data.extend_from_slice(&(block_count - 1).to_be_bytes());
4388         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
4389 }
4390
4391 #[test]
4392 fn test_htlc_timeout() {
4393         do_test_htlc_timeout(true);
4394         do_test_htlc_timeout(false);
4395 }
4396
4397 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
4398         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
4399         let chanmon_cfgs = create_chanmon_cfgs(3);
4400         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4401         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4402         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4403         create_announced_chan_between_nodes(&nodes, 0, 1);
4404         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4405
4406         // Make sure all nodes are at the same starting height
4407         connect_blocks(&nodes[0], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[0].best_block_info().1);
4408         connect_blocks(&nodes[1], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[1].best_block_info().1);
4409         connect_blocks(&nodes[2], 2*CHAN_CONFIRM_DEPTH + 1 - nodes[2].best_block_info().1);
4410
4411         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
4412         let (route, first_payment_hash, _, first_payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[2], 100000);
4413         nodes[1].node.send_payment_with_route(&route, first_payment_hash,
4414                 RecipientOnionFields::secret_only(first_payment_secret), PaymentId(first_payment_hash.0)).unwrap();
4415         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
4416         check_added_monitors!(nodes[1], 1);
4417
4418         // Now attempt to route a second payment, which should be placed in the holding cell
4419         let sending_node = if forwarded_htlc { &nodes[0] } else { &nodes[1] };
4420         let (route, second_payment_hash, _, second_payment_secret) = get_route_and_payment_hash!(sending_node, nodes[2], 100000);
4421         sending_node.node.send_payment_with_route(&route, second_payment_hash,
4422                 RecipientOnionFields::secret_only(second_payment_secret), PaymentId(second_payment_hash.0)).unwrap();
4423         if forwarded_htlc {
4424                 check_added_monitors!(nodes[0], 1);
4425                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
4426                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
4427                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4428                 expect_pending_htlcs_forwardable!(nodes[1]);
4429         }
4430         check_added_monitors!(nodes[1], 0);
4431
4432         connect_blocks(&nodes[1], TEST_FINAL_CLTV - LATENCY_GRACE_PERIOD_BLOCKS);
4433         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4434         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
4435         connect_blocks(&nodes[1], 1);
4436
4437         if forwarded_htlc {
4438                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
4439                 check_added_monitors!(nodes[1], 1);
4440                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
4441                 assert_eq!(fail_commit.len(), 1);
4442                 match fail_commit[0] {
4443                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
4444                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
4445                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
4446                         },
4447                         _ => unreachable!(),
4448                 }
4449                 expect_payment_failed_with_update!(nodes[0], second_payment_hash, false, chan_2.0.contents.short_channel_id, false);
4450         } else {
4451                 expect_payment_failed!(nodes[1], second_payment_hash, false);
4452         }
4453 }
4454
4455 #[test]
4456 fn test_holding_cell_htlc_add_timeouts() {
4457         do_test_holding_cell_htlc_add_timeouts(false);
4458         do_test_holding_cell_htlc_add_timeouts(true);
4459 }
4460
4461 macro_rules! check_spendable_outputs {
4462         ($node: expr, $keysinterface: expr) => {
4463                 {
4464                         let mut events = $node.chain_monitor.chain_monitor.get_and_clear_pending_events();
4465                         let mut txn = Vec::new();
4466                         let mut all_outputs = Vec::new();
4467                         let secp_ctx = Secp256k1::new();
4468                         for event in events.drain(..) {
4469                                 match event {
4470                                         Event::SpendableOutputs { mut outputs, channel_id: _ } => {
4471                                                 for outp in outputs.drain(..) {
4472                                                         txn.push($keysinterface.backing.spend_spendable_outputs(&[&outp], Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx).unwrap());
4473                                                         all_outputs.push(outp);
4474                                                 }
4475                                         },
4476                                         _ => panic!("Unexpected event"),
4477                                 };
4478                         }
4479                         if all_outputs.len() > 1 {
4480                                 if let Ok(tx) = $keysinterface.backing.spend_spendable_outputs(&all_outputs.iter().map(|a| a).collect::<Vec<_>>(), Vec::new(), Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(), 253, None, &secp_ctx) {
4481                                         txn.push(tx);
4482                                 }
4483                         }
4484                         txn
4485                 }
4486         }
4487 }
4488
4489 #[test]
4490 fn test_claim_sizeable_push_msat() {
4491         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4492         let chanmon_cfgs = create_chanmon_cfgs(2);
4493         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4494         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4495         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4496
4497         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4498         nodes[1].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[0].node.get_our_node_id()).unwrap();
4499         check_closed_broadcast!(nodes[1], true);
4500         check_added_monitors!(nodes[1], 1);
4501         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
4502         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4503         assert_eq!(node_txn.len(), 1);
4504         check_spends!(node_txn[0], chan.3);
4505         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
4506
4507         mine_transaction(&nodes[1], &node_txn[0]);
4508         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
4509
4510         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4511         assert_eq!(spend_txn.len(), 1);
4512         assert_eq!(spend_txn[0].input.len(), 1);
4513         check_spends!(spend_txn[0], node_txn[0]);
4514         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
4515 }
4516
4517 #[test]
4518 fn test_claim_on_remote_sizeable_push_msat() {
4519         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4520         // to_remote output is encumbered by a P2WPKH
4521         let chanmon_cfgs = create_chanmon_cfgs(2);
4522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4524         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4525
4526         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 98_000_000);
4527         nodes[0].node.force_close_broadcasting_latest_txn(&chan.2, &nodes[1].node.get_our_node_id()).unwrap();
4528         check_closed_broadcast!(nodes[0], true);
4529         check_added_monitors!(nodes[0], 1);
4530         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
4531
4532         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4533         assert_eq!(node_txn.len(), 1);
4534         check_spends!(node_txn[0], chan.3);
4535         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
4536
4537         mine_transaction(&nodes[1], &node_txn[0]);
4538         check_closed_broadcast!(nodes[1], true);
4539         check_added_monitors!(nodes[1], 1);
4540         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4541         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4542
4543         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4544         assert_eq!(spend_txn.len(), 1);
4545         check_spends!(spend_txn[0], node_txn[0]);
4546 }
4547
4548 #[test]
4549 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4550         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4551         // to_remote output is encumbered by a P2WPKH
4552
4553         let chanmon_cfgs = create_chanmon_cfgs(2);
4554         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4555         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4556         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4557
4558         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
4559         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4560         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4561         assert_eq!(revoked_local_txn[0].input.len(), 1);
4562         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4563
4564         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4565         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4566         check_closed_broadcast!(nodes[1], true);
4567         check_added_monitors!(nodes[1], 1);
4568         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4569
4570         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4571         mine_transaction(&nodes[1], &node_txn[0]);
4572         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4573
4574         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4575         assert_eq!(spend_txn.len(), 3);
4576         check_spends!(spend_txn[0], revoked_local_txn[0]); // to_remote output on revoked remote commitment_tx
4577         check_spends!(spend_txn[1], node_txn[0]);
4578         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[0]); // Both outputs
4579 }
4580
4581 #[test]
4582 fn test_static_spendable_outputs_preimage_tx() {
4583         let chanmon_cfgs = create_chanmon_cfgs(2);
4584         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4585         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4586         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4587
4588         // Create some initial channels
4589         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4590
4591         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
4592
4593         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4594         assert_eq!(commitment_tx[0].input.len(), 1);
4595         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4596
4597         // Settle A's commitment tx on B's chain
4598         nodes[1].node.claim_funds(payment_preimage);
4599         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
4600         check_added_monitors!(nodes[1], 1);
4601         mine_transaction(&nodes[1], &commitment_tx[0]);
4602         check_added_monitors!(nodes[1], 1);
4603         let events = nodes[1].node.get_and_clear_pending_msg_events();
4604         match events[0] {
4605                 MessageSendEvent::UpdateHTLCs { .. } => {},
4606                 _ => panic!("Unexpected event"),
4607         }
4608         match events[1] {
4609                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4610                 _ => panic!("Unexepected event"),
4611         }
4612
4613         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4614         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: preimage tx
4615         assert_eq!(node_txn.len(), 1);
4616         check_spends!(node_txn[0], commitment_tx[0]);
4617         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4618
4619         mine_transaction(&nodes[1], &node_txn[0]);
4620         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4621         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4622
4623         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4624         assert_eq!(spend_txn.len(), 1);
4625         check_spends!(spend_txn[0], node_txn[0]);
4626 }
4627
4628 #[test]
4629 fn test_static_spendable_outputs_timeout_tx() {
4630         let chanmon_cfgs = create_chanmon_cfgs(2);
4631         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4632         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4633         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4634
4635         // Create some initial channels
4636         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4637
4638         // Rebalance the network a bit by relaying one payment through all the channels ...
4639         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4640
4641         let (_, our_payment_hash, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4642
4643         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4644         assert_eq!(commitment_tx[0].input.len(), 1);
4645         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4646
4647         // Settle A's commitment tx on B' chain
4648         mine_transaction(&nodes[1], &commitment_tx[0]);
4649         check_added_monitors!(nodes[1], 1);
4650         let events = nodes[1].node.get_and_clear_pending_msg_events();
4651         match events[0] {
4652                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4653                 _ => panic!("Unexpected event"),
4654         }
4655         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4656
4657         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4658         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4659         assert_eq!(node_txn.len(), 1); // ChannelMonitor: timeout tx
4660         check_spends!(node_txn[0],  commitment_tx[0].clone());
4661         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4662
4663         mine_transaction(&nodes[1], &node_txn[0]);
4664         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4665         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4666         expect_payment_failed!(nodes[1], our_payment_hash, false);
4667
4668         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4669         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote, timeout_tx.output
4670         check_spends!(spend_txn[0], commitment_tx[0]);
4671         check_spends!(spend_txn[1], node_txn[0]);
4672         check_spends!(spend_txn[2], node_txn[0], commitment_tx[0]); // All outputs
4673 }
4674
4675 #[test]
4676 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4677         let chanmon_cfgs = create_chanmon_cfgs(2);
4678         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4679         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4680         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4681
4682         // Create some initial channels
4683         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4684
4685         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4686         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4687         assert_eq!(revoked_local_txn[0].input.len(), 1);
4688         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4689
4690         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4691
4692         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4693         check_closed_broadcast!(nodes[1], true);
4694         check_added_monitors!(nodes[1], 1);
4695         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4696
4697         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4698         assert_eq!(node_txn.len(), 1);
4699         assert_eq!(node_txn[0].input.len(), 2);
4700         check_spends!(node_txn[0], revoked_local_txn[0]);
4701
4702         mine_transaction(&nodes[1], &node_txn[0]);
4703         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4704
4705         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4706         assert_eq!(spend_txn.len(), 1);
4707         check_spends!(spend_txn[0], node_txn[0]);
4708 }
4709
4710 #[test]
4711 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4712         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4713         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
4714         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4715         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4716         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4717
4718         // Create some initial channels
4719         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4720
4721         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4722         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4723         assert_eq!(revoked_local_txn[0].input.len(), 1);
4724         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4725
4726         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4727
4728         // A will generate HTLC-Timeout from revoked commitment tx
4729         mine_transaction(&nodes[0], &revoked_local_txn[0]);
4730         check_closed_broadcast!(nodes[0], true);
4731         check_added_monitors!(nodes[0], 1);
4732         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4733         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
4734
4735         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
4736         assert_eq!(revoked_htlc_txn.len(), 1);
4737         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4738         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4739         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4740         assert_ne!(revoked_htlc_txn[0].lock_time, LockTime::ZERO); // HTLC-Timeout
4741
4742         // B will generate justice tx from A's revoked commitment/HTLC tx
4743         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4744         check_closed_broadcast!(nodes[1], true);
4745         check_added_monitors!(nodes[1], 1);
4746         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4747
4748         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4749         assert_eq!(node_txn.len(), 2); // ChannelMonitor: bogus justice tx, justice tx on revoked outputs
4750         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4751         // including the one already spent by revoked_htlc_txn[1]. That's OK, we'll spend with valid
4752         // transactions next...
4753         assert_eq!(node_txn[0].input.len(), 3);
4754         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4755
4756         assert_eq!(node_txn[1].input.len(), 2);
4757         check_spends!(node_txn[1], revoked_local_txn[0], revoked_htlc_txn[0]);
4758         if node_txn[1].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4759                 assert_ne!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4760         } else {
4761                 assert_eq!(node_txn[1].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4762                 assert_ne!(node_txn[1].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4763         }
4764
4765         mine_transaction(&nodes[1], &node_txn[1]);
4766         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
4767
4768         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4769         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
4770         assert_eq!(spend_txn.len(), 1);
4771         assert_eq!(spend_txn[0].input.len(), 1);
4772         check_spends!(spend_txn[0], node_txn[1]);
4773 }
4774
4775 #[test]
4776 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4777         let mut chanmon_cfgs = create_chanmon_cfgs(2);
4778         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
4779         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4780         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4781         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4782
4783         // Create some initial channels
4784         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4785
4786         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4787         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4788         assert_eq!(revoked_local_txn[0].input.len(), 1);
4789         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4790
4791         // The to-be-revoked commitment tx should have one HTLC and one to_remote output
4792         assert_eq!(revoked_local_txn[0].output.len(), 2);
4793
4794         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
4795
4796         // B will generate HTLC-Success from revoked commitment tx
4797         mine_transaction(&nodes[1], &revoked_local_txn[0]);
4798         check_closed_broadcast!(nodes[1], true);
4799         check_added_monitors!(nodes[1], 1);
4800         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4801         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4802
4803         assert_eq!(revoked_htlc_txn.len(), 1);
4804         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4805         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4806         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4807
4808         // Check that the unspent (of two) outputs on revoked_local_txn[0] is a P2WPKH:
4809         let unspent_local_txn_output = revoked_htlc_txn[0].input[0].previous_output.vout as usize ^ 1;
4810         assert_eq!(revoked_local_txn[0].output[unspent_local_txn_output].script_pubkey.len(), 2 + 20); // P2WPKH
4811
4812         // A will generate justice tx from B's revoked commitment/HTLC tx
4813         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()]));
4814         check_closed_broadcast!(nodes[0], true);
4815         check_added_monitors!(nodes[0], 1);
4816         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4817
4818         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4819         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success
4820
4821         // The first transaction generated is bogus - it spends both outputs of revoked_local_txn[0]
4822         // including the one already spent by revoked_htlc_txn[0]. That's OK, we'll spend with valid
4823         // transactions next...
4824         assert_eq!(node_txn[0].input.len(), 2);
4825         check_spends!(node_txn[0], revoked_local_txn[0], revoked_htlc_txn[0]);
4826         if node_txn[0].input[1].previous_output.txid == revoked_htlc_txn[0].txid() {
4827                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4828         } else {
4829                 assert_eq!(node_txn[0].input[0].previous_output.txid, revoked_htlc_txn[0].txid());
4830                 assert_eq!(node_txn[0].input[1].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4831         }
4832
4833         assert_eq!(node_txn[1].input.len(), 1);
4834         check_spends!(node_txn[1], revoked_htlc_txn[0]);
4835
4836         mine_transaction(&nodes[0], &node_txn[1]);
4837         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
4838
4839         // Note that nodes[0]'s tx_broadcaster is still locked, so if we get here the channelmonitor
4840         // didn't try to generate any new transactions.
4841
4842         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4843         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
4844         assert_eq!(spend_txn.len(), 3);
4845         assert_eq!(spend_txn[0].input.len(), 1);
4846         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4847         assert_ne!(spend_txn[0].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
4848         check_spends!(spend_txn[1], node_txn[1]); // spending justice tx output on the htlc success tx
4849         check_spends!(spend_txn[2], revoked_local_txn[0], node_txn[1]); // Both outputs
4850 }
4851
4852 #[test]
4853 fn test_onchain_to_onchain_claim() {
4854         // Test that in case of channel closure, we detect the state of output and claim HTLC
4855         // on downstream peer's remote commitment tx.
4856         // First, have C claim an HTLC against its own latest commitment transaction.
4857         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4858         // channel.
4859         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4860         // gets broadcast.
4861
4862         let chanmon_cfgs = create_chanmon_cfgs(3);
4863         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4864         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4865         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4866
4867         // Create some initial channels
4868         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4869         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4870
4871         // Ensure all nodes are at the same height
4872         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4873         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4874         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4875         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4876
4877         // Rebalance the network a bit by relaying one payment through all the channels ...
4878         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4879         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
4880
4881         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
4882         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4883         check_spends!(commitment_tx[0], chan_2.3);
4884         nodes[2].node.claim_funds(payment_preimage);
4885         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
4886         check_added_monitors!(nodes[2], 1);
4887         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4888         assert!(updates.update_add_htlcs.is_empty());
4889         assert!(updates.update_fail_htlcs.is_empty());
4890         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4891         assert!(updates.update_fail_malformed_htlcs.is_empty());
4892
4893         mine_transaction(&nodes[2], &commitment_tx[0]);
4894         check_closed_broadcast!(nodes[2], true);
4895         check_added_monitors!(nodes[2], 1);
4896         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
4897
4898         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelMonitor: 1 (HTLC-Success tx)
4899         assert_eq!(c_txn.len(), 1);
4900         check_spends!(c_txn[0], commitment_tx[0]);
4901         assert_eq!(c_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4902         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4903         assert_eq!(c_txn[0].lock_time, LockTime::ZERO); // Success tx
4904
4905         // 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
4906         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![commitment_tx[0].clone(), c_txn[0].clone()]));
4907         check_added_monitors!(nodes[1], 1);
4908         let events = nodes[1].node.get_and_clear_pending_events();
4909         assert_eq!(events.len(), 2);
4910         match events[0] {
4911                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
4912                 _ => panic!("Unexpected event"),
4913         }
4914         match events[1] {
4915                 Event::PaymentForwarded { fee_earned_msat, prev_channel_id, claim_from_onchain_tx, next_channel_id, outbound_amount_forwarded_msat } => {
4916                         assert_eq!(fee_earned_msat, Some(1000));
4917                         assert_eq!(prev_channel_id, Some(chan_1.2));
4918                         assert_eq!(claim_from_onchain_tx, true);
4919                         assert_eq!(next_channel_id, Some(chan_2.2));
4920                         assert_eq!(outbound_amount_forwarded_msat, Some(3000000));
4921                 },
4922                 _ => panic!("Unexpected event"),
4923         }
4924         check_added_monitors!(nodes[1], 1);
4925         let mut msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4926         assert_eq!(msg_events.len(), 3);
4927         let nodes_2_event = remove_first_msg_event_to_node(&nodes[2].node.get_our_node_id(), &mut msg_events);
4928         let nodes_0_event = remove_first_msg_event_to_node(&nodes[0].node.get_our_node_id(), &mut msg_events);
4929
4930         match nodes_2_event {
4931                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { .. }, node_id: _ } => {},
4932                 _ => panic!("Unexpected event"),
4933         }
4934
4935         match nodes_0_event {
4936                 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, .. } } => {
4937                         assert!(update_add_htlcs.is_empty());
4938                         assert!(update_fail_htlcs.is_empty());
4939                         assert_eq!(update_fulfill_htlcs.len(), 1);
4940                         assert!(update_fail_malformed_htlcs.is_empty());
4941                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4942                 },
4943                 _ => panic!("Unexpected event"),
4944         };
4945
4946         // Ensure that the last remaining message event is the BroadcastChannelUpdate msg for chan_2
4947         match msg_events[0] {
4948                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4949                 _ => panic!("Unexpected event"),
4950         }
4951
4952         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4953         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4954         mine_transaction(&nodes[1], &commitment_tx[0]);
4955         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
4956         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4957         // ChannelMonitor: HTLC-Success tx
4958         assert_eq!(b_txn.len(), 1);
4959         check_spends!(b_txn[0], commitment_tx[0]);
4960         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4961         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4962         assert_eq!(b_txn[0].lock_time.to_consensus_u32(), nodes[1].best_block_info().1); // Success tx
4963
4964         check_closed_broadcast!(nodes[1], true);
4965         check_added_monitors!(nodes[1], 1);
4966 }
4967
4968 #[test]
4969 fn test_duplicate_payment_hash_one_failure_one_success() {
4970         // Topology : A --> B --> C --> D
4971         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4972         // Note that because C will refuse to generate two payment secrets for the same payment hash,
4973         // we forward one of the payments onwards to D.
4974         let chanmon_cfgs = create_chanmon_cfgs(4);
4975         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4976         // When this test was written, the default base fee floated based on the HTLC count.
4977         // It is now fixed, so we simply set the fee to the expected value here.
4978         let mut config = test_default_channel_config();
4979         config.channel_config.forwarding_fee_base_msat = 196;
4980         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs,
4981                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
4982         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4983
4984         create_announced_chan_between_nodes(&nodes, 0, 1);
4985         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
4986         create_announced_chan_between_nodes(&nodes, 2, 3);
4987
4988         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
4989         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
4990         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
4991         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
4992         connect_blocks(&nodes[3], node_max_height - nodes[3].best_block_info().1);
4993
4994         let (our_payment_preimage, duplicate_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 900_000);
4995
4996         let payment_secret = nodes[3].node.create_inbound_payment_for_hash(duplicate_payment_hash, None, 7200, None).unwrap();
4997         // We reduce the final CLTV here by a somewhat arbitrary constant to keep it under the one-byte
4998         // script push size limit so that the below script length checks match
4999         // ACCEPTED_HTLC_SCRIPT_WEIGHT.
5000         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV - 40)
5001                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
5002         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[3], payment_params, 800_000);
5003         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2], &nodes[3]]], 800_000, duplicate_payment_hash, payment_secret);
5004
5005         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
5006         assert_eq!(commitment_txn[0].input.len(), 1);
5007         check_spends!(commitment_txn[0], chan_2.3);
5008
5009         mine_transaction(&nodes[1], &commitment_txn[0]);
5010         check_closed_broadcast!(nodes[1], true);
5011         check_added_monitors!(nodes[1], 1);
5012         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[2].node.get_our_node_id()], 100000);
5013         connect_blocks(&nodes[1], TEST_FINAL_CLTV - 40 + MIN_CLTV_EXPIRY_DELTA as u32); // Confirm blocks until the HTLC expires
5014
5015         let htlc_timeout_tx;
5016         { // Extract one of the two HTLC-Timeout transaction
5017                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5018                 // ChannelMonitor: timeout tx * 2-or-3
5019                 assert!(node_txn.len() == 2 || node_txn.len() == 3);
5020
5021                 check_spends!(node_txn[0], commitment_txn[0]);
5022                 assert_eq!(node_txn[0].input.len(), 1);
5023                 assert_eq!(node_txn[0].output.len(), 1);
5024
5025                 if node_txn.len() > 2 {
5026                         check_spends!(node_txn[1], commitment_txn[0]);
5027                         assert_eq!(node_txn[1].input.len(), 1);
5028                         assert_eq!(node_txn[1].output.len(), 1);
5029                         assert_eq!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5030
5031                         check_spends!(node_txn[2], commitment_txn[0]);
5032                         assert_eq!(node_txn[2].input.len(), 1);
5033                         assert_eq!(node_txn[2].output.len(), 1);
5034                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
5035                 } else {
5036                         check_spends!(node_txn[1], commitment_txn[0]);
5037                         assert_eq!(node_txn[1].input.len(), 1);
5038                         assert_eq!(node_txn[1].output.len(), 1);
5039                         assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
5040                 }
5041
5042                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5043                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5044                 // Assign htlc_timeout_tx to the forwarded HTLC (with value ~800 sats). The received HTLC
5045                 // (with value 900 sats) will be claimed in the below `claim_funds` call.
5046                 if node_txn.len() > 2 {
5047                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5048                         htlc_timeout_tx = if node_txn[2].output[0].value < 900 { node_txn[2].clone() } else { node_txn[0].clone() };
5049                 } else {
5050                         htlc_timeout_tx = if node_txn[0].output[0].value < 900 { node_txn[1].clone() } else { node_txn[0].clone() };
5051                 }
5052         }
5053
5054         nodes[2].node.claim_funds(our_payment_preimage);
5055         expect_payment_claimed!(nodes[2], duplicate_payment_hash, 900_000);
5056
5057         mine_transaction(&nodes[2], &commitment_txn[0]);
5058         check_added_monitors!(nodes[2], 2);
5059         check_closed_event!(nodes[2], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5060         let events = nodes[2].node.get_and_clear_pending_msg_events();
5061         match events[0] {
5062                 MessageSendEvent::UpdateHTLCs { .. } => {},
5063                 _ => panic!("Unexpected event"),
5064         }
5065         match events[1] {
5066                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5067                 _ => panic!("Unexepected event"),
5068         }
5069         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
5070         assert_eq!(htlc_success_txn.len(), 2); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs)
5071         check_spends!(htlc_success_txn[0], commitment_txn[0]);
5072         check_spends!(htlc_success_txn[1], commitment_txn[0]);
5073         assert_eq!(htlc_success_txn[0].input.len(), 1);
5074         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5075         assert_eq!(htlc_success_txn[1].input.len(), 1);
5076         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5077         assert_ne!(htlc_success_txn[0].input[0].previous_output, htlc_success_txn[1].input[0].previous_output);
5078         assert_ne!(htlc_success_txn[1].input[0].previous_output, htlc_timeout_tx.input[0].previous_output);
5079
5080         mine_transaction(&nodes[1], &htlc_timeout_tx);
5081         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5082         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
5083         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5084         assert!(htlc_updates.update_add_htlcs.is_empty());
5085         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
5086         let first_htlc_id = htlc_updates.update_fail_htlcs[0].htlc_id;
5087         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
5088         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
5089         check_added_monitors!(nodes[1], 1);
5090
5091         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
5092         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5093         {
5094                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
5095         }
5096         expect_payment_failed_with_update!(nodes[0], duplicate_payment_hash, false, chan_2.0.contents.short_channel_id, true);
5097
5098         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
5099         mine_transaction(&nodes[1], &htlc_success_txn[1]);
5100         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], Some(196), true, true);
5101         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5102         assert!(updates.update_add_htlcs.is_empty());
5103         assert!(updates.update_fail_htlcs.is_empty());
5104         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
5105         assert_ne!(updates.update_fulfill_htlcs[0].htlc_id, first_htlc_id);
5106         assert!(updates.update_fail_malformed_htlcs.is_empty());
5107         check_added_monitors!(nodes[1], 1);
5108
5109         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
5110         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
5111         expect_payment_sent(&nodes[0], our_payment_preimage, None, true, true);
5112 }
5113
5114 #[test]
5115 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
5116         let chanmon_cfgs = create_chanmon_cfgs(2);
5117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5119         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5120
5121         // Create some initial channels
5122         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5123
5124         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
5125         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
5126         assert_eq!(local_txn.len(), 1);
5127         assert_eq!(local_txn[0].input.len(), 1);
5128         check_spends!(local_txn[0], chan_1.3);
5129
5130         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
5131         nodes[1].node.claim_funds(payment_preimage);
5132         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
5133         check_added_monitors!(nodes[1], 1);
5134
5135         mine_transaction(&nodes[1], &local_txn[0]);
5136         check_added_monitors!(nodes[1], 1);
5137         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
5138         let events = nodes[1].node.get_and_clear_pending_msg_events();
5139         match events[0] {
5140                 MessageSendEvent::UpdateHTLCs { .. } => {},
5141                 _ => panic!("Unexpected event"),
5142         }
5143         match events[1] {
5144                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5145                 _ => panic!("Unexepected event"),
5146         }
5147         let node_tx = {
5148                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
5149                 assert_eq!(node_txn.len(), 1);
5150                 assert_eq!(node_txn[0].input.len(), 1);
5151                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5152                 check_spends!(node_txn[0], local_txn[0]);
5153                 node_txn[0].clone()
5154         };
5155
5156         mine_transaction(&nodes[1], &node_tx);
5157         connect_blocks(&nodes[1], BREAKDOWN_TIMEOUT as u32 - 1);
5158
5159         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
5160         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5161         assert_eq!(spend_txn.len(), 1);
5162         assert_eq!(spend_txn[0].input.len(), 1);
5163         check_spends!(spend_txn[0], node_tx);
5164         assert_eq!(spend_txn[0].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5165 }
5166
5167 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
5168         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
5169         // unrevoked commitment transaction.
5170         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
5171         // a remote RAA before they could be failed backwards (and combinations thereof).
5172         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
5173         // use the same payment hashes.
5174         // Thus, we use a six-node network:
5175         //
5176         // A \         / E
5177         //    - C - D -
5178         // B /         \ F
5179         // And test where C fails back to A/B when D announces its latest commitment transaction
5180         let chanmon_cfgs = create_chanmon_cfgs(6);
5181         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
5182         // When this test was written, the default base fee floated based on the HTLC count.
5183         // It is now fixed, so we simply set the fee to the expected value here.
5184         let mut config = test_default_channel_config();
5185         config.channel_config.forwarding_fee_base_msat = 196;
5186         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs,
5187                 &[Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone()), Some(config.clone())]);
5188         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5189
5190         let _chan_0_2 = create_announced_chan_between_nodes(&nodes, 0, 2);
5191         let _chan_1_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
5192         let chan_2_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
5193         let chan_3_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
5194         let chan_3_5  = create_announced_chan_between_nodes(&nodes, 3, 5);
5195
5196         // Rebalance and check output sanity...
5197         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
5198         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
5199         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 2);
5200
5201         let ds_dust_limit = nodes[3].node.per_peer_state.read().unwrap().get(&nodes[2].node.get_our_node_id())
5202                 .unwrap().lock().unwrap().channel_by_id.get(&chan_2_3.2).unwrap().context().holder_dust_limit_satoshis;
5203         // 0th HTLC:
5204         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
5205         // 1st HTLC:
5206         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
5207         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5208         // 2nd HTLC:
5209         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_1, nodes[5].node.create_inbound_payment_for_hash(payment_hash_1, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5210         // 3rd HTLC:
5211         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_2, nodes[5].node.create_inbound_payment_for_hash(payment_hash_2, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5212         // 4th HTLC:
5213         let (_, payment_hash_3, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5214         // 5th HTLC:
5215         let (_, payment_hash_4, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5216         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5217         // 6th HTLC:
5218         send_along_route_with_secret(&nodes[1], route.clone(), &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_3, nodes[5].node.create_inbound_payment_for_hash(payment_hash_3, None, 7200, None).unwrap());
5219         // 7th HTLC:
5220         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_4, nodes[5].node.create_inbound_payment_for_hash(payment_hash_4, None, 7200, None).unwrap());
5221
5222         // 8th HTLC:
5223         let (_, payment_hash_5, ..) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5224         // 9th HTLC:
5225         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], ds_dust_limit*1000);
5226         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], ds_dust_limit*1000, payment_hash_5, nodes[5].node.create_inbound_payment_for_hash(payment_hash_5, None, 7200, None).unwrap()); // not added < dust limit + HTLC tx fee
5227
5228         // 10th HTLC:
5229         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
5230         // 11th HTLC:
5231         let (route, _, _, _) = get_route_and_payment_hash!(nodes[1], nodes[5], 1000000);
5232         send_along_route_with_secret(&nodes[1], route, &[&[&nodes[2], &nodes[3], &nodes[5]]], 1000000, payment_hash_6, nodes[5].node.create_inbound_payment_for_hash(payment_hash_6, None, 7200, None).unwrap());
5233
5234         // Double-check that six of the new HTLC were added
5235         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5236         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5237         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2).len(), 1);
5238         assert_eq!(get_local_commitment_txn!(nodes[3], chan_2_3.2)[0].output.len(), 8);
5239
5240         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5241         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5242         nodes[4].node.fail_htlc_backwards(&payment_hash_1);
5243         nodes[4].node.fail_htlc_backwards(&payment_hash_3);
5244         nodes[4].node.fail_htlc_backwards(&payment_hash_5);
5245         nodes[4].node.fail_htlc_backwards(&payment_hash_6);
5246         check_added_monitors!(nodes[4], 0);
5247
5248         let failed_destinations = vec![
5249                 HTLCDestination::FailedPayment { payment_hash: payment_hash_1 },
5250                 HTLCDestination::FailedPayment { payment_hash: payment_hash_3 },
5251                 HTLCDestination::FailedPayment { payment_hash: payment_hash_5 },
5252                 HTLCDestination::FailedPayment { payment_hash: payment_hash_6 },
5253         ];
5254         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[4], failed_destinations);
5255         check_added_monitors!(nodes[4], 1);
5256
5257         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5258         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5259         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5260         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5261         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5262         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5263
5264         // Fail 3rd below-dust and 7th above-dust HTLCs
5265         nodes[5].node.fail_htlc_backwards(&payment_hash_2);
5266         nodes[5].node.fail_htlc_backwards(&payment_hash_4);
5267         check_added_monitors!(nodes[5], 0);
5268
5269         let failed_destinations_2 = vec![
5270                 HTLCDestination::FailedPayment { payment_hash: payment_hash_2 },
5271                 HTLCDestination::FailedPayment { payment_hash: payment_hash_4 },
5272         ];
5273         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[5], failed_destinations_2);
5274         check_added_monitors!(nodes[5], 1);
5275
5276         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5277         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5278         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5279         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5280
5281         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5282
5283         // After 4 and 2 removes respectively above in nodes[4] and nodes[5], nodes[3] should receive 6 PaymentForwardedFailed events
5284         let failed_destinations_3 = vec![
5285                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5286                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5287                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5288                 HTLCDestination::NextHopChannel { node_id: Some(nodes[4].node.get_our_node_id()), channel_id: chan_3_4.2 },
5289                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5290                 HTLCDestination::NextHopChannel { node_id: Some(nodes[5].node.get_our_node_id()), channel_id: chan_3_5.2 },
5291         ];
5292         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations_3);
5293         check_added_monitors!(nodes[3], 1);
5294         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5295         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5296         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5297         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5298         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5299         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5300         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5301         if deliver_last_raa {
5302                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5303         } else {
5304                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5305         }
5306
5307         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5308         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5309         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5310         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5311         //
5312         // We now broadcast the latest commitment transaction, which *should* result in failures for
5313         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5314         // the non-broadcast above-dust HTLCs.
5315         //
5316         // Alternatively, we may broadcast the previous commitment transaction, which should only
5317         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5318         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan_2_3.2);
5319
5320         if announce_latest {
5321                 mine_transaction(&nodes[2], &ds_last_commitment_tx[0]);
5322         } else {
5323                 mine_transaction(&nodes[2], &ds_prev_commitment_tx[0]);
5324         }
5325         let events = nodes[2].node.get_and_clear_pending_events();
5326         let close_event = if deliver_last_raa {
5327                 assert_eq!(events.len(), 2 + 6);
5328                 events.last().clone().unwrap()
5329         } else {
5330                 assert_eq!(events.len(), 1);
5331                 events.last().clone().unwrap()
5332         };
5333         match close_event {
5334                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
5335                 _ => panic!("Unexpected event"),
5336         }
5337
5338         connect_blocks(&nodes[2], ANTI_REORG_DELAY - 1);
5339         check_closed_broadcast!(nodes[2], true);
5340         if deliver_last_raa {
5341                 expect_pending_htlcs_forwardable_from_events!(nodes[2], events[0..1], true);
5342
5343                 let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(3).collect();
5344                 expect_htlc_handling_failed_destinations!(nodes[2].node.get_and_clear_pending_events(), expected_destinations);
5345         } else {
5346                 let expected_destinations: Vec<HTLCDestination> = if announce_latest {
5347                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(9).collect()
5348                 } else {
5349                         repeat(HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }).take(6).collect()
5350                 };
5351
5352                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], expected_destinations);
5353         }
5354         check_added_monitors!(nodes[2], 3);
5355
5356         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5357         assert_eq!(cs_msgs.len(), 2);
5358         let mut a_done = false;
5359         for msg in cs_msgs {
5360                 match msg {
5361                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5362                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5363                                 // should be failed-backwards here.
5364                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5365                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5366                                         for htlc in &updates.update_fail_htlcs {
5367                                                 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 });
5368                                         }
5369                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5370                                         assert!(!a_done);
5371                                         a_done = true;
5372                                         &nodes[0]
5373                                 } else {
5374                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5375                                         for htlc in &updates.update_fail_htlcs {
5376                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5377                                         }
5378                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5379                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5380                                         &nodes[1]
5381                                 };
5382                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5383                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5384                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5385                                 if announce_latest {
5386                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5387                                         if *node_id == nodes[0].node.get_our_node_id() {
5388                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5389                                         }
5390                                 }
5391                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5392                         },
5393                         _ => panic!("Unexpected event"),
5394                 }
5395         }
5396
5397         let as_events = nodes[0].node.get_and_clear_pending_events();
5398         assert_eq!(as_events.len(), if announce_latest { 10 } else { 6 });
5399         let mut as_failds = HashSet::new();
5400         let mut as_updates = 0;
5401         for event in as_events.iter() {
5402                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5403                         assert!(as_failds.insert(*payment_hash));
5404                         if *payment_hash != payment_hash_2 {
5405                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5406                         } else {
5407                                 assert!(!payment_failed_permanently);
5408                         }
5409                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5410                                 as_updates += 1;
5411                         }
5412                 } else if let &Event::PaymentFailed { .. } = event {
5413                 } else { panic!("Unexpected event"); }
5414         }
5415         assert!(as_failds.contains(&payment_hash_1));
5416         assert!(as_failds.contains(&payment_hash_2));
5417         if announce_latest {
5418                 assert!(as_failds.contains(&payment_hash_3));
5419                 assert!(as_failds.contains(&payment_hash_5));
5420         }
5421         assert!(as_failds.contains(&payment_hash_6));
5422
5423         let bs_events = nodes[1].node.get_and_clear_pending_events();
5424         assert_eq!(bs_events.len(), if announce_latest { 8 } else { 6 });
5425         let mut bs_failds = HashSet::new();
5426         let mut bs_updates = 0;
5427         for event in bs_events.iter() {
5428                 if let &Event::PaymentPathFailed { ref payment_hash, ref payment_failed_permanently, ref failure, .. } = event {
5429                         assert!(bs_failds.insert(*payment_hash));
5430                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5431                                 assert_eq!(*payment_failed_permanently, deliver_last_raa);
5432                         } else {
5433                                 assert!(!payment_failed_permanently);
5434                         }
5435                         if let PathFailure::OnPath { network_update: Some(_) } = failure {
5436                                 bs_updates += 1;
5437                         }
5438                 } else if let &Event::PaymentFailed { .. } = event {
5439                 } else { panic!("Unexpected event"); }
5440         }
5441         assert!(bs_failds.contains(&payment_hash_1));
5442         assert!(bs_failds.contains(&payment_hash_2));
5443         if announce_latest {
5444                 assert!(bs_failds.contains(&payment_hash_4));
5445         }
5446         assert!(bs_failds.contains(&payment_hash_5));
5447
5448         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5449         // get a NetworkUpdate. A should have gotten 4 HTLCs which were failed-back due to
5450         // unknown-preimage-etc, B should have gotten 2. Thus, in the
5451         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2 NetworkUpdates.
5452         assert_eq!(as_updates, if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5453         assert_eq!(bs_updates, if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5454 }
5455
5456 #[test]
5457 fn test_fail_backwards_latest_remote_announce_a() {
5458         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5459 }
5460
5461 #[test]
5462 fn test_fail_backwards_latest_remote_announce_b() {
5463         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5464 }
5465
5466 #[test]
5467 fn test_fail_backwards_previous_remote_announce() {
5468         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5469         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5470         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5471 }
5472
5473 #[test]
5474 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5475         let chanmon_cfgs = create_chanmon_cfgs(2);
5476         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5477         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5478         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5479
5480         // Create some initial channels
5481         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5482
5483         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5484         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5485         assert_eq!(local_txn[0].input.len(), 1);
5486         check_spends!(local_txn[0], chan_1.3);
5487
5488         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5489         mine_transaction(&nodes[0], &local_txn[0]);
5490         check_closed_broadcast!(nodes[0], true);
5491         check_added_monitors!(nodes[0], 1);
5492         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5493         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5494
5495         let htlc_timeout = {
5496                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5497                 assert_eq!(node_txn.len(), 1);
5498                 assert_eq!(node_txn[0].input.len(), 1);
5499                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5500                 check_spends!(node_txn[0], local_txn[0]);
5501                 node_txn[0].clone()
5502         };
5503
5504         mine_transaction(&nodes[0], &htlc_timeout);
5505         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5506         expect_payment_failed!(nodes[0], our_payment_hash, false);
5507
5508         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5509         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5510         assert_eq!(spend_txn.len(), 3);
5511         check_spends!(spend_txn[0], local_txn[0]);
5512         assert_eq!(spend_txn[1].input.len(), 1);
5513         check_spends!(spend_txn[1], htlc_timeout);
5514         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5515         assert_eq!(spend_txn[2].input.len(), 2);
5516         check_spends!(spend_txn[2], local_txn[0], htlc_timeout);
5517         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5518                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5519 }
5520
5521 #[test]
5522 fn test_key_derivation_params() {
5523         // This test is a copy of test_dynamic_spendable_outputs_local_htlc_timeout_tx, with a key
5524         // manager rotation to test that `channel_keys_id` returned in
5525         // [`SpendableOutputDescriptor::DelayedPaymentOutput`] let us re-derive the channel key set to
5526         // then derive a `delayed_payment_key`.
5527
5528         let chanmon_cfgs = create_chanmon_cfgs(3);
5529
5530         // We manually create the node configuration to backup the seed.
5531         let seed = [42; 32];
5532         let keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5533         let chain_monitor = test_utils::TestChainMonitor::new(Some(&chanmon_cfgs[0].chain_source), &chanmon_cfgs[0].tx_broadcaster, &chanmon_cfgs[0].logger, &chanmon_cfgs[0].fee_estimator, &chanmon_cfgs[0].persister, &keys_manager);
5534         let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &chanmon_cfgs[0].logger));
5535         let scorer = RwLock::new(test_utils::TestScorer::new());
5536         let router = test_utils::TestRouter::new(network_graph.clone(), &scorer);
5537         let node = NodeCfg { chain_source: &chanmon_cfgs[0].chain_source, logger: &chanmon_cfgs[0].logger, tx_broadcaster: &chanmon_cfgs[0].tx_broadcaster, fee_estimator: &chanmon_cfgs[0].fee_estimator, router, chain_monitor, keys_manager: &keys_manager, network_graph, node_seed: seed, override_init_features: alloc::rc::Rc::new(core::cell::RefCell::new(None)) };
5538         let mut node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5539         node_cfgs.remove(0);
5540         node_cfgs.insert(0, node);
5541
5542         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5543         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5544
5545         // Create some initial channels
5546         // Create a dummy channel to advance index by one and thus test re-derivation correctness
5547         // for node 0
5548         let chan_0 = create_announced_chan_between_nodes(&nodes, 0, 2);
5549         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
5550         assert_ne!(chan_0.3.output[0].script_pubkey, chan_1.3.output[0].script_pubkey);
5551
5552         // Ensure all nodes are at the same height
5553         let node_max_height = nodes.iter().map(|node| node.blocks.lock().unwrap().len()).max().unwrap() as u32;
5554         connect_blocks(&nodes[0], node_max_height - nodes[0].best_block_info().1);
5555         connect_blocks(&nodes[1], node_max_height - nodes[1].best_block_info().1);
5556         connect_blocks(&nodes[2], node_max_height - nodes[2].best_block_info().1);
5557
5558         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5559         let local_txn_0 = get_local_commitment_txn!(nodes[0], chan_0.2);
5560         let local_txn_1 = get_local_commitment_txn!(nodes[0], chan_1.2);
5561         assert_eq!(local_txn_1[0].input.len(), 1);
5562         check_spends!(local_txn_1[0], chan_1.3);
5563
5564         // We check funding pubkey are unique
5565         let (from_0_funding_key_0, from_0_funding_key_1) = (PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_0[0].input[0].witness.to_vec()[3][36..69]));
5566         let (from_1_funding_key_0, from_1_funding_key_1) = (PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][2..35]), PublicKey::from_slice(&local_txn_1[0].input[0].witness.to_vec()[3][36..69]));
5567         if from_0_funding_key_0 == from_1_funding_key_0
5568             || from_0_funding_key_0 == from_1_funding_key_1
5569             || from_0_funding_key_1 == from_1_funding_key_0
5570             || from_0_funding_key_1 == from_1_funding_key_1 {
5571                 panic!("Funding pubkeys aren't unique");
5572         }
5573
5574         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5575         mine_transaction(&nodes[0], &local_txn_1[0]);
5576         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
5577         check_closed_broadcast!(nodes[0], true);
5578         check_added_monitors!(nodes[0], 1);
5579         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
5580
5581         let htlc_timeout = {
5582                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5583                 assert_eq!(node_txn.len(), 1);
5584                 assert_eq!(node_txn[0].input.len(), 1);
5585                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5586                 check_spends!(node_txn[0], local_txn_1[0]);
5587                 node_txn[0].clone()
5588         };
5589
5590         mine_transaction(&nodes[0], &htlc_timeout);
5591         connect_blocks(&nodes[0], BREAKDOWN_TIMEOUT as u32 - 1);
5592         expect_payment_failed!(nodes[0], our_payment_hash, false);
5593
5594         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5595         let new_keys_manager = test_utils::TestKeysInterface::new(&seed, Network::Testnet);
5596         let spend_txn = check_spendable_outputs!(nodes[0], new_keys_manager);
5597         assert_eq!(spend_txn.len(), 3);
5598         check_spends!(spend_txn[0], local_txn_1[0]);
5599         assert_eq!(spend_txn[1].input.len(), 1);
5600         check_spends!(spend_txn[1], htlc_timeout);
5601         assert_eq!(spend_txn[1].input[0].sequence.0, BREAKDOWN_TIMEOUT as u32);
5602         assert_eq!(spend_txn[2].input.len(), 2);
5603         check_spends!(spend_txn[2], local_txn_1[0], htlc_timeout);
5604         assert!(spend_txn[2].input[0].sequence.0 == BREAKDOWN_TIMEOUT as u32 ||
5605                 spend_txn[2].input[1].sequence.0 == BREAKDOWN_TIMEOUT as u32);
5606 }
5607
5608 #[test]
5609 fn test_static_output_closing_tx() {
5610         let chanmon_cfgs = create_chanmon_cfgs(2);
5611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5613         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5614
5615         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5616
5617         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5618         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5619
5620         mine_transaction(&nodes[0], &closing_tx);
5621         check_closed_event!(nodes[0], 1, ClosureReason::CooperativeClosure, [nodes[1].node.get_our_node_id()], 100000);
5622         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
5623
5624         let spend_txn = check_spendable_outputs!(nodes[0], node_cfgs[0].keys_manager);
5625         assert_eq!(spend_txn.len(), 1);
5626         check_spends!(spend_txn[0], closing_tx);
5627
5628         mine_transaction(&nodes[1], &closing_tx);
5629         check_closed_event!(nodes[1], 1, ClosureReason::CooperativeClosure, [nodes[0].node.get_our_node_id()], 100000);
5630         connect_blocks(&nodes[1], ANTI_REORG_DELAY - 1);
5631
5632         let spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
5633         assert_eq!(spend_txn.len(), 1);
5634         check_spends!(spend_txn[0], closing_tx);
5635 }
5636
5637 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5638         let chanmon_cfgs = create_chanmon_cfgs(2);
5639         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5640         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5641         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5642         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5643
5644         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3_000_000 });
5645
5646         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5647         // present in B's local commitment transaction, but none of A's commitment transactions.
5648         nodes[1].node.claim_funds(payment_preimage);
5649         check_added_monitors!(nodes[1], 1);
5650         expect_payment_claimed!(nodes[1], payment_hash, if use_dust { 50000 } else { 3_000_000 });
5651
5652         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5653         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5654         expect_payment_sent(&nodes[0], payment_preimage, None, false, false);
5655
5656         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5657         check_added_monitors!(nodes[0], 1);
5658         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5659         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5660         check_added_monitors!(nodes[1], 1);
5661
5662         let starting_block = nodes[1].best_block_info();
5663         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5664         for _ in starting_block.1 + 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + starting_block.1 + 2 {
5665                 connect_block(&nodes[1], &block);
5666                 block.header.prev_blockhash = block.block_hash();
5667         }
5668         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5669         check_closed_broadcast!(nodes[1], true);
5670         check_added_monitors!(nodes[1], 1);
5671         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[0].node.get_our_node_id()], 100000);
5672 }
5673
5674 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5675         let chanmon_cfgs = create_chanmon_cfgs(2);
5676         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5677         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5678         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5679         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5680
5681         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], if use_dust { 50000 } else { 3000000 });
5682         nodes[0].node.send_payment_with_route(&route, payment_hash,
5683                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
5684         check_added_monitors!(nodes[0], 1);
5685
5686         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5687
5688         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5689         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5690         // to "time out" the HTLC.
5691
5692         let starting_block = nodes[1].best_block_info();
5693         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5694
5695         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + starting_block.1 + 2 {
5696                 connect_block(&nodes[0], &block);
5697                 block.header.prev_blockhash = block.block_hash();
5698         }
5699         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5700         check_closed_broadcast!(nodes[0], true);
5701         check_added_monitors!(nodes[0], 1);
5702         check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5703 }
5704
5705 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5706         let chanmon_cfgs = create_chanmon_cfgs(3);
5707         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5708         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5709         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5710         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5711
5712         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5713         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5714         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5715         // actually revoked.
5716         let htlc_value = if use_dust { 50000 } else { 3000000 };
5717         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5718         nodes[1].node.fail_htlc_backwards(&our_payment_hash);
5719         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
5720         check_added_monitors!(nodes[1], 1);
5721
5722         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5723         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5724         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5725         check_added_monitors!(nodes[0], 1);
5726         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5727         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5728         check_added_monitors!(nodes[1], 1);
5729         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5730         check_added_monitors!(nodes[1], 1);
5731         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5732
5733         if check_revoke_no_close {
5734                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5735                 check_added_monitors!(nodes[0], 1);
5736         }
5737
5738         let starting_block = nodes[1].best_block_info();
5739         let mut block = create_dummy_block(starting_block.0, 42, Vec::new());
5740         for _ in starting_block.1 + 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 2 {
5741                 connect_block(&nodes[0], &block);
5742                 block.header.prev_blockhash = block.block_hash();
5743         }
5744         if !check_revoke_no_close {
5745                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5746                 check_closed_broadcast!(nodes[0], true);
5747                 check_added_monitors!(nodes[0], 1);
5748                 check_closed_event!(nodes[0], 1, ClosureReason::HolderForceClosed, [nodes[1].node.get_our_node_id()], 100000);
5749         } else {
5750                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5751         }
5752 }
5753
5754 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5755 // There are only a few cases to test here:
5756 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5757 //    broadcastable commitment transactions result in channel closure,
5758 //  * its included in an unrevoked-but-previous remote commitment transaction,
5759 //  * its included in the latest remote or local commitment transactions.
5760 // We test each of the three possible commitment transactions individually and use both dust and
5761 // non-dust HTLCs.
5762 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5763 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5764 // tested for at least one of the cases in other tests.
5765 #[test]
5766 fn htlc_claim_single_commitment_only_a() {
5767         do_htlc_claim_local_commitment_only(true);
5768         do_htlc_claim_local_commitment_only(false);
5769
5770         do_htlc_claim_current_remote_commitment_only(true);
5771         do_htlc_claim_current_remote_commitment_only(false);
5772 }
5773
5774 #[test]
5775 fn htlc_claim_single_commitment_only_b() {
5776         do_htlc_claim_previous_remote_commitment_only(true, false);
5777         do_htlc_claim_previous_remote_commitment_only(false, false);
5778         do_htlc_claim_previous_remote_commitment_only(true, true);
5779         do_htlc_claim_previous_remote_commitment_only(false, true);
5780 }
5781
5782 #[test]
5783 #[should_panic]
5784 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5785         let chanmon_cfgs = create_chanmon_cfgs(2);
5786         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5787         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5788         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5789         // Force duplicate randomness for every get-random call
5790         for node in nodes.iter() {
5791                 *node.keys_manager.override_random_bytes.lock().unwrap() = Some([0; 32]);
5792         }
5793
5794         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5795         let channel_value_satoshis=10000;
5796         let push_msat=10001;
5797         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5798         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5799         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5800         get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5801
5802         // Create a second channel with the same random values. This used to panic due to a colliding
5803         // channel_id, but now panics due to a colliding outbound SCID alias.
5804         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5805 }
5806
5807 #[test]
5808 fn bolt2_open_channel_sending_node_checks_part2() {
5809         let chanmon_cfgs = create_chanmon_cfgs(2);
5810         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5811         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5812         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5813
5814         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5815         let channel_value_satoshis=2^24;
5816         let push_msat=10001;
5817         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5818
5819         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5820         let channel_value_satoshis=10000;
5821         // Test when push_msat is equal to 1000 * funding_satoshis.
5822         let push_msat=1000*channel_value_satoshis+1;
5823         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_err());
5824
5825         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5826         let channel_value_satoshis=10000;
5827         let push_msat=10001;
5828         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).is_ok()); //Create a valid channel
5829         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5830         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5831
5832         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5833         // 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
5834         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5835
5836         // 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.
5837         assert!(BREAKDOWN_TIMEOUT>0);
5838         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5839
5840         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5841         let chain_hash = ChainHash::using_genesis_block(Network::Testnet);
5842         assert_eq!(node0_to_1_send_open_channel.chain_hash, chain_hash);
5843
5844         // 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.
5845         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5846         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5847         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5848         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5849         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5850 }
5851
5852 #[test]
5853 fn bolt2_open_channel_sane_dust_limit() {
5854         let chanmon_cfgs = create_chanmon_cfgs(2);
5855         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5856         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5857         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5858
5859         let channel_value_satoshis=1000000;
5860         let push_msat=10001;
5861         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None, None).unwrap();
5862         let mut node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5863         node0_to_1_send_open_channel.dust_limit_satoshis = 547;
5864         node0_to_1_send_open_channel.channel_reserve_satoshis = 100001;
5865
5866         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel);
5867         let events = nodes[1].node.get_and_clear_pending_msg_events();
5868         let err_msg = match events[0] {
5869                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
5870                         msg.clone()
5871                 },
5872                 _ => panic!("Unexpected event"),
5873         };
5874         assert_eq!(err_msg.data, "dust_limit_satoshis (547) is greater than the implementation limit (546)");
5875 }
5876
5877 // Test that if we fail to send an HTLC that is being freed from the holding cell, and the HTLC
5878 // originated from our node, its failure is surfaced to the user. We trigger this failure to
5879 // free the HTLC by increasing our fee while the HTLC is in the holding cell such that the HTLC
5880 // is no longer affordable once it's freed.
5881 #[test]
5882 fn test_fail_holding_cell_htlc_upon_free() {
5883         let chanmon_cfgs = create_chanmon_cfgs(2);
5884         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5885         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5886         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5887         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5888
5889         // First nodes[0] generates an update_fee, setting the channel's
5890         // pending_update_fee.
5891         {
5892                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5893                 *feerate_lock += 20;
5894         }
5895         nodes[0].node.timer_tick_occurred();
5896         check_added_monitors!(nodes[0], 1);
5897
5898         let events = nodes[0].node.get_and_clear_pending_msg_events();
5899         assert_eq!(events.len(), 1);
5900         let (update_msg, commitment_signed) = match events[0] {
5901                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5902                         (update_fee.as_ref(), commitment_signed)
5903                 },
5904                 _ => panic!("Unexpected event"),
5905         };
5906
5907         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5908
5909         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5910         let channel_reserve = chan_stat.channel_reserve_msat;
5911         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5912         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5913
5914         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5915         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
5916         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
5917
5918         // Send a payment which passes reserve checks but gets stuck in the holding cell.
5919         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
5920                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
5921         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5922         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
5923
5924         // Flush the pending fee update.
5925         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
5926         let (as_revoke_and_ack, _) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5927         check_added_monitors!(nodes[1], 1);
5928         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
5929         check_added_monitors!(nodes[0], 1);
5930
5931         // Upon receipt of the RAA, there will be an attempt to resend the holding cell
5932         // HTLC, but now that the fee has been raised the payment will now fail, causing
5933         // us to surface its failure to the user.
5934         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5935         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
5936         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 1 HTLC updates in channel {}", chan.2), 1);
5937
5938         // Check that the payment failed to be sent out.
5939         let events = nodes[0].node.get_and_clear_pending_events();
5940         assert_eq!(events.len(), 2);
5941         match &events[0] {
5942                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
5943                         assert_eq!(PaymentId(our_payment_hash.0), *payment_id.as_ref().unwrap());
5944                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5945                         assert_eq!(*payment_failed_permanently, false);
5946                         assert_eq!(*short_channel_id, Some(route.paths[0].hops[0].short_channel_id));
5947                 },
5948                 _ => panic!("Unexpected event"),
5949         }
5950         match &events[1] {
5951                 &Event::PaymentFailed { ref payment_hash, .. } => {
5952                         assert_eq!(our_payment_hash.clone(), *payment_hash);
5953                 },
5954                 _ => panic!("Unexpected event"),
5955         }
5956 }
5957
5958 // Test that if multiple HTLCs are released from the holding cell and one is
5959 // valid but the other is no longer valid upon release, the valid HTLC can be
5960 // successfully completed while the other one fails as expected.
5961 #[test]
5962 fn test_free_and_fail_holding_cell_htlcs() {
5963         let chanmon_cfgs = create_chanmon_cfgs(2);
5964         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5965         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5966         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5967         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
5968
5969         // First nodes[0] generates an update_fee, setting the channel's
5970         // pending_update_fee.
5971         {
5972                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
5973                 *feerate_lock += 200;
5974         }
5975         nodes[0].node.timer_tick_occurred();
5976         check_added_monitors!(nodes[0], 1);
5977
5978         let events = nodes[0].node.get_and_clear_pending_msg_events();
5979         assert_eq!(events.len(), 1);
5980         let (update_msg, commitment_signed) = match events[0] {
5981                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
5982                         (update_fee.as_ref(), commitment_signed)
5983                 },
5984                 _ => panic!("Unexpected event"),
5985         };
5986
5987         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
5988
5989         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
5990         let channel_reserve = chan_stat.channel_reserve_msat;
5991         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
5992         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
5993
5994         // 2* and +1 HTLCs on the commit tx fee calculation for the fee spike reserve.
5995         let amt_1 = 20000;
5996         let amt_2 = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 2 + 1, &channel_type_features) - amt_1;
5997         let (route_1, payment_hash_1, payment_preimage_1, payment_secret_1) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_1);
5998         let (route_2, payment_hash_2, _, payment_secret_2) = get_route_and_payment_hash!(nodes[0], nodes[1], amt_2);
5999
6000         // Send 2 payments which pass reserve checks but get stuck in the holding cell.
6001         nodes[0].node.send_payment_with_route(&route_1, payment_hash_1,
6002                 RecipientOnionFields::secret_only(payment_secret_1), PaymentId(payment_hash_1.0)).unwrap();
6003         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6004         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1);
6005         let payment_id_2 = PaymentId(nodes[0].keys_manager.get_secure_random_bytes());
6006         nodes[0].node.send_payment_with_route(&route_2, payment_hash_2,
6007                 RecipientOnionFields::secret_only(payment_secret_2), payment_id_2).unwrap();
6008         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6009         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, amt_1 + amt_2);
6010
6011         // Flush the pending fee update.
6012         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
6013         let (revoke_and_ack, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6014         check_added_monitors!(nodes[1], 1);
6015         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_and_ack);
6016         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6017         check_added_monitors!(nodes[0], 2);
6018
6019         // Upon receipt of the RAA, there will be an attempt to resend the holding cell HTLCs,
6020         // but now that the fee has been raised the second payment will now fail, causing us
6021         // to surface its failure to the user. The first payment should succeed.
6022         chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6023         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, 0);
6024         nodes[0].logger.assert_log("lightning::ln::channel", format!("Freeing holding cell with 2 HTLC updates in channel {}", chan.2), 1);
6025
6026         // Check that the second payment failed to be sent out.
6027         let events = nodes[0].node.get_and_clear_pending_events();
6028         assert_eq!(events.len(), 2);
6029         match &events[0] {
6030                 &Event::PaymentPathFailed { ref payment_id, ref payment_hash, ref payment_failed_permanently, failure: PathFailure::OnPath { network_update: None }, ref short_channel_id, .. } => {
6031                         assert_eq!(payment_id_2, *payment_id.as_ref().unwrap());
6032                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6033                         assert_eq!(*payment_failed_permanently, false);
6034                         assert_eq!(*short_channel_id, Some(route_2.paths[0].hops[0].short_channel_id));
6035                 },
6036                 _ => panic!("Unexpected event"),
6037         }
6038         match &events[1] {
6039                 &Event::PaymentFailed { ref payment_hash, .. } => {
6040                         assert_eq!(payment_hash_2.clone(), *payment_hash);
6041                 },
6042                 _ => panic!("Unexpected event"),
6043         }
6044
6045         // Complete the first payment and the RAA from the fee update.
6046         let (payment_event, send_raa_event) = {
6047                 let mut msgs = nodes[0].node.get_and_clear_pending_msg_events();
6048                 assert_eq!(msgs.len(), 2);
6049                 (SendEvent::from_event(msgs.remove(0)), msgs.remove(0))
6050         };
6051         let raa = match send_raa_event {
6052                 MessageSendEvent::SendRevokeAndACK { msg, .. } => msg,
6053                 _ => panic!("Unexpected event"),
6054         };
6055         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6056         check_added_monitors!(nodes[1], 1);
6057         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6058         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6059         let events = nodes[1].node.get_and_clear_pending_events();
6060         assert_eq!(events.len(), 1);
6061         match events[0] {
6062                 Event::PendingHTLCsForwardable { .. } => {},
6063                 _ => panic!("Unexpected event"),
6064         }
6065         nodes[1].node.process_pending_htlc_forwards();
6066         let events = nodes[1].node.get_and_clear_pending_events();
6067         assert_eq!(events.len(), 1);
6068         match events[0] {
6069                 Event::PaymentClaimable { .. } => {},
6070                 _ => panic!("Unexpected event"),
6071         }
6072         nodes[1].node.claim_funds(payment_preimage_1);
6073         check_added_monitors!(nodes[1], 1);
6074         expect_payment_claimed!(nodes[1], payment_hash_1, amt_1);
6075
6076         let update_msgs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6077         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msgs.update_fulfill_htlcs[0]);
6078         commitment_signed_dance!(nodes[0], nodes[1], update_msgs.commitment_signed, false, true);
6079         expect_payment_sent!(nodes[0], payment_preimage_1);
6080 }
6081
6082 // Test that if we fail to forward an HTLC that is being freed from the holding cell that the
6083 // HTLC is failed backwards. We trigger this failure to forward the freed HTLC by increasing
6084 // our fee while the HTLC is in the holding cell such that the HTLC is no longer affordable
6085 // once it's freed.
6086 #[test]
6087 fn test_fail_holding_cell_htlc_upon_free_multihop() {
6088         let chanmon_cfgs = create_chanmon_cfgs(3);
6089         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6090         // Avoid having to include routing fees in calculations
6091         let mut config = test_default_channel_config();
6092         config.channel_config.forwarding_fee_base_msat = 0;
6093         config.channel_config.forwarding_fee_proportional_millionths = 0;
6094         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[Some(config.clone()), Some(config.clone()), Some(config.clone())]);
6095         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6096         let chan_0_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6097         let chan_1_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 95000000);
6098
6099         // First nodes[1] generates an update_fee, setting the channel's
6100         // pending_update_fee.
6101         {
6102                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
6103                 *feerate_lock += 20;
6104         }
6105         nodes[1].node.timer_tick_occurred();
6106         check_added_monitors!(nodes[1], 1);
6107
6108         let events = nodes[1].node.get_and_clear_pending_msg_events();
6109         assert_eq!(events.len(), 1);
6110         let (update_msg, commitment_signed) = match events[0] {
6111                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
6112                         (update_fee.as_ref(), commitment_signed)
6113                 },
6114                 _ => panic!("Unexpected event"),
6115         };
6116
6117         nodes[2].node.handle_update_fee(&nodes[1].node.get_our_node_id(), update_msg.unwrap());
6118
6119         let mut chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan_0_1.2);
6120         let channel_reserve = chan_stat.channel_reserve_msat;
6121         let feerate = get_feerate!(nodes[0], nodes[1], chan_0_1.2);
6122         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan_0_1.2);
6123
6124         // Send a payment which passes reserve checks but gets stuck in the holding cell.
6125         let max_can_send = 5000000 - channel_reserve - 2*commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6126         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], max_can_send);
6127         let payment_event = {
6128                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6129                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6130                 check_added_monitors!(nodes[0], 1);
6131
6132                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6133                 assert_eq!(events.len(), 1);
6134
6135                 SendEvent::from_event(events.remove(0))
6136         };
6137         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6138         check_added_monitors!(nodes[1], 0);
6139         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6140         expect_pending_htlcs_forwardable!(nodes[1]);
6141
6142         chan_stat = get_channel_value_stat!(nodes[1], nodes[2], chan_1_2.2);
6143         assert_eq!(chan_stat.holding_cell_outbound_amount_msat, max_can_send);
6144
6145         // Flush the pending fee update.
6146         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
6147         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
6148         check_added_monitors!(nodes[2], 1);
6149         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &raa);
6150         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &commitment_signed);
6151         check_added_monitors!(nodes[1], 2);
6152
6153         // A final RAA message is generated to finalize the fee update.
6154         let events = nodes[1].node.get_and_clear_pending_msg_events();
6155         assert_eq!(events.len(), 1);
6156
6157         let raa_msg = match &events[0] {
6158                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => {
6159                         msg.clone()
6160                 },
6161                 _ => panic!("Unexpected event"),
6162         };
6163
6164         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa_msg);
6165         check_added_monitors!(nodes[2], 1);
6166         assert!(nodes[2].node.get_and_clear_pending_msg_events().is_empty());
6167
6168         // nodes[1]'s ChannelManager will now signal that we have HTLC forwards to process.
6169         let process_htlc_forwards_event = nodes[1].node.get_and_clear_pending_events();
6170         assert_eq!(process_htlc_forwards_event.len(), 2);
6171         match &process_htlc_forwards_event[0] {
6172                 &Event::PendingHTLCsForwardable { .. } => {},
6173                 _ => panic!("Unexpected event"),
6174         }
6175
6176         // In response, we call ChannelManager's process_pending_htlc_forwards
6177         nodes[1].node.process_pending_htlc_forwards();
6178         check_added_monitors!(nodes[1], 1);
6179
6180         // This causes the HTLC to be failed backwards.
6181         let fail_event = nodes[1].node.get_and_clear_pending_msg_events();
6182         assert_eq!(fail_event.len(), 1);
6183         let (fail_msg, commitment_signed) = match &fail_event[0] {
6184                 &MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6185                         assert_eq!(updates.update_add_htlcs.len(), 0);
6186                         assert_eq!(updates.update_fulfill_htlcs.len(), 0);
6187                         assert_eq!(updates.update_fail_malformed_htlcs.len(), 0);
6188                         assert_eq!(updates.update_fail_htlcs.len(), 1);
6189                         (updates.update_fail_htlcs[0].clone(), updates.commitment_signed.clone())
6190                 },
6191                 _ => panic!("Unexpected event"),
6192         };
6193
6194         // Pass the failure messages back to nodes[0].
6195         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
6196         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
6197
6198         // Complete the HTLC failure+removal process.
6199         let (raa, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6200         check_added_monitors!(nodes[0], 1);
6201         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &raa);
6202         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
6203         check_added_monitors!(nodes[1], 2);
6204         let final_raa_event = nodes[1].node.get_and_clear_pending_msg_events();
6205         assert_eq!(final_raa_event.len(), 1);
6206         let raa = match &final_raa_event[0] {
6207                 &MessageSendEvent::SendRevokeAndACK { ref msg, .. } => msg.clone(),
6208                 _ => panic!("Unexpected event"),
6209         };
6210         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &raa);
6211         expect_payment_failed_with_update!(nodes[0], our_payment_hash, false, chan_1_2.0.contents.short_channel_id, false);
6212         check_added_monitors!(nodes[0], 1);
6213 }
6214
6215 #[test]
6216 fn test_payment_route_reaching_same_channel_twice() {
6217         //A route should not go through the same channel twice
6218         //It is enforced when constructing a route.
6219         let chanmon_cfgs = create_chanmon_cfgs(2);
6220         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6221         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6222         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6223         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6224
6225         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6226                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6227         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6228
6229         // Extend the path by itself, essentially simulating route going through same channel twice
6230         let cloned_hops = route.paths[0].hops.clone();
6231         route.paths[0].hops.extend_from_slice(&cloned_hops);
6232
6233         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6234                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6235         ), false, APIError::InvalidRoute { ref err },
6236         assert_eq!(err, &"Path went through the same channel twice"));
6237 }
6238
6239 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
6240 // 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.
6241 //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.
6242
6243 #[test]
6244 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
6245         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
6246         let chanmon_cfgs = create_chanmon_cfgs(2);
6247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6249         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6250         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6251
6252         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6253         route.paths[0].hops[0].fee_msat = 100;
6254
6255         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6256                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6257                 ), true, APIError::ChannelUnavailable { .. }, {});
6258         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6259 }
6260
6261 #[test]
6262 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
6263         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6264         let chanmon_cfgs = create_chanmon_cfgs(2);
6265         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6266         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6267         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6268         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6269
6270         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6271         route.paths[0].hops[0].fee_msat = 0;
6272         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6273                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)),
6274                 true, APIError::ChannelUnavailable { ref err },
6275                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6276
6277         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6278         nodes[0].logger.assert_log_contains("lightning::ln::channelmanager", "Cannot send 0-msat HTLC", 1);
6279 }
6280
6281 #[test]
6282 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6283         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6284         let chanmon_cfgs = create_chanmon_cfgs(2);
6285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6287         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6288         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6289
6290         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6291         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6292                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6293         check_added_monitors!(nodes[0], 1);
6294         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6295         updates.update_add_htlcs[0].amount_msat = 0;
6296
6297         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6298         nodes[1].logger.assert_log_contains("lightning::ln::channelmanager", "Remote side tried to send a 0-msat HTLC", 3);
6299         check_closed_broadcast!(nodes[1], true).unwrap();
6300         check_added_monitors!(nodes[1], 1);
6301         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Remote side tried to send a 0-msat HTLC".to_string() },
6302                 [nodes[0].node.get_our_node_id()], 100000);
6303 }
6304
6305 #[test]
6306 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6307         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6308         //It is enforced when constructing a route.
6309         let chanmon_cfgs = create_chanmon_cfgs(2);
6310         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6311         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6312         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6313         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6314
6315         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 0)
6316                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
6317         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], payment_params, 100000000);
6318         route.paths[0].hops.last_mut().unwrap().cltv_expiry_delta = 500000001;
6319         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6320                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6321                 ), true, APIError::InvalidRoute { ref err },
6322                 assert_eq!(err, &"Channel CLTV overflowed?"));
6323 }
6324
6325 #[test]
6326 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6327         //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.
6328         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6329         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6330         let chanmon_cfgs = create_chanmon_cfgs(2);
6331         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6332         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6333         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6334         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
6335         let max_accepted_htlcs = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
6336                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().counterparty_max_accepted_htlcs as u64;
6337
6338         // Fetch a route in advance as we will be unable to once we're unable to send.
6339         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6340         for i in 0..max_accepted_htlcs {
6341                 let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 100000);
6342                 let payment_event = {
6343                         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6344                                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6345                         check_added_monitors!(nodes[0], 1);
6346
6347                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6348                         assert_eq!(events.len(), 1);
6349                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6350                                 assert_eq!(htlcs[0].htlc_id, i);
6351                         } else {
6352                                 assert!(false);
6353                         }
6354                         SendEvent::from_event(events.remove(0))
6355                 };
6356                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6357                 check_added_monitors!(nodes[1], 0);
6358                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6359
6360                 expect_pending_htlcs_forwardable!(nodes[1]);
6361                 expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 100000);
6362         }
6363         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6364                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6365                 ), true, APIError::ChannelUnavailable { .. }, {});
6366
6367         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6368 }
6369
6370 #[test]
6371 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6372         //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.
6373         let chanmon_cfgs = create_chanmon_cfgs(2);
6374         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6375         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6376         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6377         let channel_value = 100000;
6378         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
6379         let max_in_flight = get_channel_value_stat!(nodes[0], nodes[1], chan.2).counterparty_max_htlc_value_in_flight_msat;
6380
6381         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
6382
6383         let (mut route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_in_flight);
6384         // Manually create a route over our max in flight (which our router normally automatically
6385         // limits us to.
6386         route.paths[0].hops[0].fee_msat =  max_in_flight + 1;
6387         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6388                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)
6389                 ), true, APIError::ChannelUnavailable { .. }, {});
6390         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6391
6392         send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
6393 }
6394
6395 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6396 #[test]
6397 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6398         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6399         let chanmon_cfgs = create_chanmon_cfgs(2);
6400         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6401         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6402         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6403         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6404         let htlc_minimum_msat: u64;
6405         {
6406                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
6407                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
6408                 let channel = chan_lock.channel_by_id.get(&chan.2).unwrap();
6409                 htlc_minimum_msat = channel.context().get_holder_htlc_minimum_msat();
6410         }
6411
6412         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], htlc_minimum_msat);
6413         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6414                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6415         check_added_monitors!(nodes[0], 1);
6416         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6417         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6418         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6419         assert!(nodes[1].node.list_channels().is_empty());
6420         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6421         assert!(regex::Regex::new(r"Remote side tried to send less than our minimum HTLC value\. Lower limit: \(\d+\)\. Actual: \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6422         check_added_monitors!(nodes[1], 1);
6423         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6424 }
6425
6426 #[test]
6427 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6428         //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
6429         let chanmon_cfgs = create_chanmon_cfgs(2);
6430         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6431         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6432         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6433         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6434
6435         let chan_stat = get_channel_value_stat!(nodes[0], nodes[1], chan.2);
6436         let channel_reserve = chan_stat.channel_reserve_msat;
6437         let feerate = get_feerate!(nodes[0], nodes[1], chan.2);
6438         let channel_type_features = get_channel_type_features!(nodes[0], nodes[1], chan.2);
6439         // The 2* and +1 are for the fee spike reserve.
6440         let commit_tx_fee_outbound = 2 * commit_tx_fee_msat(feerate, 1 + 1, &channel_type_features);
6441
6442         let max_can_send = 5000000 - channel_reserve - commit_tx_fee_outbound;
6443         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], max_can_send);
6444         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6445                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6446         check_added_monitors!(nodes[0], 1);
6447         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6448
6449         // Even though channel-initiator senders are required to respect the fee_spike_reserve,
6450         // at this time channel-initiatee receivers are not required to enforce that senders
6451         // respect the fee_spike_reserve.
6452         updates.update_add_htlcs[0].amount_msat = max_can_send + commit_tx_fee_outbound + 1;
6453         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6454
6455         assert!(nodes[1].node.list_channels().is_empty());
6456         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6457         assert_eq!(err_msg.data, "Remote HTLC add would put them under remote reserve value");
6458         check_added_monitors!(nodes[1], 1);
6459         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6460 }
6461
6462 #[test]
6463 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6464         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6465         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6466         let chanmon_cfgs = create_chanmon_cfgs(2);
6467         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6468         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6469         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6470         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6471
6472         let send_amt = 3999999;
6473         let (mut route, our_payment_hash, _, our_payment_secret) =
6474                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
6475         route.paths[0].hops[0].fee_msat = send_amt;
6476         let session_priv = SecretKey::from_slice(&[42; 32]).unwrap();
6477         let cur_height = nodes[0].node.best_block.read().unwrap().height() + 1;
6478         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6479         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(
6480                 &route.paths[0], send_amt, RecipientOnionFields::secret_only(our_payment_secret), cur_height, &None).unwrap();
6481         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
6482
6483         let mut msg = msgs::UpdateAddHTLC {
6484                 channel_id: chan.2,
6485                 htlc_id: 0,
6486                 amount_msat: 1000,
6487                 payment_hash: our_payment_hash,
6488                 cltv_expiry: htlc_cltv,
6489                 onion_routing_packet: onion_packet.clone(),
6490                 skimmed_fee_msat: None,
6491                 blinding_point: None,
6492         };
6493
6494         for i in 0..50 {
6495                 msg.htlc_id = i as u64;
6496                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6497         }
6498         msg.htlc_id = (50) as u64;
6499         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6500
6501         assert!(nodes[1].node.list_channels().is_empty());
6502         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6503         assert!(regex::Regex::new(r"Remote tried to push more than our max accepted HTLCs \(\d+\)").unwrap().is_match(err_msg.data.as_str()));
6504         check_added_monitors!(nodes[1], 1);
6505         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6506 }
6507
6508 #[test]
6509 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6510         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6511         let chanmon_cfgs = create_chanmon_cfgs(2);
6512         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6513         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6514         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6515         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6516
6517         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6518         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6519                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6520         check_added_monitors!(nodes[0], 1);
6521         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6522         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], nodes[0], chan.2).counterparty_max_htlc_value_in_flight_msat + 1;
6523         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6524
6525         assert!(nodes[1].node.list_channels().is_empty());
6526         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6527         assert!(regex::Regex::new("Remote HTLC add would put them over our max HTLC value").unwrap().is_match(err_msg.data.as_str()));
6528         check_added_monitors!(nodes[1], 1);
6529         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 1000000);
6530 }
6531
6532 #[test]
6533 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6534         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6535         let chanmon_cfgs = create_chanmon_cfgs(2);
6536         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6537         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6538         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6539
6540         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
6541         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6542         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6543                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6544         check_added_monitors!(nodes[0], 1);
6545         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6546         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6547         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6548
6549         assert!(nodes[1].node.list_channels().is_empty());
6550         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6551         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6552         check_added_monitors!(nodes[1], 1);
6553         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6554 }
6555
6556 #[test]
6557 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6558         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6559         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6560         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6561         let chanmon_cfgs = create_chanmon_cfgs(2);
6562         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6563         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6564         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6565
6566         create_announced_chan_between_nodes(&nodes, 0, 1);
6567         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6568         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6569                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6570         check_added_monitors!(nodes[0], 1);
6571         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6572         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6573
6574         //Disconnect and Reconnect
6575         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
6576         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
6577         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
6578                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
6579         }, true).unwrap();
6580         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6581         assert_eq!(reestablish_1.len(), 1);
6582         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
6583                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
6584         }, false).unwrap();
6585         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6586         assert_eq!(reestablish_2.len(), 1);
6587         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6588         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6589         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6590         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6591
6592         //Resend HTLC
6593         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6594         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6595         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6596         check_added_monitors!(nodes[1], 1);
6597         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6598
6599         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6600
6601         assert!(nodes[1].node.list_channels().is_empty());
6602         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6603         assert!(regex::Regex::new(r"Remote skipped HTLC ID \(skipped ID: \d+\)").unwrap().is_match(err_msg.data.as_str()));
6604         check_added_monitors!(nodes[1], 1);
6605         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[0].node.get_our_node_id()], 100000);
6606 }
6607
6608 #[test]
6609 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6610         //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.
6611
6612         let chanmon_cfgs = create_chanmon_cfgs(2);
6613         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6614         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6615         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6616         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6617         let (route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6618         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6619                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6620
6621         check_added_monitors!(nodes[0], 1);
6622         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6623         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6624
6625         let update_msg = msgs::UpdateFulfillHTLC{
6626                 channel_id: chan.2,
6627                 htlc_id: 0,
6628                 payment_preimage: our_payment_preimage,
6629         };
6630
6631         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6632
6633         assert!(nodes[0].node.list_channels().is_empty());
6634         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6635         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6636         check_added_monitors!(nodes[0], 1);
6637         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6638 }
6639
6640 #[test]
6641 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6642         //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.
6643
6644         let chanmon_cfgs = create_chanmon_cfgs(2);
6645         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6646         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6647         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6648         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6649
6650         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6651         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6652                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6653         check_added_monitors!(nodes[0], 1);
6654         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6655         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6656
6657         let update_msg = msgs::UpdateFailHTLC{
6658                 channel_id: chan.2,
6659                 htlc_id: 0,
6660                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6661         };
6662
6663         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6664
6665         assert!(nodes[0].node.list_channels().is_empty());
6666         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6667         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6668         check_added_monitors!(nodes[0], 1);
6669         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6670 }
6671
6672 #[test]
6673 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6674         //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.
6675
6676         let chanmon_cfgs = create_chanmon_cfgs(2);
6677         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6678         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6679         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6680         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
6681
6682         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6683         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6684                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6685         check_added_monitors!(nodes[0], 1);
6686         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6687         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6688         let update_msg = msgs::UpdateFailMalformedHTLC{
6689                 channel_id: chan.2,
6690                 htlc_id: 0,
6691                 sha256_of_onion: [1; 32],
6692                 failure_code: 0x8000,
6693         };
6694
6695         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6696
6697         assert!(nodes[0].node.list_channels().is_empty());
6698         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6699         assert!(regex::Regex::new(r"Remote tried to fulfill/fail HTLC \(\d+\) before it had been committed").unwrap().is_match(err_msg.data.as_str()));
6700         check_added_monitors!(nodes[0], 1);
6701         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6702 }
6703
6704 #[test]
6705 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6706         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6707
6708         let chanmon_cfgs = create_chanmon_cfgs(2);
6709         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6710         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6711         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6712         create_announced_chan_between_nodes(&nodes, 0, 1);
6713
6714         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6715
6716         nodes[1].node.claim_funds(our_payment_preimage);
6717         check_added_monitors!(nodes[1], 1);
6718         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6719
6720         let events = nodes[1].node.get_and_clear_pending_msg_events();
6721         assert_eq!(events.len(), 1);
6722         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6723                 match events[0] {
6724                         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, .. } } => {
6725                                 assert!(update_add_htlcs.is_empty());
6726                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6727                                 assert!(update_fail_htlcs.is_empty());
6728                                 assert!(update_fail_malformed_htlcs.is_empty());
6729                                 assert!(update_fee.is_none());
6730                                 update_fulfill_htlcs[0].clone()
6731                         },
6732                         _ => panic!("Unexpected event"),
6733                 }
6734         };
6735
6736         update_fulfill_msg.htlc_id = 1;
6737
6738         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6739
6740         assert!(nodes[0].node.list_channels().is_empty());
6741         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6742         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6743         check_added_monitors!(nodes[0], 1);
6744         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6745 }
6746
6747 #[test]
6748 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6749         //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.
6750
6751         let chanmon_cfgs = create_chanmon_cfgs(2);
6752         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6753         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6754         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6755         create_announced_chan_between_nodes(&nodes, 0, 1);
6756
6757         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 100_000);
6758
6759         nodes[1].node.claim_funds(our_payment_preimage);
6760         check_added_monitors!(nodes[1], 1);
6761         expect_payment_claimed!(nodes[1], our_payment_hash, 100_000);
6762
6763         let events = nodes[1].node.get_and_clear_pending_msg_events();
6764         assert_eq!(events.len(), 1);
6765         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6766                 match events[0] {
6767                         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, .. } } => {
6768                                 assert!(update_add_htlcs.is_empty());
6769                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6770                                 assert!(update_fail_htlcs.is_empty());
6771                                 assert!(update_fail_malformed_htlcs.is_empty());
6772                                 assert!(update_fee.is_none());
6773                                 update_fulfill_htlcs[0].clone()
6774                         },
6775                         _ => panic!("Unexpected event"),
6776                 }
6777         };
6778
6779         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6780
6781         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6782
6783         assert!(nodes[0].node.list_channels().is_empty());
6784         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6785         assert!(regex::Regex::new(r"Remote tried to fulfill HTLC \(\d+\) with an incorrect preimage").unwrap().is_match(err_msg.data.as_str()));
6786         check_added_monitors!(nodes[0], 1);
6787         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 100000);
6788 }
6789
6790 #[test]
6791 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6792         //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.
6793
6794         let chanmon_cfgs = create_chanmon_cfgs(2);
6795         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6796         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6797         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6798         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6799
6800         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], 1000000);
6801         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6802                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6803         check_added_monitors!(nodes[0], 1);
6804
6805         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6806         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6807
6808         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6809         check_added_monitors!(nodes[1], 0);
6810         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6811
6812         let events = nodes[1].node.get_and_clear_pending_msg_events();
6813
6814         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6815                 match events[0] {
6816                         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, .. } } => {
6817                                 assert!(update_add_htlcs.is_empty());
6818                                 assert!(update_fulfill_htlcs.is_empty());
6819                                 assert!(update_fail_htlcs.is_empty());
6820                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6821                                 assert!(update_fee.is_none());
6822                                 update_fail_malformed_htlcs[0].clone()
6823                         },
6824                         _ => panic!("Unexpected event"),
6825                 }
6826         };
6827         update_msg.failure_code &= !0x8000;
6828         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6829
6830         assert!(nodes[0].node.list_channels().is_empty());
6831         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6832         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6833         check_added_monitors!(nodes[0], 1);
6834         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: err_msg.data }, [nodes[1].node.get_our_node_id()], 1000000);
6835 }
6836
6837 #[test]
6838 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6839         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6840         //    * 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.
6841
6842         let chanmon_cfgs = create_chanmon_cfgs(3);
6843         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6844         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6845         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6846         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
6847         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
6848
6849         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100000);
6850
6851         //First hop
6852         let mut payment_event = {
6853                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6854                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6855                 check_added_monitors!(nodes[0], 1);
6856                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6857                 assert_eq!(events.len(), 1);
6858                 SendEvent::from_event(events.remove(0))
6859         };
6860         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6861         check_added_monitors!(nodes[1], 0);
6862         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6863         expect_pending_htlcs_forwardable!(nodes[1]);
6864         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6865         assert_eq!(events_2.len(), 1);
6866         check_added_monitors!(nodes[1], 1);
6867         payment_event = SendEvent::from_event(events_2.remove(0));
6868         assert_eq!(payment_event.msgs.len(), 1);
6869
6870         //Second Hop
6871         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6872         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6873         check_added_monitors!(nodes[2], 0);
6874         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6875
6876         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6877         assert_eq!(events_3.len(), 1);
6878         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6879                 match events_3[0] {
6880                         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 } } => {
6881                                 assert!(update_add_htlcs.is_empty());
6882                                 assert!(update_fulfill_htlcs.is_empty());
6883                                 assert!(update_fail_htlcs.is_empty());
6884                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6885                                 assert!(update_fee.is_none());
6886                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6887                         },
6888                         _ => panic!("Unexpected event"),
6889                 }
6890         };
6891
6892         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6893
6894         check_added_monitors!(nodes[1], 0);
6895         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6896         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6897         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6898         assert_eq!(events_4.len(), 1);
6899
6900         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6901         match events_4[0] {
6902                 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, .. } } => {
6903                         assert!(update_add_htlcs.is_empty());
6904                         assert!(update_fulfill_htlcs.is_empty());
6905                         assert_eq!(update_fail_htlcs.len(), 1);
6906                         assert!(update_fail_malformed_htlcs.is_empty());
6907                         assert!(update_fee.is_none());
6908                 },
6909                 _ => panic!("Unexpected event"),
6910         };
6911
6912         check_added_monitors!(nodes[1], 1);
6913 }
6914
6915 #[test]
6916 fn test_channel_failed_after_message_with_badonion_node_perm_bits_set() {
6917         let chanmon_cfgs = create_chanmon_cfgs(3);
6918         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6919         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6920         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6921         create_announced_chan_between_nodes(&nodes, 0, 1);
6922         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
6923
6924         let (route, our_payment_hash, _, our_payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[2], 100_000);
6925
6926         // First hop
6927         let mut payment_event = {
6928                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
6929                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
6930                 check_added_monitors!(nodes[0], 1);
6931                 SendEvent::from_node(&nodes[0])
6932         };
6933
6934         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6935         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6936         expect_pending_htlcs_forwardable!(nodes[1]);
6937         check_added_monitors!(nodes[1], 1);
6938         payment_event = SendEvent::from_node(&nodes[1]);
6939         assert_eq!(payment_event.msgs.len(), 1);
6940
6941         // Second Hop
6942         payment_event.msgs[0].onion_routing_packet.version = 1; // Trigger an invalid_onion_version error
6943         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6944         check_added_monitors!(nodes[2], 0);
6945         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6946
6947         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6948         assert_eq!(events_3.len(), 1);
6949         match events_3[0] {
6950                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6951                         let mut update_msg = updates.update_fail_malformed_htlcs[0].clone();
6952                         // Set the NODE bit (BADONION and PERM already set in invalid_onion_version error)
6953                         update_msg.failure_code |= 0x2000;
6954
6955                         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg);
6956                         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true);
6957                 },
6958                 _ => panic!("Unexpected event"),
6959         }
6960
6961         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1],
6962                 vec![HTLCDestination::NextHopChannel {
6963                         node_id: Some(nodes[2].node.get_our_node_id()), channel_id: chan_2.2 }]);
6964         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6965         assert_eq!(events_4.len(), 1);
6966         check_added_monitors!(nodes[1], 1);
6967
6968         match events_4[0] {
6969                 MessageSendEvent::UpdateHTLCs { ref updates, .. } => {
6970                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
6971                         commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, false, true);
6972                 },
6973                 _ => panic!("Unexpected event"),
6974         }
6975
6976         let events_5 = nodes[0].node.get_and_clear_pending_events();
6977         assert_eq!(events_5.len(), 2);
6978
6979         // Expect a PaymentPathFailed event with a ChannelFailure network update for the channel between
6980         // the node originating the error to its next hop.
6981         match events_5[0] {
6982                 Event::PaymentPathFailed { error_code, failure: PathFailure::OnPath { network_update: Some(NetworkUpdate::ChannelFailure { short_channel_id, is_permanent }) }, ..
6983                 } => {
6984                         assert_eq!(short_channel_id, chan_2.0.contents.short_channel_id);
6985                         assert!(is_permanent);
6986                         assert_eq!(error_code, Some(0x8000|0x4000|0x2000|4));
6987                 },
6988                 _ => panic!("Unexpected event"),
6989         }
6990         match events_5[1] {
6991                 Event::PaymentFailed { payment_hash, .. } => {
6992                         assert_eq!(payment_hash, our_payment_hash);
6993                 },
6994                 _ => panic!("Unexpected event"),
6995         }
6996
6997         // TODO: Test actual removal of channel from NetworkGraph when it's implemented.
6998 }
6999
7000 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
7001         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
7002         // 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
7003         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
7004
7005         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7006         chanmon_cfgs[0].keys_manager.disable_revocation_policy_check = true;
7007         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7008         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7009         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7010         let chan =create_announced_chan_between_nodes(&nodes, 0, 1);
7011
7012         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7013                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7014
7015         // We route 2 dust-HTLCs between A and B
7016         let (_, payment_hash_1, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7017         let (_, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7018         route_payment(&nodes[0], &[&nodes[1]], 1000000);
7019
7020         // Cache one local commitment tx as previous
7021         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7022
7023         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
7024         nodes[1].node.fail_htlc_backwards(&payment_hash_2);
7025         check_added_monitors!(nodes[1], 0);
7026         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7027         check_added_monitors!(nodes[1], 1);
7028
7029         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7030         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
7031         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
7032         check_added_monitors!(nodes[0], 1);
7033
7034         // Cache one local commitment tx as lastest
7035         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7036
7037         let events = nodes[0].node.get_and_clear_pending_msg_events();
7038         match events[0] {
7039                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
7040                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7041                 },
7042                 _ => panic!("Unexpected event"),
7043         }
7044         match events[1] {
7045                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
7046                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
7047                 },
7048                 _ => panic!("Unexpected event"),
7049         }
7050
7051         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
7052         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
7053         if announce_latest {
7054                 mine_transaction(&nodes[0], &as_last_commitment_tx[0]);
7055         } else {
7056                 mine_transaction(&nodes[0], &as_prev_commitment_tx[0]);
7057         }
7058
7059         check_closed_broadcast!(nodes[0], true);
7060         check_added_monitors!(nodes[0], 1);
7061         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7062
7063         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7064         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7065         let events = nodes[0].node.get_and_clear_pending_events();
7066         // Only 2 PaymentPathFailed events should show up, over-dust HTLC has to be failed by timeout tx
7067         assert_eq!(events.len(), 4);
7068         let mut first_failed = false;
7069         for event in events {
7070                 match event {
7071                         Event::PaymentPathFailed { payment_hash, .. } => {
7072                                 if payment_hash == payment_hash_1 {
7073                                         assert!(!first_failed);
7074                                         first_failed = true;
7075                                 } else {
7076                                         assert_eq!(payment_hash, payment_hash_2);
7077                                 }
7078                         },
7079                         Event::PaymentFailed { .. } => {}
7080                         _ => panic!("Unexpected event"),
7081                 }
7082         }
7083 }
7084
7085 #[test]
7086 fn test_failure_delay_dust_htlc_local_commitment() {
7087         do_test_failure_delay_dust_htlc_local_commitment(true);
7088         do_test_failure_delay_dust_htlc_local_commitment(false);
7089 }
7090
7091 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
7092         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
7093         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
7094         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
7095         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
7096         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
7097         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
7098
7099         let chanmon_cfgs = create_chanmon_cfgs(3);
7100         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7101         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7102         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7103         let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
7104
7105         let bs_dust_limit = nodes[1].node.per_peer_state.read().unwrap().get(&nodes[0].node.get_our_node_id())
7106                 .unwrap().lock().unwrap().channel_by_id.get(&chan.2).unwrap().context().holder_dust_limit_satoshis;
7107
7108         let (_payment_preimage_1, dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
7109         let (_payment_preimage_2, non_dust_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7110
7111         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
7112         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
7113
7114         // We revoked bs_commitment_tx
7115         if revoked {
7116                 let (payment_preimage_3, ..) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
7117                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
7118         }
7119
7120         let mut timeout_tx = Vec::new();
7121         if local {
7122                 // We fail dust-HTLC 1 by broadcast of local commitment tx
7123                 mine_transaction(&nodes[0], &as_commitment_tx[0]);
7124                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7125                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7126                 expect_payment_failed!(nodes[0], dust_hash, false);
7127
7128                 connect_blocks(&nodes[0], TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS - ANTI_REORG_DELAY);
7129                 check_closed_broadcast!(nodes[0], true);
7130                 check_added_monitors!(nodes[0], 1);
7131                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7132                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
7133                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7134                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
7135                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7136                 mine_transaction(&nodes[0], &timeout_tx[0]);
7137                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7138                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7139         } else {
7140                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
7141                 mine_transaction(&nodes[0], &bs_commitment_tx[0]);
7142                 check_closed_broadcast!(nodes[0], true);
7143                 check_added_monitors!(nodes[0], 1);
7144                 check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
7145                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7146
7147                 connect_blocks(&nodes[0], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7148                 timeout_tx = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().drain(..)
7149                         .filter(|tx| tx.input[0].previous_output.txid == bs_commitment_tx[0].txid()).collect();
7150                 check_spends!(timeout_tx[0], bs_commitment_tx[0]);
7151                 // For both a revoked or non-revoked commitment transaction, after ANTI_REORG_DELAY the
7152                 // dust HTLC should have been failed.
7153                 expect_payment_failed!(nodes[0], dust_hash, false);
7154
7155                 if !revoked {
7156                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7157                 } else {
7158                         assert_eq!(timeout_tx[0].lock_time.to_consensus_u32(), 11);
7159                 }
7160                 // We fail non-dust-HTLC 2 by broadcast of local timeout/revocation-claim tx
7161                 mine_transaction(&nodes[0], &timeout_tx[0]);
7162                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
7163                 connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7164                 expect_payment_failed!(nodes[0], non_dust_hash, false);
7165         }
7166 }
7167
7168 #[test]
7169 fn test_sweep_outbound_htlc_failure_update() {
7170         do_test_sweep_outbound_htlc_failure_update(false, true);
7171         do_test_sweep_outbound_htlc_failure_update(false, false);
7172         do_test_sweep_outbound_htlc_failure_update(true, false);
7173 }
7174
7175 #[test]
7176 fn test_user_configurable_csv_delay() {
7177         // We test our channel constructors yield errors when we pass them absurd csv delay
7178
7179         let mut low_our_to_self_config = UserConfig::default();
7180         low_our_to_self_config.channel_handshake_config.our_to_self_delay = 6;
7181         let mut high_their_to_self_config = UserConfig::default();
7182         high_their_to_self_config.channel_handshake_limits.their_to_self_delay = 100;
7183         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
7184         let chanmon_cfgs = create_chanmon_cfgs(2);
7185         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7186         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
7187         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7188
7189         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in OutboundV1Channel::new()
7190         if let Err(error) = OutboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7191                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[1].node.init_features(), 1000000, 1000000, 0,
7192                 &low_our_to_self_config, 0, 42, None)
7193         {
7194                 match error {
7195                         APIError::APIMisuseError { err } => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str())); },
7196                         _ => panic!("Unexpected event"),
7197                 }
7198         } else { assert!(false) }
7199
7200         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in InboundV1Channel::new()
7201         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7202         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7203         open_channel.to_self_delay = 200;
7204         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7205                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
7206                 &low_our_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7207         {
7208                 match error {
7209                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"Configured with an unreasonable our_to_self_delay \(\d+\) putting user funds at risks").unwrap().is_match(err.as_str()));  },
7210                         _ => panic!("Unexpected event"),
7211                 }
7212         } else { assert!(false); }
7213
7214         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7215         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7216         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7217         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7218         accept_channel.to_self_delay = 200;
7219         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
7220         let reason_msg;
7221         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7222                 match action {
7223                         &ErrorAction::SendErrorMessage { ref msg } => {
7224                                 assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(msg.data.as_str()));
7225                                 reason_msg = msg.data.clone();
7226                         },
7227                         _ => { panic!(); }
7228                 }
7229         } else { panic!(); }
7230         check_closed_event!(nodes[0], 1, ClosureReason::ProcessingError { err: reason_msg }, [nodes[1].node.get_our_node_id()], 1000000);
7231
7232         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in InboundV1Channel::new()
7233         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None, None).unwrap();
7234         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7235         open_channel.to_self_delay = 200;
7236         if let Err(error) = InboundV1Channel::new(&LowerBoundedFeeEstimator::new(&test_utils::TestFeeEstimator { sat_per_kw: Mutex::new(253) }),
7237                 &nodes[0].keys_manager, &nodes[0].keys_manager, nodes[1].node.get_our_node_id(), &nodes[0].node.channel_type_features(), &nodes[1].node.init_features(), &open_channel, 0,
7238                 &high_their_to_self_config, 0, &nodes[0].logger, /*is_0conf=*/false)
7239         {
7240                 match error {
7241                         ChannelError::Close(err) => { assert!(regex::Regex::new(r"They wanted our payments to be delayed by a needlessly long period\. Upper limit: \d+\. Actual: \d+").unwrap().is_match(err.as_str())); },
7242                         _ => panic!("Unexpected event"),
7243                 }
7244         } else { assert!(false); }
7245 }
7246
7247 #[test]
7248 fn test_check_htlc_underpaying() {
7249         // Send payment through A -> B but A is maliciously
7250         // sending a probe payment (i.e less than expected value0
7251         // to B, B should refuse payment.
7252
7253         let chanmon_cfgs = create_chanmon_cfgs(2);
7254         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7255         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7256         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7257
7258         // Create some initial channels
7259         create_announced_chan_between_nodes(&nodes, 0, 1);
7260
7261         let scorer = test_utils::TestScorer::new();
7262         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7263         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
7264                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7265         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 10_000);
7266         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(),
7267                 None, nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7268         let (_, our_payment_hash, _) = get_payment_preimage_hash!(nodes[0]);
7269         let our_payment_secret = nodes[1].node.create_inbound_payment_for_hash(our_payment_hash, Some(100_000), 7200, None).unwrap();
7270         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
7271                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
7272         check_added_monitors!(nodes[0], 1);
7273
7274         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
7275         assert_eq!(events.len(), 1);
7276         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
7277         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
7278         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
7279
7280         // Note that we first have to wait a random delay before processing the receipt of the HTLC,
7281         // and then will wait a second random delay before failing the HTLC back:
7282         expect_pending_htlcs_forwardable!(nodes[1]);
7283         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
7284
7285         // Node 3 is expecting payment of 100_000 but received 10_000,
7286         // it should fail htlc like we didn't know the preimage.
7287         nodes[1].node.process_pending_htlc_forwards();
7288
7289         let events = nodes[1].node.get_and_clear_pending_msg_events();
7290         assert_eq!(events.len(), 1);
7291         let (update_fail_htlc, commitment_signed) = match events[0] {
7292                 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 } } => {
7293                         assert!(update_add_htlcs.is_empty());
7294                         assert!(update_fulfill_htlcs.is_empty());
7295                         assert_eq!(update_fail_htlcs.len(), 1);
7296                         assert!(update_fail_malformed_htlcs.is_empty());
7297                         assert!(update_fee.is_none());
7298                         (update_fail_htlcs[0].clone(), commitment_signed)
7299                 },
7300                 _ => panic!("Unexpected event"),
7301         };
7302         check_added_monitors!(nodes[1], 1);
7303
7304         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7305         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7306
7307         // 10_000 msat as u64, followed by a height of CHAN_CONFIRM_DEPTH as u32
7308         let mut expected_failure_data = (10_000 as u64).to_be_bytes().to_vec();
7309         expected_failure_data.extend_from_slice(&CHAN_CONFIRM_DEPTH.to_be_bytes());
7310         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7311 }
7312
7313 #[test]
7314 fn test_announce_disable_channels() {
7315         // Create 2 channels between A and B. Disconnect B. Call timer_tick_occurred and check for generated
7316         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7317
7318         let chanmon_cfgs = create_chanmon_cfgs(2);
7319         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7320         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7321         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7322
7323         create_announced_chan_between_nodes(&nodes, 0, 1);
7324         create_announced_chan_between_nodes(&nodes, 1, 0);
7325         create_announced_chan_between_nodes(&nodes, 0, 1);
7326
7327         // Disconnect peers
7328         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
7329         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
7330
7331         for _ in 0..DISABLE_GOSSIP_TICKS + 1 {
7332                 nodes[0].node.timer_tick_occurred();
7333         }
7334         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7335         assert_eq!(msg_events.len(), 3);
7336         let mut chans_disabled = HashMap::new();
7337         for e in msg_events {
7338                 match e {
7339                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7340                                 assert_eq!(msg.contents.flags & (1<<1), 1<<1); // The "channel disabled" bit should be set
7341                                 // Check that each channel gets updated exactly once
7342                                 if chans_disabled.insert(msg.contents.short_channel_id, msg.contents.timestamp).is_some() {
7343                                         panic!("Generated ChannelUpdate for wrong chan!");
7344                                 }
7345                         },
7346                         _ => panic!("Unexpected event"),
7347                 }
7348         }
7349         // Reconnect peers
7350         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init {
7351                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
7352         }, true).unwrap();
7353         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7354         assert_eq!(reestablish_1.len(), 3);
7355         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init {
7356                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
7357         }, false).unwrap();
7358         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7359         assert_eq!(reestablish_2.len(), 3);
7360
7361         // Reestablish chan_1
7362         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7363         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7364         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7365         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7366         // Reestablish chan_2
7367         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7368         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7369         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7370         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7371         // Reestablish chan_3
7372         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7373         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7374         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7375         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7376
7377         for _ in 0..ENABLE_GOSSIP_TICKS {
7378                 nodes[0].node.timer_tick_occurred();
7379         }
7380         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7381         nodes[0].node.timer_tick_occurred();
7382         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7383         assert_eq!(msg_events.len(), 3);
7384         for e in msg_events {
7385                 match e {
7386                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7387                                 assert_eq!(msg.contents.flags & (1<<1), 0); // The "channel disabled" bit should be off
7388                                 match chans_disabled.remove(&msg.contents.short_channel_id) {
7389                                         // Each update should have a higher timestamp than the previous one, replacing
7390                                         // the old one.
7391                                         Some(prev_timestamp) => assert!(msg.contents.timestamp > prev_timestamp),
7392                                         None => panic!("Generated ChannelUpdate for wrong chan!"),
7393                                 }
7394                         },
7395                         _ => panic!("Unexpected event"),
7396                 }
7397         }
7398         // Check that each channel gets updated exactly once
7399         assert!(chans_disabled.is_empty());
7400 }
7401
7402 #[test]
7403 fn test_bump_penalty_txn_on_revoked_commitment() {
7404         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7405         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7406
7407         let chanmon_cfgs = create_chanmon_cfgs(2);
7408         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7409         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7410         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7411
7412         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7413
7414         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7415         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 30)
7416                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7417         let (route,_, _, _) = get_route_and_payment_hash!(nodes[1], nodes[0], payment_params, 3000000);
7418         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7419
7420         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7421         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7422         assert_eq!(revoked_txn[0].output.len(), 4);
7423         assert_eq!(revoked_txn[0].input.len(), 1);
7424         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7425         let revoked_txid = revoked_txn[0].txid();
7426
7427         let mut penalty_sum = 0;
7428         for outp in revoked_txn[0].output.iter() {
7429                 if outp.script_pubkey.is_v0_p2wsh() {
7430                         penalty_sum += outp.value;
7431                 }
7432         }
7433
7434         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7435         let header_114 = connect_blocks(&nodes[1], 14);
7436
7437         // Actually revoke tx by claiming a HTLC
7438         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7439         connect_block(&nodes[1], &create_dummy_block(header_114, 42, vec![revoked_txn[0].clone()]));
7440         check_added_monitors!(nodes[1], 1);
7441
7442         // One or more justice tx should have been broadcast, check it
7443         let penalty_1;
7444         let feerate_1;
7445         {
7446                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7447                 assert_eq!(node_txn.len(), 1); // justice tx (broadcasted from ChannelMonitor)
7448                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7449                 assert_eq!(node_txn[0].output.len(), 1);
7450                 check_spends!(node_txn[0], revoked_txn[0]);
7451                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7452                 feerate_1 = fee_1 * 1000 / node_txn[0].weight().to_wu();
7453                 penalty_1 = node_txn[0].txid();
7454                 node_txn.clear();
7455         };
7456
7457         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7458         connect_blocks(&nodes[1], 15);
7459         let mut penalty_2 = penalty_1;
7460         let mut feerate_2 = 0;
7461         {
7462                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7463                 assert_eq!(node_txn.len(), 1);
7464                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7465                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7466                         assert_eq!(node_txn[0].output.len(), 1);
7467                         check_spends!(node_txn[0], revoked_txn[0]);
7468                         penalty_2 = node_txn[0].txid();
7469                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7470                         assert_ne!(penalty_2, penalty_1);
7471                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7472                         feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7473                         // Verify 25% bump heuristic
7474                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7475                         node_txn.clear();
7476                 }
7477         }
7478         assert_ne!(feerate_2, 0);
7479
7480         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7481         connect_blocks(&nodes[1], 1);
7482         let penalty_3;
7483         let mut feerate_3 = 0;
7484         {
7485                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7486                 assert_eq!(node_txn.len(), 1);
7487                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7488                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7489                         assert_eq!(node_txn[0].output.len(), 1);
7490                         check_spends!(node_txn[0], revoked_txn[0]);
7491                         penalty_3 = node_txn[0].txid();
7492                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7493                         assert_ne!(penalty_3, penalty_2);
7494                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7495                         feerate_3 = fee_3 * 1000 / node_txn[0].weight().to_wu();
7496                         // Verify 25% bump heuristic
7497                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7498                         node_txn.clear();
7499                 }
7500         }
7501         assert_ne!(feerate_3, 0);
7502
7503         nodes[1].node.get_and_clear_pending_events();
7504         nodes[1].node.get_and_clear_pending_msg_events();
7505 }
7506
7507 #[test]
7508 fn test_bump_penalty_txn_on_revoked_htlcs() {
7509         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7510         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7511
7512         let mut chanmon_cfgs = create_chanmon_cfgs(2);
7513         chanmon_cfgs[1].keys_manager.disable_revocation_policy_check = true;
7514         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7515         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7516         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7517
7518         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7519         // Lock HTLC in both directions (using a slightly lower CLTV delay to provide timely RBF bumps)
7520         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), 50).with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
7521         let scorer = test_utils::TestScorer::new();
7522         let random_seed_bytes = chanmon_cfgs[1].keys_manager.get_secure_random_bytes();
7523         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7524         let route = get_route(&nodes[0].node.get_our_node_id(), &route_params, &nodes[0].network_graph.read_only(), None,
7525                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7526         let payment_preimage = send_along_route(&nodes[0], route, &[&nodes[1]], 3_000_000).0;
7527         let payment_params = PaymentParameters::from_node_id(nodes[0].node.get_our_node_id(), 50)
7528                 .with_bolt11_features(nodes[0].node.bolt11_invoice_features()).unwrap();
7529         let route_params = RouteParameters::from_payment_params_and_value(payment_params, 3_000_000);
7530         let route = get_route(&nodes[1].node.get_our_node_id(), &route_params, &nodes[1].network_graph.read_only(), None,
7531                 nodes[0].logger, &scorer, &Default::default(), &random_seed_bytes).unwrap();
7532         send_along_route(&nodes[1], route, &[&nodes[0]], 3_000_000);
7533
7534         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7535         assert_eq!(revoked_local_txn[0].input.len(), 1);
7536         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7537
7538         // Revoke local commitment tx
7539         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
7540
7541         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7542         connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![revoked_local_txn[0].clone()]));
7543         check_closed_broadcast!(nodes[1], true);
7544         check_added_monitors!(nodes[1], 1);
7545         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 1000000);
7546         connect_blocks(&nodes[1], 50); // Confirm blocks until the HTLC expires (note CLTV was explicitly 50 above)
7547
7548         let revoked_htlc_txn = {
7549                 let txn = nodes[1].tx_broadcaster.unique_txn_broadcast();
7550                 assert_eq!(txn.len(), 2);
7551
7552                 assert_eq!(txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
7553                 assert_eq!(txn[0].input.len(), 1);
7554                 check_spends!(txn[0], revoked_local_txn[0]);
7555
7556                 assert_eq!(txn[1].input.len(), 1);
7557                 assert_eq!(txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7558                 assert_eq!(txn[1].output.len(), 1);
7559                 check_spends!(txn[1], revoked_local_txn[0]);
7560
7561                 txn
7562         };
7563
7564         // Broadcast set of revoked txn on A
7565         let hash_128 = connect_blocks(&nodes[0], 40);
7566         let block_11 = create_dummy_block(hash_128, 42, vec![revoked_local_txn[0].clone()]);
7567         connect_block(&nodes[0], &block_11);
7568         let block_129 = create_dummy_block(block_11.block_hash(), 42, vec![revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()]);
7569         connect_block(&nodes[0], &block_129);
7570         let events = nodes[0].node.get_and_clear_pending_events();
7571         expect_pending_htlcs_forwardable_from_events!(nodes[0], events[0..1], true);
7572         match events.last().unwrap() {
7573                 Event::ChannelClosed { reason: ClosureReason::CommitmentTxConfirmed, .. } => {}
7574                 _ => panic!("Unexpected event"),
7575         }
7576         let first;
7577         let feerate_1;
7578         let penalty_txn;
7579         {
7580                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7581                 assert_eq!(node_txn.len(), 4); // 3 penalty txn on revoked commitment tx + 1 penalty tnx on revoked HTLC txn
7582                 // Verify claim tx are spending revoked HTLC txn
7583
7584                 // node_txn 0-2 each spend a separate revoked output from revoked_local_txn[0]
7585                 // Note that node_txn[0] and node_txn[1] are bogus - they double spend the revoked_htlc_txn
7586                 // which are included in the same block (they are broadcasted because we scan the
7587                 // transactions linearly and generate claims as we go, they likely should be removed in the
7588                 // future).
7589                 assert_eq!(node_txn[0].input.len(), 1);
7590                 check_spends!(node_txn[0], revoked_local_txn[0]);
7591                 assert_eq!(node_txn[1].input.len(), 1);
7592                 check_spends!(node_txn[1], revoked_local_txn[0]);
7593                 assert_eq!(node_txn[2].input.len(), 1);
7594                 check_spends!(node_txn[2], revoked_local_txn[0]);
7595
7596                 // Each of the three justice transactions claim a separate (single) output of the three
7597                 // available, which we check here:
7598                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[1].input[0].previous_output);
7599                 assert_ne!(node_txn[0].input[0].previous_output, node_txn[2].input[0].previous_output);
7600                 assert_ne!(node_txn[1].input[0].previous_output, node_txn[2].input[0].previous_output);
7601
7602                 assert_eq!(node_txn[0].input[0].previous_output, revoked_htlc_txn[1].input[0].previous_output);
7603                 assert_eq!(node_txn[1].input[0].previous_output, revoked_htlc_txn[0].input[0].previous_output);
7604
7605                 // node_txn[3] spends the revoked outputs from the revoked_htlc_txn (which only have one
7606                 // output, checked above).
7607                 assert_eq!(node_txn[3].input.len(), 2);
7608                 assert_eq!(node_txn[3].output.len(), 1);
7609                 check_spends!(node_txn[3], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7610
7611                 first = node_txn[3].txid();
7612                 // Store both feerates for later comparison
7613                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[3].output[0].value;
7614                 feerate_1 = fee_1 * 1000 / node_txn[3].weight().to_wu();
7615                 penalty_txn = vec![node_txn[2].clone()];
7616                 node_txn.clear();
7617         }
7618
7619         // Connect one more block to see if bumped penalty are issued for HTLC txn
7620         let block_130 = create_dummy_block(block_129.block_hash(), 42, penalty_txn);
7621         connect_block(&nodes[0], &block_130);
7622         let block_131 = create_dummy_block(block_130.block_hash(), 42, Vec::new());
7623         connect_block(&nodes[0], &block_131);
7624
7625         // Few more blocks to confirm penalty txn
7626         connect_blocks(&nodes[0], 4);
7627         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7628         let header_144 = connect_blocks(&nodes[0], 9);
7629         let node_txn = {
7630                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7631                 assert_eq!(node_txn.len(), 1);
7632
7633                 assert_eq!(node_txn[0].input.len(), 2);
7634                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7635                 // Verify bumped tx is different and 25% bump heuristic
7636                 assert_ne!(first, node_txn[0].txid());
7637                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7638                 let feerate_2 = fee_2 * 1000 / node_txn[0].weight().to_wu();
7639                 assert!(feerate_2 * 100 > feerate_1 * 125);
7640                 let txn = vec![node_txn[0].clone()];
7641                 node_txn.clear();
7642                 txn
7643         };
7644         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7645         connect_block(&nodes[0], &create_dummy_block(header_144, 42, node_txn));
7646         connect_blocks(&nodes[0], 20);
7647         {
7648                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7649                 // We verify than no new transaction has been broadcast because previously
7650                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7651                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7652                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7653                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7654                 // up bumped justice generation.
7655                 assert_eq!(node_txn.len(), 0);
7656                 node_txn.clear();
7657         }
7658         check_closed_broadcast!(nodes[0], true);
7659         check_added_monitors!(nodes[0], 1);
7660 }
7661
7662 #[test]
7663 fn test_bump_penalty_txn_on_remote_commitment() {
7664         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7665         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7666
7667         // Create 2 HTLCs
7668         // Provide preimage for one
7669         // Check aggregation
7670
7671         let chanmon_cfgs = create_chanmon_cfgs(2);
7672         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7673         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7674         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7675
7676         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7677         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 3_000_000);
7678         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7679
7680         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7681         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7682         assert_eq!(remote_txn[0].output.len(), 4);
7683         assert_eq!(remote_txn[0].input.len(), 1);
7684         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7685
7686         // Claim a HTLC without revocation (provide B monitor with preimage)
7687         nodes[1].node.claim_funds(payment_preimage);
7688         expect_payment_claimed!(nodes[1], payment_hash, 3_000_000);
7689         mine_transaction(&nodes[1], &remote_txn[0]);
7690         check_added_monitors!(nodes[1], 2);
7691         connect_blocks(&nodes[1], TEST_FINAL_CLTV); // Confirm blocks until the HTLC expires
7692
7693         // One or more claim tx should have been broadcast, check it
7694         let timeout;
7695         let preimage;
7696         let preimage_bump;
7697         let feerate_timeout;
7698         let feerate_preimage;
7699         {
7700                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7701                 // 3 transactions including:
7702                 //   preimage and timeout sweeps from remote commitment + preimage sweep bump
7703                 assert_eq!(node_txn.len(), 3);
7704                 assert_eq!(node_txn[0].input.len(), 1);
7705                 assert_eq!(node_txn[1].input.len(), 1);
7706                 assert_eq!(node_txn[2].input.len(), 1);
7707                 check_spends!(node_txn[0], remote_txn[0]);
7708                 check_spends!(node_txn[1], remote_txn[0]);
7709                 check_spends!(node_txn[2], remote_txn[0]);
7710
7711                 preimage = node_txn[0].txid();
7712                 let index = node_txn[0].input[0].previous_output.vout;
7713                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7714                 feerate_preimage = fee * 1000 / node_txn[0].weight().to_wu();
7715
7716                 let (preimage_bump_tx, timeout_tx) = if node_txn[2].input[0].previous_output == node_txn[0].input[0].previous_output {
7717                         (node_txn[2].clone(), node_txn[1].clone())
7718                 } else {
7719                         (node_txn[1].clone(), node_txn[2].clone())
7720                 };
7721
7722                 preimage_bump = preimage_bump_tx;
7723                 check_spends!(preimage_bump, remote_txn[0]);
7724                 assert_eq!(node_txn[0].input[0].previous_output, preimage_bump.input[0].previous_output);
7725
7726                 timeout = timeout_tx.txid();
7727                 let index = timeout_tx.input[0].previous_output.vout;
7728                 let fee = remote_txn[0].output[index as usize].value - timeout_tx.output[0].value;
7729                 feerate_timeout = fee * 1000 / timeout_tx.weight().to_wu();
7730
7731                 node_txn.clear();
7732         };
7733         assert_ne!(feerate_timeout, 0);
7734         assert_ne!(feerate_preimage, 0);
7735
7736         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7737         connect_blocks(&nodes[1], 1);
7738         {
7739                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7740                 assert_eq!(node_txn.len(), 1);
7741                 assert_eq!(node_txn[0].input.len(), 1);
7742                 assert_eq!(preimage_bump.input.len(), 1);
7743                 check_spends!(node_txn[0], remote_txn[0]);
7744                 check_spends!(preimage_bump, remote_txn[0]);
7745
7746                 let index = preimage_bump.input[0].previous_output.vout;
7747                 let fee = remote_txn[0].output[index as usize].value - preimage_bump.output[0].value;
7748                 let new_feerate = fee * 1000 / preimage_bump.weight().to_wu();
7749                 assert!(new_feerate * 100 > feerate_timeout * 125);
7750                 assert_ne!(timeout, preimage_bump.txid());
7751
7752                 let index = node_txn[0].input[0].previous_output.vout;
7753                 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7754                 let new_feerate = fee * 1000 / node_txn[0].weight().to_wu();
7755                 assert!(new_feerate * 100 > feerate_preimage * 125);
7756                 assert_ne!(preimage, node_txn[0].txid());
7757
7758                 node_txn.clear();
7759         }
7760
7761         nodes[1].node.get_and_clear_pending_events();
7762         nodes[1].node.get_and_clear_pending_msg_events();
7763 }
7764
7765 #[test]
7766 fn test_counterparty_raa_skip_no_crash() {
7767         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7768         // commitment transaction, we would have happily carried on and provided them the next
7769         // commitment transaction based on one RAA forward. This would probably eventually have led to
7770         // channel closure, but it would not have resulted in funds loss. Still, our
7771         // TestChannelSigner would have panicked as it doesn't like jumps into the future. Here, we
7772         // check simply that the channel is closed in response to such an RAA, but don't check whether
7773         // we decide to punish our counterparty for revoking their funds (as we don't currently
7774         // implement that).
7775         let chanmon_cfgs = create_chanmon_cfgs(2);
7776         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7777         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7778         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7779         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
7780
7781         let per_commitment_secret;
7782         let next_per_commitment_point;
7783         {
7784                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
7785                 let mut guard = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
7786                 let keys = guard.channel_by_id.get_mut(&channel_id).map(
7787                         |phase| if let ChannelPhase::Funded(chan) = phase { Some(chan) } else { None }
7788                 ).flatten().unwrap().get_signer();
7789
7790                 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7791
7792                 // Make signer believe we got a counterparty signature, so that it allows the revocation
7793                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7794                 per_commitment_secret = keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER);
7795
7796                 // Must revoke without gaps
7797                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7798                 keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 1);
7799
7800                 keys.as_ecdsa().unwrap().get_enforcement_state().last_holder_commitment -= 1;
7801                 next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7802                         &SecretKey::from_slice(&keys.as_ref().release_commitment_secret(INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7803         }
7804
7805         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7806                 &msgs::RevokeAndACK {
7807                         channel_id,
7808                         per_commitment_secret,
7809                         next_per_commitment_point,
7810                         #[cfg(taproot)]
7811                         next_local_nonce: None,
7812                 });
7813         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7814         check_added_monitors!(nodes[1], 1);
7815         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: "Received an unexpected revoke_and_ack".to_string() }
7816                 , [nodes[0].node.get_our_node_id()], 100000);
7817 }
7818
7819 #[test]
7820 fn test_bump_txn_sanitize_tracking_maps() {
7821         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7822         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7823
7824         let chanmon_cfgs = create_chanmon_cfgs(2);
7825         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7826         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7827         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7828
7829         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000);
7830         // Lock HTLC in both directions
7831         let (payment_preimage_1, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000);
7832         let (_, payment_hash_2, ..) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000);
7833
7834         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7835         assert_eq!(revoked_local_txn[0].input.len(), 1);
7836         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7837
7838         // Revoke local commitment tx
7839         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
7840
7841         // Broadcast set of revoked txn on A
7842         connect_blocks(&nodes[0], TEST_FINAL_CLTV + 2 - CHAN_CONFIRM_DEPTH);
7843         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[0], vec![HTLCDestination::FailedPayment { payment_hash: payment_hash_2 }]);
7844         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
7845
7846         mine_transaction(&nodes[0], &revoked_local_txn[0]);
7847         check_closed_broadcast!(nodes[0], true);
7848         check_added_monitors!(nodes[0], 1);
7849         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 1000000);
7850         let penalty_txn = {
7851                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7852                 assert_eq!(node_txn.len(), 3); //ChannelMonitor: justice txn * 3
7853                 check_spends!(node_txn[0], revoked_local_txn[0]);
7854                 check_spends!(node_txn[1], revoked_local_txn[0]);
7855                 check_spends!(node_txn[2], revoked_local_txn[0]);
7856                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7857                 node_txn.clear();
7858                 penalty_txn
7859         };
7860         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, penalty_txn));
7861         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
7862         {
7863                 let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(OutPoint { txid: chan.3.txid(), index: 0 }).unwrap();
7864                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.pending_claim_requests.is_empty());
7865                 assert!(monitor.inner.lock().unwrap().onchain_tx_handler.claimable_outpoints.is_empty());
7866         }
7867 }
7868
7869 #[test]
7870 fn test_channel_conf_timeout() {
7871         // Tests that, for inbound channels, we give up on them if the funding transaction does not
7872         // confirm within 2016 blocks, as recommended by BOLT 2.
7873         let chanmon_cfgs = create_chanmon_cfgs(2);
7874         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7875         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7876         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7877
7878         let _funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 100_000);
7879
7880         // The outbound node should wait forever for confirmation:
7881         // This matches `channel::FUNDING_CONF_DEADLINE_BLOCKS` and BOLT 2's suggested timeout, thus is
7882         // copied here instead of directly referencing the constant.
7883         connect_blocks(&nodes[0], 2016);
7884         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7885
7886         // The inbound node should fail the channel after exactly 2016 blocks
7887         connect_blocks(&nodes[1], 2015);
7888         check_added_monitors!(nodes[1], 0);
7889         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7890
7891         connect_blocks(&nodes[1], 1);
7892         check_added_monitors!(nodes[1], 1);
7893         check_closed_event!(nodes[1], 1, ClosureReason::FundingTimedOut, [nodes[0].node.get_our_node_id()], 1000000);
7894         let close_ev = nodes[1].node.get_and_clear_pending_msg_events();
7895         assert_eq!(close_ev.len(), 1);
7896         match close_ev[0] {
7897                 MessageSendEvent::HandleError { action: ErrorAction::DisconnectPeer { ref msg }, ref node_id } => {
7898                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
7899                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because funding transaction failed to confirm within 2016 blocks");
7900                 },
7901                 _ => panic!("Unexpected event"),
7902         }
7903 }
7904
7905 #[test]
7906 fn test_override_channel_config() {
7907         let chanmon_cfgs = create_chanmon_cfgs(2);
7908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7911
7912         // Node0 initiates a channel to node1 using the override config.
7913         let mut override_config = UserConfig::default();
7914         override_config.channel_handshake_config.our_to_self_delay = 200;
7915
7916         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(override_config)).unwrap();
7917
7918         // Assert the channel created by node0 is using the override config.
7919         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7920         assert_eq!(res.channel_flags, 0);
7921         assert_eq!(res.to_self_delay, 200);
7922 }
7923
7924 #[test]
7925 fn test_override_0msat_htlc_minimum() {
7926         let mut zero_config = UserConfig::default();
7927         zero_config.channel_handshake_config.our_htlc_minimum_msat = 0;
7928         let chanmon_cfgs = create_chanmon_cfgs(2);
7929         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7930         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7931         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7932
7933         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, None, Some(zero_config)).unwrap();
7934         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7935         assert_eq!(res.htlc_minimum_msat, 1);
7936
7937         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
7938         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7939         assert_eq!(res.htlc_minimum_msat, 1);
7940 }
7941
7942 #[test]
7943 fn test_channel_update_has_correct_htlc_maximum_msat() {
7944         // Tests that the `ChannelUpdate` message has the correct values for `htlc_maximum_msat` set.
7945         // Bolt 7 specifies that if present `htlc_maximum_msat`:
7946         // 1. MUST be set to less than or equal to the channel capacity. In LDK, this is capped to
7947         // 90% of the `channel_value`.
7948         // 2. MUST be set to less than or equal to the `max_htlc_value_in_flight_msat` received from the peer.
7949
7950         let mut config_30_percent = UserConfig::default();
7951         config_30_percent.channel_handshake_config.announced_channel = true;
7952         config_30_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 30;
7953         let mut config_50_percent = UserConfig::default();
7954         config_50_percent.channel_handshake_config.announced_channel = true;
7955         config_50_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 50;
7956         let mut config_95_percent = UserConfig::default();
7957         config_95_percent.channel_handshake_config.announced_channel = true;
7958         config_95_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 95;
7959         let mut config_100_percent = UserConfig::default();
7960         config_100_percent.channel_handshake_config.announced_channel = true;
7961         config_100_percent.channel_handshake_config.max_inbound_htlc_value_in_flight_percent_of_channel = 100;
7962
7963         let chanmon_cfgs = create_chanmon_cfgs(4);
7964         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7965         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[Some(config_30_percent), Some(config_50_percent), Some(config_95_percent), Some(config_100_percent)]);
7966         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7967
7968         let channel_value_satoshis = 100000;
7969         let channel_value_msat = channel_value_satoshis * 1000;
7970         let channel_value_30_percent_msat = (channel_value_msat as f64 * 0.3) as u64;
7971         let channel_value_50_percent_msat = (channel_value_msat as f64 * 0.5) as u64;
7972         let channel_value_90_percent_msat = (channel_value_msat as f64 * 0.9) as u64;
7973
7974         let (node_0_chan_update, node_1_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value_satoshis, 10001);
7975         let (node_2_chan_update, node_3_chan_update, _, _)  = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, channel_value_satoshis, 10001);
7976
7977         // Assert that `node[0]`'s `ChannelUpdate` is capped at 50 percent of the `channel_value`, as
7978         // that's the value of `node[1]`'s `holder_max_htlc_value_in_flight_msat`.
7979         assert_eq!(node_0_chan_update.contents.htlc_maximum_msat, channel_value_50_percent_msat);
7980         // Assert that `node[1]`'s `ChannelUpdate` is capped at 30 percent of the `channel_value`, as
7981         // that's the value of `node[0]`'s `holder_max_htlc_value_in_flight_msat`.
7982         assert_eq!(node_1_chan_update.contents.htlc_maximum_msat, channel_value_30_percent_msat);
7983
7984         // Assert that `node[2]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7985         // the value of `node[3]`'s `holder_max_htlc_value_in_flight_msat` (100%), exceeds 90% of the
7986         // `channel_value`.
7987         assert_eq!(node_2_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7988         // Assert that `node[3]`'s `ChannelUpdate` is capped at 90 percent of the `channel_value`, as
7989         // the value of `node[2]`'s `holder_max_htlc_value_in_flight_msat` (95%), exceeds 90% of the
7990         // `channel_value`.
7991         assert_eq!(node_3_chan_update.contents.htlc_maximum_msat, channel_value_90_percent_msat);
7992 }
7993
7994 #[test]
7995 fn test_manually_accept_inbound_channel_request() {
7996         let mut manually_accept_conf = UserConfig::default();
7997         manually_accept_conf.manually_accept_inbound_channels = true;
7998         let chanmon_cfgs = create_chanmon_cfgs(2);
7999         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8000         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8001         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8002
8003         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8004         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8005
8006         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8007
8008         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8009         // accepting the inbound channel request.
8010         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8011
8012         let events = nodes[1].node.get_and_clear_pending_events();
8013         match events[0] {
8014                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8015                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 23).unwrap();
8016                 }
8017                 _ => panic!("Unexpected event"),
8018         }
8019
8020         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8021         assert_eq!(accept_msg_ev.len(), 1);
8022
8023         match accept_msg_ev[0] {
8024                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8025                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8026                 }
8027                 _ => panic!("Unexpected event"),
8028         }
8029
8030         nodes[1].node.force_close_broadcasting_latest_txn(&temp_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8031
8032         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8033         assert_eq!(close_msg_ev.len(), 1);
8034
8035         let events = nodes[1].node.get_and_clear_pending_events();
8036         match events[0] {
8037                 Event::ChannelClosed { user_channel_id, .. } => {
8038                         assert_eq!(user_channel_id, 23);
8039                 }
8040                 _ => panic!("Unexpected event"),
8041         }
8042 }
8043
8044 #[test]
8045 fn test_manually_reject_inbound_channel_request() {
8046         let mut manually_accept_conf = UserConfig::default();
8047         manually_accept_conf.manually_accept_inbound_channels = true;
8048         let chanmon_cfgs = create_chanmon_cfgs(2);
8049         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8050         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8051         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8052
8053         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8054         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8055
8056         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8057
8058         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8059         // rejecting the inbound channel request.
8060         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8061
8062         let events = nodes[1].node.get_and_clear_pending_events();
8063         match events[0] {
8064                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8065                         nodes[1].node.force_close_broadcasting_latest_txn(&temporary_channel_id, &nodes[0].node.get_our_node_id()).unwrap();
8066                 }
8067                 _ => panic!("Unexpected event"),
8068         }
8069
8070         let close_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8071         assert_eq!(close_msg_ev.len(), 1);
8072
8073         match close_msg_ev[0] {
8074                 MessageSendEvent::HandleError { ref node_id, .. } => {
8075                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8076                 }
8077                 _ => panic!("Unexpected event"),
8078         }
8079
8080         // There should be no more events to process, as the channel was never opened.
8081         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
8082 }
8083
8084 #[test]
8085 fn test_can_not_accept_inbound_channel_twice() {
8086         let mut manually_accept_conf = UserConfig::default();
8087         manually_accept_conf.manually_accept_inbound_channels = true;
8088         let chanmon_cfgs = create_chanmon_cfgs(2);
8089         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8090         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(manually_accept_conf.clone())]);
8091         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8092
8093         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, Some(manually_accept_conf)).unwrap();
8094         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8095
8096         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &res);
8097
8098         // Assert that `nodes[1]` has no `MessageSendEvent::SendAcceptChannel` in `msg_events` before
8099         // accepting the inbound channel request.
8100         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
8101
8102         let events = nodes[1].node.get_and_clear_pending_events();
8103         match events[0] {
8104                 Event::OpenChannelRequest { temporary_channel_id, .. } => {
8105                         nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0).unwrap();
8106                         let api_res = nodes[1].node.accept_inbound_channel(&temporary_channel_id, &nodes[0].node.get_our_node_id(), 0);
8107                         match api_res {
8108                                 Err(APIError::APIMisuseError { err }) => {
8109                                         assert_eq!(err, "No such channel awaiting to be accepted.");
8110                                 },
8111                                 Ok(_) => panic!("Channel shouldn't be possible to be accepted twice"),
8112                                 Err(e) => panic!("Unexpected Error {:?}", e),
8113                         }
8114                 }
8115                 _ => panic!("Unexpected event"),
8116         }
8117
8118         // Ensure that the channel wasn't closed after attempting to accept it twice.
8119         let accept_msg_ev = nodes[1].node.get_and_clear_pending_msg_events();
8120         assert_eq!(accept_msg_ev.len(), 1);
8121
8122         match accept_msg_ev[0] {
8123                 MessageSendEvent::SendAcceptChannel { ref node_id, .. } => {
8124                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8125                 }
8126                 _ => panic!("Unexpected event"),
8127         }
8128 }
8129
8130 #[test]
8131 fn test_can_not_accept_unknown_inbound_channel() {
8132         let chanmon_cfg = create_chanmon_cfgs(2);
8133         let node_cfg = create_node_cfgs(2, &chanmon_cfg);
8134         let node_chanmgr = create_node_chanmgrs(2, &node_cfg, &[None, None]);
8135         let nodes = create_network(2, &node_cfg, &node_chanmgr);
8136
8137         let unknown_channel_id = ChannelId::new_zero();
8138         let api_res = nodes[0].node.accept_inbound_channel(&unknown_channel_id, &nodes[1].node.get_our_node_id(), 0);
8139         match api_res {
8140                 Err(APIError::APIMisuseError { err }) => {
8141                         assert_eq!(err, "No such channel awaiting to be accepted.");
8142                 },
8143                 Ok(_) => panic!("It shouldn't be possible to accept an unkown channel"),
8144                 Err(e) => panic!("Unexpected Error: {:?}", e),
8145         }
8146 }
8147
8148 #[test]
8149 fn test_onion_value_mpp_set_calculation() {
8150         // Test that we use the onion value `amt_to_forward` when
8151         // calculating whether we've reached the `total_msat` of an MPP
8152         // by having a routing node forward more than `amt_to_forward`
8153         // and checking that the receiving node doesn't generate
8154         // a PaymentClaimable event too early
8155         let node_count = 4;
8156         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8157         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8158         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8159         let mut nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8160
8161         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8162         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8163         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8164         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8165
8166         let total_msat = 100_000;
8167         let expected_paths: &[&[&Node]] = &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]];
8168         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], total_msat);
8169         let sample_path = route.paths.pop().unwrap();
8170
8171         let mut path_1 = sample_path.clone();
8172         path_1.hops[0].pubkey = nodes[1].node.get_our_node_id();
8173         path_1.hops[0].short_channel_id = chan_1_id;
8174         path_1.hops[1].pubkey = nodes[3].node.get_our_node_id();
8175         path_1.hops[1].short_channel_id = chan_3_id;
8176         path_1.hops[1].fee_msat = 100_000;
8177         route.paths.push(path_1);
8178
8179         let mut path_2 = sample_path.clone();
8180         path_2.hops[0].pubkey = nodes[2].node.get_our_node_id();
8181         path_2.hops[0].short_channel_id = chan_2_id;
8182         path_2.hops[1].pubkey = nodes[3].node.get_our_node_id();
8183         path_2.hops[1].short_channel_id = chan_4_id;
8184         path_2.hops[1].fee_msat = 1_000;
8185         route.paths.push(path_2);
8186
8187         // Send payment
8188         let payment_id = PaymentId(nodes[0].keys_manager.backing.get_secure_random_bytes());
8189         let onion_session_privs = nodes[0].node.test_add_new_pending_payment(our_payment_hash,
8190                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8191         nodes[0].node.test_send_payment_internal(&route, our_payment_hash,
8192                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8193         check_added_monitors!(nodes[0], expected_paths.len());
8194
8195         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8196         assert_eq!(events.len(), expected_paths.len());
8197
8198         // First path
8199         let ev = remove_first_msg_event_to_node(&expected_paths[0][0].node.get_our_node_id(), &mut events);
8200         let mut payment_event = SendEvent::from_event(ev);
8201         let mut prev_node = &nodes[0];
8202
8203         for (idx, &node) in expected_paths[0].iter().enumerate() {
8204                 assert_eq!(node.node.get_our_node_id(), payment_event.node_id);
8205
8206                 if idx == 0 { // routing node
8207                         let session_priv = [3; 32];
8208                         let height = nodes[0].best_block_info().1;
8209                         let session_priv = SecretKey::from_slice(&session_priv).unwrap();
8210                         let mut onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
8211                         let (mut onion_payloads, _, _) = onion_utils::build_onion_payloads(&route.paths[0], 100_000,
8212                                 RecipientOnionFields::secret_only(our_payment_secret), height + 1, &None).unwrap();
8213                         // Edit amt_to_forward to simulate the sender having set
8214                         // the final amount and the routing node taking less fee
8215                         if let msgs::OutboundOnionPayload::Receive { ref mut amt_msat, .. } = onion_payloads[1] {
8216                                 *amt_msat = 99_000;
8217                         } else { panic!() }
8218                         let new_onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash).unwrap();
8219                         payment_event.msgs[0].onion_routing_packet = new_onion_packet;
8220                 }
8221
8222                 node.node.handle_update_add_htlc(&prev_node.node.get_our_node_id(), &payment_event.msgs[0]);
8223                 check_added_monitors!(node, 0);
8224                 commitment_signed_dance!(node, prev_node, payment_event.commitment_msg, false);
8225                 expect_pending_htlcs_forwardable!(node);
8226
8227                 if idx == 0 {
8228                         let mut events_2 = node.node.get_and_clear_pending_msg_events();
8229                         assert_eq!(events_2.len(), 1);
8230                         check_added_monitors!(node, 1);
8231                         payment_event = SendEvent::from_event(events_2.remove(0));
8232                         assert_eq!(payment_event.msgs.len(), 1);
8233                 } else {
8234                         let events_2 = node.node.get_and_clear_pending_events();
8235                         assert!(events_2.is_empty());
8236                 }
8237
8238                 prev_node = node;
8239         }
8240
8241         // Second path
8242         let ev = remove_first_msg_event_to_node(&expected_paths[1][0].node.get_our_node_id(), &mut events);
8243         pass_along_path(&nodes[0], expected_paths[1], 101_000, our_payment_hash.clone(), Some(our_payment_secret), ev, true, None);
8244
8245         claim_payment_along_route(&nodes[0], expected_paths, false, our_payment_preimage);
8246 }
8247
8248 fn do_test_overshoot_mpp(msat_amounts: &[u64], total_msat: u64) {
8249
8250         let routing_node_count = msat_amounts.len();
8251         let node_count = routing_node_count + 2;
8252
8253         let chanmon_cfgs = create_chanmon_cfgs(node_count);
8254         let node_cfgs = create_node_cfgs(node_count, &chanmon_cfgs);
8255         let node_chanmgrs = create_node_chanmgrs(node_count, &node_cfgs, &vec![None; node_count]);
8256         let nodes = create_network(node_count, &node_cfgs, &node_chanmgrs);
8257
8258         let src_idx = 0;
8259         let dst_idx = 1;
8260
8261         // Create channels for each amount
8262         let mut expected_paths = Vec::with_capacity(routing_node_count);
8263         let mut src_chan_ids = Vec::with_capacity(routing_node_count);
8264         let mut dst_chan_ids = Vec::with_capacity(routing_node_count);
8265         for i in 0..routing_node_count {
8266                 let routing_node = 2 + i;
8267                 let src_chan_id = create_announced_chan_between_nodes(&nodes, src_idx, routing_node).0.contents.short_channel_id;
8268                 src_chan_ids.push(src_chan_id);
8269                 let dst_chan_id = create_announced_chan_between_nodes(&nodes, routing_node, dst_idx).0.contents.short_channel_id;
8270                 dst_chan_ids.push(dst_chan_id);
8271                 let path = vec![&nodes[routing_node], &nodes[dst_idx]];
8272                 expected_paths.push(path);
8273         }
8274         let expected_paths: Vec<&[&Node]> = expected_paths.iter().map(|route| route.as_slice()).collect();
8275
8276         // Create a route for each amount
8277         let example_amount = 100000;
8278         let (mut route, our_payment_hash, our_payment_preimage, our_payment_secret) = get_route_and_payment_hash!(&nodes[src_idx], nodes[dst_idx], example_amount);
8279         let sample_path = route.paths.pop().unwrap();
8280         for i in 0..routing_node_count {
8281                 let routing_node = 2 + i;
8282                 let mut path = sample_path.clone();
8283                 path.hops[0].pubkey = nodes[routing_node].node.get_our_node_id();
8284                 path.hops[0].short_channel_id = src_chan_ids[i];
8285                 path.hops[1].pubkey = nodes[dst_idx].node.get_our_node_id();
8286                 path.hops[1].short_channel_id = dst_chan_ids[i];
8287                 path.hops[1].fee_msat = msat_amounts[i];
8288                 route.paths.push(path);
8289         }
8290
8291         // Send payment with manually set total_msat
8292         let payment_id = PaymentId(nodes[src_idx].keys_manager.backing.get_secure_random_bytes());
8293         let onion_session_privs = nodes[src_idx].node.test_add_new_pending_payment(our_payment_hash,
8294                 RecipientOnionFields::secret_only(our_payment_secret), payment_id, &route).unwrap();
8295         nodes[src_idx].node.test_send_payment_internal(&route, our_payment_hash,
8296                 RecipientOnionFields::secret_only(our_payment_secret), None, payment_id, Some(total_msat), onion_session_privs).unwrap();
8297         check_added_monitors!(nodes[src_idx], expected_paths.len());
8298
8299         let mut events = nodes[src_idx].node.get_and_clear_pending_msg_events();
8300         assert_eq!(events.len(), expected_paths.len());
8301         let mut amount_received = 0;
8302         for (path_idx, expected_path) in expected_paths.iter().enumerate() {
8303                 let ev = remove_first_msg_event_to_node(&expected_path[0].node.get_our_node_id(), &mut events);
8304
8305                 let current_path_amount = msat_amounts[path_idx];
8306                 amount_received += current_path_amount;
8307                 let became_claimable_now = amount_received >= total_msat && amount_received - current_path_amount < total_msat;
8308                 pass_along_path(&nodes[src_idx], expected_path, amount_received, our_payment_hash.clone(), Some(our_payment_secret), ev, became_claimable_now, None);
8309         }
8310
8311         claim_payment_along_route(&nodes[src_idx], &expected_paths, false, our_payment_preimage);
8312 }
8313
8314 #[test]
8315 fn test_overshoot_mpp() {
8316         do_test_overshoot_mpp(&[100_000, 101_000], 200_000);
8317         do_test_overshoot_mpp(&[100_000, 10_000, 100_000], 200_000);
8318 }
8319
8320 #[test]
8321 fn test_simple_mpp() {
8322         // Simple test of sending a multi-path payment.
8323         let chanmon_cfgs = create_chanmon_cfgs(4);
8324         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
8325         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
8326         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
8327
8328         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8329         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2).0.contents.short_channel_id;
8330         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3).0.contents.short_channel_id;
8331         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3).0.contents.short_channel_id;
8332
8333         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(&nodes[0], nodes[3], 100000);
8334         let path = route.paths[0].clone();
8335         route.paths.push(path);
8336         route.paths[0].hops[0].pubkey = nodes[1].node.get_our_node_id();
8337         route.paths[0].hops[0].short_channel_id = chan_1_id;
8338         route.paths[0].hops[1].short_channel_id = chan_3_id;
8339         route.paths[1].hops[0].pubkey = nodes[2].node.get_our_node_id();
8340         route.paths[1].hops[0].short_channel_id = chan_2_id;
8341         route.paths[1].hops[1].short_channel_id = chan_4_id;
8342         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, payment_secret);
8343         claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage);
8344 }
8345
8346 #[test]
8347 fn test_preimage_storage() {
8348         // Simple test of payment preimage storage allowing no client-side storage to claim payments
8349         let chanmon_cfgs = create_chanmon_cfgs(2);
8350         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8351         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8352         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8353
8354         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8355
8356         {
8357                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 7200, None).unwrap();
8358                 let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8359                 nodes[0].node.send_payment_with_route(&route, payment_hash,
8360                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8361                 check_added_monitors!(nodes[0], 1);
8362                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8363                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
8364                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8365                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8366         }
8367         // Note that after leaving the above scope we have no knowledge of any arguments or return
8368         // values from previous calls.
8369         expect_pending_htlcs_forwardable!(nodes[1]);
8370         let events = nodes[1].node.get_and_clear_pending_events();
8371         assert_eq!(events.len(), 1);
8372         match events[0] {
8373                 Event::PaymentClaimable { ref purpose, .. } => {
8374                         match &purpose {
8375                                 PaymentPurpose::InvoicePayment { payment_preimage, .. } => {
8376                                         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage.unwrap());
8377                                 },
8378                                 _ => panic!("expected PaymentPurpose::InvoicePayment")
8379                         }
8380                 },
8381                 _ => panic!("Unexpected event"),
8382         }
8383 }
8384
8385 #[test]
8386 fn test_bad_secret_hash() {
8387         // Simple test of unregistered payment hash/invalid payment secret handling
8388         let chanmon_cfgs = create_chanmon_cfgs(2);
8389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8391         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8392
8393         create_announced_chan_between_nodes(&nodes, 0, 1).0.contents.short_channel_id;
8394
8395         let random_payment_hash = PaymentHash([42; 32]);
8396         let random_payment_secret = PaymentSecret([43; 32]);
8397         let (our_payment_hash, our_payment_secret) = nodes[1].node.create_inbound_payment(Some(100_000), 2, None).unwrap();
8398         let (route, _, _, _) = get_route_and_payment_hash!(nodes[0], nodes[1], 100_000);
8399
8400         // All the below cases should end up being handled exactly identically, so we macro the
8401         // resulting events.
8402         macro_rules! handle_unknown_invalid_payment_data {
8403                 ($payment_hash: expr) => {
8404                         check_added_monitors!(nodes[0], 1);
8405                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
8406                         let payment_event = SendEvent::from_event(events.pop().unwrap());
8407                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
8408                         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
8409
8410                         // We have to forward pending HTLCs once to process the receipt of the HTLC and then
8411                         // again to process the pending backwards-failure of the HTLC
8412                         expect_pending_htlcs_forwardable!(nodes[1]);
8413                         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment{ payment_hash: $payment_hash }]);
8414                         check_added_monitors!(nodes[1], 1);
8415
8416                         // We should fail the payment back
8417                         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
8418                         match events.pop().unwrap() {
8419                                 MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate { update_fail_htlcs, commitment_signed, .. } } => {
8420                                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
8421                                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false);
8422                                 },
8423                                 _ => panic!("Unexpected event"),
8424                         }
8425                 }
8426         }
8427
8428         let expected_error_code = 0x4000|15; // incorrect_or_unknown_payment_details
8429         // Error data is the HTLC value (100,000) and current block height
8430         let expected_error_data = [0, 0, 0, 0, 0, 1, 0x86, 0xa0, 0, 0, 0, CHAN_CONFIRM_DEPTH as u8];
8431
8432         // Send a payment with the right payment hash but the wrong payment secret
8433         nodes[0].node.send_payment_with_route(&route, our_payment_hash,
8434                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
8435         handle_unknown_invalid_payment_data!(our_payment_hash);
8436         expect_payment_failed!(nodes[0], our_payment_hash, true, expected_error_code, expected_error_data);
8437
8438         // Send a payment with a random payment hash, but the right payment secret
8439         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8440                 RecipientOnionFields::secret_only(our_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8441         handle_unknown_invalid_payment_data!(random_payment_hash);
8442         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8443
8444         // Send a payment with a random payment hash and random payment secret
8445         nodes[0].node.send_payment_with_route(&route, random_payment_hash,
8446                 RecipientOnionFields::secret_only(random_payment_secret), PaymentId(random_payment_hash.0)).unwrap();
8447         handle_unknown_invalid_payment_data!(random_payment_hash);
8448         expect_payment_failed!(nodes[0], random_payment_hash, true, expected_error_code, expected_error_data);
8449 }
8450
8451 #[test]
8452 fn test_update_err_monitor_lockdown() {
8453         // Our monitor will lock update of local commitment transaction if a broadcastion condition
8454         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
8455         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateStatus
8456         // error.
8457         //
8458         // This scenario may happen in a watchtower setup, where watchtower process a block height
8459         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
8460         // commitment at same time.
8461
8462         let chanmon_cfgs = create_chanmon_cfgs(2);
8463         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8464         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8465         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8466
8467         // Create some initial channel
8468         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8469         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8470
8471         // Rebalance the network to generate htlc in the two directions
8472         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8473
8474         // Route a HTLC from node 0 to node 1 (but don't settle)
8475         let (preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 9_000_000);
8476
8477         // Copy ChainMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
8478         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8479         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
8480         let persister = test_utils::TestPersister::new();
8481         let watchtower = {
8482                 let new_monitor = {
8483                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8484                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8485                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8486                         assert!(new_monitor == *monitor);
8487                         new_monitor
8488                 };
8489                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8490                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8491                 watchtower
8492         };
8493         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8494         // Make the tx_broadcaster aware of enough blocks that it doesn't think we're violating
8495         // transaction lock time requirements here.
8496         chanmon_cfgs[0].tx_broadcaster.blocks.lock().unwrap().resize(200, (block.clone(), 200));
8497         watchtower.chain_monitor.block_connected(&block, 200);
8498
8499         // Try to update ChannelMonitor
8500         nodes[1].node.claim_funds(preimage);
8501         check_added_monitors!(nodes[1], 1);
8502         expect_payment_claimed!(nodes[1], payment_hash, 9_000_000);
8503
8504         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8505         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
8506         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
8507         {
8508                 let mut node_0_per_peer_lock;
8509                 let mut node_0_peer_state_lock;
8510                 if let ChannelPhase::Funded(ref mut channel) = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2) {
8511                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8512                                 assert_eq!(watchtower.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8513                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8514                         } else { assert!(false); }
8515                 } else {
8516                         assert!(false);
8517                 }
8518         }
8519         // Our local monitor is in-sync and hasn't processed yet timeout
8520         check_added_monitors!(nodes[0], 1);
8521         let events = nodes[0].node.get_and_clear_pending_events();
8522         assert_eq!(events.len(), 1);
8523 }
8524
8525 #[test]
8526 fn test_concurrent_monitor_claim() {
8527         // Watchtower A receives block, broadcasts state N, then channel receives new state N+1,
8528         // sending it to both watchtowers, Bob accepts N+1, then receives block and broadcasts
8529         // the latest state N+1, Alice rejects state N+1, but Bob has already broadcast it,
8530         // state N+1 confirms. Alice claims output from state N+1.
8531
8532         let chanmon_cfgs = create_chanmon_cfgs(2);
8533         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8534         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8535         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8536
8537         // Create some initial channel
8538         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
8539         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
8540
8541         // Rebalance the network to generate htlc in the two directions
8542         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000);
8543
8544         // Route a HTLC from node 0 to node 1 (but don't settle)
8545         route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
8546
8547         // Copy ChainMonitor to simulate watchtower Alice and update block height her ChannelMonitor timeout HTLC onchain
8548         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8549         let logger = test_utils::TestLogger::with_id(format!("node {}", "Alice"));
8550         let persister = test_utils::TestPersister::new();
8551         let alice_broadcaster = test_utils::TestBroadcaster::with_blocks(
8552                 Arc::new(Mutex::new(nodes[0].blocks.lock().unwrap().clone())),
8553         );
8554         let watchtower_alice = {
8555                 let new_monitor = {
8556                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8557                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8558                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8559                         assert!(new_monitor == *monitor);
8560                         new_monitor
8561                 };
8562                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &alice_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8563                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8564                 watchtower
8565         };
8566         let block = create_dummy_block(BlockHash::all_zeros(), 42, Vec::new());
8567         // Make Alice aware of enough blocks that it doesn't think we're violating transaction lock time
8568         // requirements here.
8569         const HTLC_TIMEOUT_BROADCAST: u32 = CHAN_CONFIRM_DEPTH + 1 + TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS;
8570         alice_broadcaster.blocks.lock().unwrap().resize((HTLC_TIMEOUT_BROADCAST) as usize, (block.clone(), HTLC_TIMEOUT_BROADCAST));
8571         watchtower_alice.chain_monitor.block_connected(&block, HTLC_TIMEOUT_BROADCAST);
8572
8573         // Watchtower Alice should have broadcast a commitment/HTLC-timeout
8574         {
8575                 let mut txn = alice_broadcaster.txn_broadcast();
8576                 assert_eq!(txn.len(), 2);
8577                 check_spends!(txn[0], chan_1.3);
8578                 check_spends!(txn[1], txn[0]);
8579         };
8580
8581         // Copy ChainMonitor to simulate watchtower Bob and make it receive a commitment update first.
8582         let chain_source = test_utils::TestChainSource::new(Network::Testnet);
8583         let logger = test_utils::TestLogger::with_id(format!("node {}", "Bob"));
8584         let persister = test_utils::TestPersister::new();
8585         let bob_broadcaster = test_utils::TestBroadcaster::with_blocks(Arc::clone(&alice_broadcaster.blocks));
8586         let watchtower_bob = {
8587                 let new_monitor = {
8588                         let monitor = nodes[0].chain_monitor.chain_monitor.get_monitor(outpoint).unwrap();
8589                         let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::read(
8590                                         &mut io::Cursor::new(&monitor.encode()), (nodes[0].keys_manager, nodes[0].keys_manager)).unwrap().1;
8591                         assert!(new_monitor == *monitor);
8592                         new_monitor
8593                 };
8594                 let watchtower = test_utils::TestChainMonitor::new(Some(&chain_source), &bob_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);
8595                 assert_eq!(watchtower.watch_channel(outpoint, new_monitor), Ok(ChannelMonitorUpdateStatus::Completed));
8596                 watchtower
8597         };
8598         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST - 1);
8599
8600         // Route another payment to generate another update with still previous HTLC pending
8601         let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], 3000000);
8602         nodes[1].node.send_payment_with_route(&route, payment_hash,
8603                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
8604         check_added_monitors!(nodes[1], 1);
8605
8606         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
8607         assert_eq!(updates.update_add_htlcs.len(), 1);
8608         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &updates.update_add_htlcs[0]);
8609         {
8610                 let mut node_0_per_peer_lock;
8611                 let mut node_0_peer_state_lock;
8612                 if let ChannelPhase::Funded(ref mut channel) = get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, chan_1.2) {
8613                         if let Ok(Some(update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].logger) {
8614                                 // Watchtower Alice should already have seen the block and reject the update
8615                                 assert_eq!(watchtower_alice.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::InProgress);
8616                                 assert_eq!(watchtower_bob.chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8617                                 assert_eq!(nodes[0].chain_monitor.update_channel(outpoint, &update), ChannelMonitorUpdateStatus::Completed);
8618                         } else { assert!(false); }
8619                 } else {
8620                         assert!(false);
8621                 }
8622         }
8623         // Our local monitor is in-sync and hasn't processed yet timeout
8624         check_added_monitors!(nodes[0], 1);
8625
8626         //// Provide one more block to watchtower Bob, expect broadcast of commitment and HTLC-Timeout
8627         watchtower_bob.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, Vec::new()), HTLC_TIMEOUT_BROADCAST);
8628
8629         // Watchtower Bob should have broadcast a commitment/HTLC-timeout
8630         let bob_state_y;
8631         {
8632                 let mut txn = bob_broadcaster.txn_broadcast();
8633                 assert_eq!(txn.len(), 2);
8634                 bob_state_y = txn.remove(0);
8635         };
8636
8637         // We confirm Bob's state Y on Alice, she should broadcast a HTLC-timeout
8638         let height = HTLC_TIMEOUT_BROADCAST + 1;
8639         connect_blocks(&nodes[0], height - nodes[0].best_block_info().1);
8640         check_closed_broadcast(&nodes[0], 1, true);
8641         check_closed_event!(&nodes[0], 1, ClosureReason::HolderForceClosed, false,
8642                 [nodes[1].node.get_our_node_id()], 100000);
8643         watchtower_alice.chain_monitor.block_connected(&create_dummy_block(BlockHash::all_zeros(), 42, vec![bob_state_y.clone()]), height);
8644         check_added_monitors(&nodes[0], 1);
8645         {
8646                 let htlc_txn = alice_broadcaster.txn_broadcast();
8647                 assert_eq!(htlc_txn.len(), 1);
8648                 check_spends!(htlc_txn[0], bob_state_y);
8649         }
8650 }
8651
8652 #[test]
8653 fn test_pre_lockin_no_chan_closed_update() {
8654         // Test that if a peer closes a channel in response to a funding_created message we don't
8655         // generate a channel update (as the channel cannot appear on chain without a funding_signed
8656         // message).
8657         //
8658         // Doing so would imply a channel monitor update before the initial channel monitor
8659         // registration, violating our API guarantees.
8660         //
8661         // Previously, full_stack_target managed to hit this case by opening then closing a channel,
8662         // then opening a second channel with the same funding output as the first (which is not
8663         // rejected because the first channel does not exist in the ChannelManager) and closing it
8664         // before receiving funding_signed.
8665         let chanmon_cfgs = create_chanmon_cfgs(2);
8666         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8667         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8668         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8669
8670         // Create an initial channel
8671         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8672         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
8673         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
8674         let accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
8675         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
8676
8677         // Move the first channel through the funding flow...
8678         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
8679
8680         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
8681         check_added_monitors!(nodes[0], 0);
8682
8683         let funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
8684         let channel_id = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index }.to_channel_id();
8685         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id, data: "Hi".to_owned() });
8686         assert!(nodes[0].chain_monitor.added_monitors.lock().unwrap().is_empty());
8687         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("Hi".to_string()) }, true,
8688                 [nodes[1].node.get_our_node_id()], 100000);
8689 }
8690
8691 #[test]
8692 fn test_htlc_no_detection() {
8693         // This test is a mutation to underscore the detection logic bug we had
8694         // before #653. HTLC value routed is above the remaining balance, thus
8695         // inverting HTLC and `to_remote` output. HTLC will come second and
8696         // it wouldn't be seen by pre-#653 detection as we were enumerate()'ing
8697         // on a watched outputs vector (Vec<TxOut>) thus implicitly relying on
8698         // outputs order detection for correct spending children filtring.
8699
8700         let chanmon_cfgs = create_chanmon_cfgs(2);
8701         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
8702         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
8703         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
8704
8705         // Create some initial channels
8706         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8707
8708         send_payment(&nodes[0], &vec!(&nodes[1])[..], 1_000_000);
8709         let (_, our_payment_hash, ..) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 2_000_000);
8710         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
8711         assert_eq!(local_txn[0].input.len(), 1);
8712         assert_eq!(local_txn[0].output.len(), 3);
8713         check_spends!(local_txn[0], chan_1.3);
8714
8715         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
8716         let block = create_dummy_block(nodes[0].best_block_hash(), 42, vec![local_txn[0].clone()]);
8717         connect_block(&nodes[0], &block);
8718         // We deliberately connect the local tx twice as this should provoke a failure calling
8719         // this test before #653 fix.
8720         chain::Listen::block_connected(&nodes[0].chain_monitor.chain_monitor, &block, nodes[0].best_block_info().1 + 1);
8721         check_closed_broadcast!(nodes[0], true);
8722         check_added_monitors!(nodes[0], 1);
8723         check_closed_event!(nodes[0], 1, ClosureReason::CommitmentTxConfirmed, [nodes[1].node.get_our_node_id()], 100000);
8724         connect_blocks(&nodes[0], TEST_FINAL_CLTV);
8725
8726         let htlc_timeout = {
8727                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
8728                 assert_eq!(node_txn.len(), 1);
8729                 assert_eq!(node_txn[0].input.len(), 1);
8730                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8731                 check_spends!(node_txn[0], local_txn[0]);
8732                 node_txn[0].clone()
8733         };
8734
8735         connect_block(&nodes[0], &create_dummy_block(nodes[0].best_block_hash(), 42, vec![htlc_timeout.clone()]));
8736         connect_blocks(&nodes[0], ANTI_REORG_DELAY - 1);
8737         expect_payment_failed!(nodes[0], our_payment_hash, false);
8738 }
8739
8740 fn do_test_onchain_htlc_settlement_after_close(broadcast_alice: bool, go_onchain_before_fulfill: bool) {
8741         // If we route an HTLC, then learn the HTLC's preimage after the upstream channel has been
8742         // force-closed, we must claim that HTLC on-chain. (Given an HTLC forwarded from Alice --> Bob -->
8743         // Carol, Alice would be the upstream node, and Carol the downstream.)
8744         //
8745         // Steps of the test:
8746         // 1) Alice sends a HTLC to Carol through Bob.
8747         // 2) Carol doesn't settle the HTLC.
8748         // 3) If broadcast_alice is true, Alice force-closes her channel with Bob. Else Bob force closes.
8749         // Steps 4 and 5 may be reordered depending on go_onchain_before_fulfill.
8750         // 4) Bob sees the Alice's commitment on his chain or vice versa. An offered output is present
8751         //    but can't be claimed as Bob doesn't have yet knowledge of the preimage.
8752         // 5) Carol release the preimage to Bob off-chain.
8753         // 6) Bob claims the offered output on the broadcasted commitment.
8754         let chanmon_cfgs = create_chanmon_cfgs(3);
8755         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8756         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8757         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8758
8759         // Create some initial channels
8760         let chan_ab = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
8761         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 100000, 10001);
8762
8763         // Steps (1) and (2):
8764         // Send an HTLC Alice --> Bob --> Carol, but Carol doesn't settle the HTLC back.
8765         let (payment_preimage, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3_000_000);
8766
8767         // Check that Alice's commitment transaction now contains an output for this HTLC.
8768         let alice_txn = get_local_commitment_txn!(nodes[0], chan_ab.2);
8769         check_spends!(alice_txn[0], chan_ab.3);
8770         assert_eq!(alice_txn[0].output.len(), 2);
8771         check_spends!(alice_txn[1], alice_txn[0]); // 2nd transaction is a non-final HTLC-timeout
8772         assert_eq!(alice_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
8773         assert_eq!(alice_txn.len(), 2);
8774
8775         // Steps (3) and (4):
8776         // If `go_onchain_before_fufill`, broadcast the relevant commitment transaction and check that Bob
8777         // responds by (1) broadcasting a channel update and (2) adding a new ChannelMonitor.
8778         let mut force_closing_node = 0; // Alice force-closes
8779         let mut counterparty_node = 1; // Bob if Alice force-closes
8780
8781         // Bob force-closes
8782         if !broadcast_alice {
8783                 force_closing_node = 1;
8784                 counterparty_node = 0;
8785         }
8786         nodes[force_closing_node].node.force_close_broadcasting_latest_txn(&chan_ab.2, &nodes[counterparty_node].node.get_our_node_id()).unwrap();
8787         check_closed_broadcast!(nodes[force_closing_node], true);
8788         check_added_monitors!(nodes[force_closing_node], 1);
8789         check_closed_event!(nodes[force_closing_node], 1, ClosureReason::HolderForceClosed, [nodes[counterparty_node].node.get_our_node_id()], 100000);
8790         if go_onchain_before_fulfill {
8791                 let txn_to_broadcast = match broadcast_alice {
8792                         true => alice_txn.clone(),
8793                         false => get_local_commitment_txn!(nodes[1], chan_ab.2)
8794                 };
8795                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8796                 if broadcast_alice {
8797                         check_closed_broadcast!(nodes[1], true);
8798                         check_added_monitors!(nodes[1], 1);
8799                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8800                 }
8801         }
8802
8803         // Step (5):
8804         // Carol then claims the funds and sends an update_fulfill message to Bob, and they go through the
8805         // process of removing the HTLC from their commitment transactions.
8806         nodes[2].node.claim_funds(payment_preimage);
8807         check_added_monitors!(nodes[2], 1);
8808         expect_payment_claimed!(nodes[2], payment_hash, 3_000_000);
8809
8810         let carol_updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
8811         assert!(carol_updates.update_add_htlcs.is_empty());
8812         assert!(carol_updates.update_fail_htlcs.is_empty());
8813         assert!(carol_updates.update_fail_malformed_htlcs.is_empty());
8814         assert!(carol_updates.update_fee.is_none());
8815         assert_eq!(carol_updates.update_fulfill_htlcs.len(), 1);
8816
8817         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &carol_updates.update_fulfill_htlcs[0]);
8818         let went_onchain = go_onchain_before_fulfill || force_closing_node == 1;
8819         expect_payment_forwarded!(nodes[1], nodes[0], nodes[2], if went_onchain { None } else { Some(1000) }, went_onchain, false);
8820         // If Alice broadcasted but Bob doesn't know yet, here he prepares to tell her about the preimage.
8821         if !go_onchain_before_fulfill && broadcast_alice {
8822                 let events = nodes[1].node.get_and_clear_pending_msg_events();
8823                 assert_eq!(events.len(), 1);
8824                 match events[0] {
8825                         MessageSendEvent::UpdateHTLCs { ref node_id, .. } => {
8826                                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
8827                         },
8828                         _ => panic!("Unexpected event"),
8829                 };
8830         }
8831         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &carol_updates.commitment_signed);
8832         // One monitor update for the preimage to update the Bob<->Alice channel, one monitor update
8833         // Carol<->Bob's updated commitment transaction info.
8834         check_added_monitors!(nodes[1], 2);
8835
8836         let events = nodes[1].node.get_and_clear_pending_msg_events();
8837         assert_eq!(events.len(), 2);
8838         let bob_revocation = match events[0] {
8839                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8840                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8841                         (*msg).clone()
8842                 },
8843                 _ => panic!("Unexpected event"),
8844         };
8845         let bob_updates = match events[1] {
8846                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
8847                         assert_eq!(*node_id, nodes[2].node.get_our_node_id());
8848                         (*updates).clone()
8849                 },
8850                 _ => panic!("Unexpected event"),
8851         };
8852
8853         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revocation);
8854         check_added_monitors!(nodes[2], 1);
8855         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_updates.commitment_signed);
8856         check_added_monitors!(nodes[2], 1);
8857
8858         let events = nodes[2].node.get_and_clear_pending_msg_events();
8859         assert_eq!(events.len(), 1);
8860         let carol_revocation = match events[0] {
8861                 MessageSendEvent::SendRevokeAndACK { ref node_id, ref msg } => {
8862                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
8863                         (*msg).clone()
8864                 },
8865                 _ => panic!("Unexpected event"),
8866         };
8867         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &carol_revocation);
8868         check_added_monitors!(nodes[1], 1);
8869
8870         // If this test requires the force-closed channel to not be on-chain until after the fulfill,
8871         // here's where we put said channel's commitment tx on-chain.
8872         let mut txn_to_broadcast = alice_txn.clone();
8873         if !broadcast_alice { txn_to_broadcast = get_local_commitment_txn!(nodes[1], chan_ab.2); }
8874         if !go_onchain_before_fulfill {
8875                 connect_block(&nodes[1], &create_dummy_block(nodes[1].best_block_hash(), 42, vec![txn_to_broadcast[0].clone()]));
8876                 // If Bob was the one to force-close, he will have already passed these checks earlier.
8877                 if broadcast_alice {
8878                         check_closed_broadcast!(nodes[1], true);
8879                         check_added_monitors!(nodes[1], 1);
8880                         check_closed_event!(nodes[1], 1, ClosureReason::CommitmentTxConfirmed, [nodes[0].node.get_our_node_id()], 100000);
8881                 }
8882                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
8883                 if broadcast_alice {
8884                         assert_eq!(bob_txn.len(), 1);
8885                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8886                 } else {
8887                         if nodes[1].connect_style.borrow().updates_best_block_first() {
8888                                 assert_eq!(bob_txn.len(), 3);
8889                                 assert_eq!(bob_txn[0].txid(), bob_txn[1].txid());
8890                         } else {
8891                                 assert_eq!(bob_txn.len(), 2);
8892                         }
8893                         check_spends!(bob_txn[0], chan_ab.3);
8894                 }
8895         }
8896
8897         // Step (6):
8898         // Finally, check that Bob broadcasted a preimage-claiming transaction for the HTLC output on the
8899         // broadcasted commitment transaction.
8900         {
8901                 let script_weight = match broadcast_alice {
8902                         true => OFFERED_HTLC_SCRIPT_WEIGHT,
8903                         false => ACCEPTED_HTLC_SCRIPT_WEIGHT
8904                 };
8905                 // If Alice force-closed, Bob only broadcasts a HTLC-output-claiming transaction. Otherwise,
8906                 // Bob force-closed and broadcasts the commitment transaction along with a
8907                 // HTLC-output-claiming transaction.
8908                 let mut bob_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
8909                 if broadcast_alice {
8910                         assert_eq!(bob_txn.len(), 1);
8911                         check_spends!(bob_txn[0], txn_to_broadcast[0]);
8912                         assert_eq!(bob_txn[0].input[0].witness.last().unwrap().len(), script_weight);
8913                 } else {
8914                         assert_eq!(bob_txn.len(), if nodes[1].connect_style.borrow().updates_best_block_first() { 3 } else { 2 });
8915                         let htlc_tx = bob_txn.pop().unwrap();
8916                         check_spends!(htlc_tx, txn_to_broadcast[0]);
8917                         assert_eq!(htlc_tx.input[0].witness.last().unwrap().len(), script_weight);
8918                 }
8919         }
8920 }
8921
8922 #[test]
8923 fn test_onchain_htlc_settlement_after_close() {
8924         do_test_onchain_htlc_settlement_after_close(true, true);
8925         do_test_onchain_htlc_settlement_after_close(false, true); // Technically redundant, but may as well
8926         do_test_onchain_htlc_settlement_after_close(true, false);
8927         do_test_onchain_htlc_settlement_after_close(false, false);
8928 }
8929
8930 #[test]
8931 fn test_duplicate_temporary_channel_id_from_different_peers() {
8932         // Tests that we can accept two different `OpenChannel` requests with the same
8933         // `temporary_channel_id`, as long as they are from different peers.
8934         let chanmon_cfgs = create_chanmon_cfgs(3);
8935         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8936         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8937         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8938
8939         // Create an first channel channel
8940         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
8941         let mut open_chan_msg_chan_1_0 = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8942
8943         // Create an second channel
8944         nodes[2].node.create_channel(nodes[0].node.get_our_node_id(), 100000, 10001, 43, None, None).unwrap();
8945         let mut open_chan_msg_chan_2_0 = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
8946
8947         // Modify the `OpenChannel` from `nodes[2]` to `nodes[0]` to ensure that it uses the same
8948         // `temporary_channel_id` as the `OpenChannel` from nodes[1] to nodes[0].
8949         open_chan_msg_chan_2_0.temporary_channel_id = open_chan_msg_chan_1_0.temporary_channel_id;
8950
8951         // Assert that `nodes[0]` can accept both `OpenChannel` requests, even though they use the same
8952         // `temporary_channel_id` as they are from different peers.
8953         nodes[0].node.handle_open_channel(&nodes[1].node.get_our_node_id(), &open_chan_msg_chan_1_0);
8954         {
8955                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8956                 assert_eq!(events.len(), 1);
8957                 match &events[0] {
8958                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8959                                 assert_eq!(node_id, &nodes[1].node.get_our_node_id());
8960                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8961                         },
8962                         _ => panic!("Unexpected event"),
8963                 }
8964         }
8965
8966         nodes[0].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg_chan_2_0);
8967         {
8968                 let events = nodes[0].node.get_and_clear_pending_msg_events();
8969                 assert_eq!(events.len(), 1);
8970                 match &events[0] {
8971                         MessageSendEvent::SendAcceptChannel { node_id, msg } => {
8972                                 assert_eq!(node_id, &nodes[2].node.get_our_node_id());
8973                                 assert_eq!(msg.temporary_channel_id, open_chan_msg_chan_1_0.temporary_channel_id);
8974                         },
8975                         _ => panic!("Unexpected event"),
8976                 }
8977         }
8978 }
8979
8980 #[test]
8981 fn test_peer_funding_sidechannel() {
8982         // Test that if a peer somehow learns which txid we'll use for our channel funding before we
8983         // receive `funding_transaction_generated` the peer cannot cause us to crash. We'd previously
8984         // assumed that LDK would receive `funding_transaction_generated` prior to our peer learning
8985         // the txid and panicked if the peer tried to open a redundant channel to us with the same
8986         // funding outpoint.
8987         //
8988         // While this assumption is generally safe, some users may have out-of-band protocols where
8989         // they notify their LSP about a funding outpoint first, or this may be violated in the future
8990         // with collaborative transaction construction protocols, i.e. dual-funding.
8991         let chanmon_cfgs = create_chanmon_cfgs(3);
8992         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
8993         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
8994         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
8995
8996         let temp_chan_id_ab = exchange_open_accept_chan(&nodes[0], &nodes[1], 1_000_000, 0);
8997         let temp_chan_id_ca = exchange_open_accept_chan(&nodes[2], &nodes[0], 1_000_000, 0);
8998
8999         let (_, tx, funding_output) =
9000                 create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9001
9002         let cs_funding_events = nodes[2].node.get_and_clear_pending_events();
9003         assert_eq!(cs_funding_events.len(), 1);
9004         match cs_funding_events[0] {
9005                 Event::FundingGenerationReady { .. } => {}
9006                 _ => panic!("Unexpected event {:?}", cs_funding_events),
9007         }
9008
9009         nodes[2].node.funding_transaction_generated_unchecked(&temp_chan_id_ca, &nodes[0].node.get_our_node_id(), tx.clone(), funding_output.index).unwrap();
9010         let funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[0].node.get_our_node_id());
9011         nodes[0].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9012         get_event_msg!(nodes[0], MessageSendEvent::SendFundingSigned, nodes[2].node.get_our_node_id());
9013         expect_channel_pending_event(&nodes[0], &nodes[2].node.get_our_node_id());
9014         check_added_monitors!(nodes[0], 1);
9015
9016         let res = nodes[0].node.funding_transaction_generated(&temp_chan_id_ab, &nodes[1].node.get_our_node_id(), tx.clone());
9017         let err_msg = format!("{:?}", res.unwrap_err());
9018         assert!(err_msg.contains("An existing channel using outpoint "));
9019         assert!(err_msg.contains(" is open with peer"));
9020         // Even though the last funding_transaction_generated errored, it still generated a
9021         // SendFundingCreated. However, when the peer responds with a funding_signed it will send the
9022         // appropriate error message.
9023         let as_funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9024         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &as_funding_created);
9025         check_added_monitors!(nodes[1], 1);
9026         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9027         let reason = ClosureReason::ProcessingError { err: format!("An existing channel using outpoint {} is open with peer {}", funding_output, nodes[2].node.get_our_node_id()), };
9028         check_closed_events(&nodes[0], &[ExpectedCloseEvent::from_id_reason(funding_output.to_channel_id(), true, reason)]);
9029
9030         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9031         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9032         get_err_msg(&nodes[0], &nodes[1].node.get_our_node_id());
9033 }
9034
9035 #[test]
9036 fn test_duplicate_funding_err_in_funding() {
9037         // Test that if we have a live channel with one peer, then another peer comes along and tries
9038         // to create a second channel with the same txid we'll fail and not overwrite the
9039         // outpoint_to_peer map in `ChannelManager`.
9040         //
9041         // This was previously broken.
9042         let chanmon_cfgs = create_chanmon_cfgs(3);
9043         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9044         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9045         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9046
9047         let (_, _, _, real_channel_id, funding_tx) = create_chan_between_nodes(&nodes[0], &nodes[1]);
9048         let real_chan_funding_txo = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 };
9049         assert_eq!(real_chan_funding_txo.to_channel_id(), real_channel_id);
9050
9051         nodes[2].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
9052         let mut open_chan_msg = get_event_msg!(nodes[2], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9053         let node_c_temp_chan_id = open_chan_msg.temporary_channel_id;
9054         open_chan_msg.temporary_channel_id = real_channel_id;
9055         nodes[1].node.handle_open_channel(&nodes[2].node.get_our_node_id(), &open_chan_msg);
9056         let mut accept_chan_msg = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[2].node.get_our_node_id());
9057         accept_chan_msg.temporary_channel_id = node_c_temp_chan_id;
9058         nodes[2].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_chan_msg);
9059
9060         // Now that we have a second channel with the same funding txo, send a bogus funding message
9061         // and let nodes[1] remove the inbound channel.
9062         let (_, funding_tx, _) = create_funding_transaction(&nodes[2], &nodes[1].node.get_our_node_id(), 100_000, 42);
9063
9064         nodes[2].node.funding_transaction_generated(&node_c_temp_chan_id, &nodes[1].node.get_our_node_id(), funding_tx).unwrap();
9065
9066         let mut funding_created_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9067         funding_created_msg.temporary_channel_id = real_channel_id;
9068         // Make the signature invalid by changing the funding output
9069         funding_created_msg.funding_output_index += 10;
9070         nodes[1].node.handle_funding_created(&nodes[2].node.get_our_node_id(), &funding_created_msg);
9071         get_err_msg(&nodes[1], &nodes[2].node.get_our_node_id());
9072         let err = "Invalid funding_created signature from peer".to_owned();
9073         let reason = ClosureReason::ProcessingError { err };
9074         let expected_closing = ExpectedCloseEvent::from_id_reason(real_channel_id, false, reason);
9075         check_closed_events(&nodes[1], &[expected_closing]);
9076
9077         assert_eq!(
9078                 *nodes[1].node.outpoint_to_peer.lock().unwrap().get(&real_chan_funding_txo).unwrap(),
9079                 nodes[0].node.get_our_node_id()
9080         );
9081 }
9082
9083 #[test]
9084 fn test_duplicate_chan_id() {
9085         // Test that if a given peer tries to open a channel with the same channel_id as one that is
9086         // already open we reject it and keep the old channel.
9087         //
9088         // Previously, full_stack_target managed to figure out that if you tried to open two channels
9089         // with the same funding output (ie post-funding channel_id), we'd create a monitor update for
9090         // the existing channel when we detect the duplicate new channel, screwing up our monitor
9091         // updating logic for the existing channel.
9092         let chanmon_cfgs = create_chanmon_cfgs(2);
9093         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9094         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9095         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9096
9097         // Create an initial channel
9098         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9099         let mut open_chan_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9100         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9101         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9102
9103         // Try to create a second channel with the same temporary_channel_id as the first and check
9104         // that it is rejected.
9105         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9106         {
9107                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9108                 assert_eq!(events.len(), 1);
9109                 match events[0] {
9110                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9111                                 // Technically, at this point, nodes[1] would be justified in thinking both the
9112                                 // first (valid) and second (invalid) channels are closed, given they both have
9113                                 // the same non-temporary channel_id. However, currently we do not, so we just
9114                                 // move forward with it.
9115                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9116                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9117                         },
9118                         _ => panic!("Unexpected event"),
9119                 }
9120         }
9121
9122         // Move the first channel through the funding flow...
9123         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9124
9125         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9126         check_added_monitors!(nodes[0], 0);
9127
9128         let mut funding_created_msg = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9129         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msg);
9130         {
9131                 let mut added_monitors = nodes[1].chain_monitor.added_monitors.lock().unwrap();
9132                 assert_eq!(added_monitors.len(), 1);
9133                 assert_eq!(added_monitors[0].0, funding_output);
9134                 added_monitors.clear();
9135         }
9136         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9137
9138         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9139
9140         let funding_outpoint = crate::chain::transaction::OutPoint { txid: funding_created_msg.funding_txid, index: funding_created_msg.funding_output_index };
9141         let channel_id = funding_outpoint.to_channel_id();
9142
9143         // Now we have the first channel past funding_created (ie it has a txid-based channel_id, not a
9144         // temporary one).
9145
9146         // First try to open a second channel with a temporary channel id equal to the txid-based one.
9147         // Technically this is allowed by the spec, but we don't support it and there's little reason
9148         // to. Still, it shouldn't cause any other issues.
9149         open_chan_msg.temporary_channel_id = channel_id;
9150         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_msg);
9151         {
9152                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9153                 assert_eq!(events.len(), 1);
9154                 match events[0] {
9155                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9156                                 // Technically, at this point, nodes[1] would be justified in thinking both
9157                                 // channels are closed, but currently we do not, so we just move forward with it.
9158                                 assert_eq!(msg.channel_id, open_chan_msg.temporary_channel_id);
9159                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9160                         },
9161                         _ => panic!("Unexpected event"),
9162                 }
9163         }
9164
9165         // Now try to create a second channel which has a duplicate funding output.
9166         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9167         let open_chan_2_msg = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9168         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_chan_2_msg);
9169         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9170         create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42); // Get and check the FundingGenerationReady event
9171
9172         let funding_created = {
9173                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9174                 let mut a_peer_state = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9175                 // Once we call `get_funding_created` the channel has a duplicate channel_id as
9176                 // another channel in the ChannelManager - an invalid state. Thus, we'd panic later when we
9177                 // try to create another channel. Instead, we drop the channel entirely here (leaving the
9178                 // channelmanager in a possibly nonsense state instead).
9179                 match a_peer_state.channel_by_id.remove(&open_chan_2_msg.temporary_channel_id).unwrap() {
9180                         ChannelPhase::UnfundedOutboundV1(mut chan) => {
9181                                 let logger = test_utils::TestLogger::new();
9182                                 chan.get_funding_created(tx.clone(), funding_outpoint, false, &&logger).map_err(|_| ()).unwrap()
9183                         },
9184                         _ => panic!("Unexpected ChannelPhase variant"),
9185                 }.unwrap()
9186         };
9187         check_added_monitors!(nodes[0], 0);
9188         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9189         // At this point we'll look up if the channel_id is present and immediately fail the channel
9190         // without trying to persist the `ChannelMonitor`.
9191         check_added_monitors!(nodes[1], 0);
9192
9193         check_closed_events(&nodes[1], &[
9194                 ExpectedCloseEvent::from_id_reason(funding_created.temporary_channel_id, false, ClosureReason::ProcessingError {
9195                         err: "Already had channel with the new channel_id".to_owned()
9196                 })
9197         ]);
9198
9199         // ...still, nodes[1] will reject the duplicate channel.
9200         {
9201                 let events = nodes[1].node.get_and_clear_pending_msg_events();
9202                 assert_eq!(events.len(), 1);
9203                 match events[0] {
9204                         MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id } => {
9205                                 // Technically, at this point, nodes[1] would be justified in thinking both
9206                                 // channels are closed, but currently we do not, so we just move forward with it.
9207                                 assert_eq!(msg.channel_id, channel_id);
9208                                 assert_eq!(node_id, nodes[0].node.get_our_node_id());
9209                         },
9210                         _ => panic!("Unexpected event"),
9211                 }
9212         }
9213
9214         // finally, finish creating the original channel and send a payment over it to make sure
9215         // everything is functional.
9216         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
9217         {
9218                 let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9219                 assert_eq!(added_monitors.len(), 1);
9220                 assert_eq!(added_monitors[0].0, funding_output);
9221                 added_monitors.clear();
9222         }
9223         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9224
9225         let events_4 = nodes[0].node.get_and_clear_pending_events();
9226         assert_eq!(events_4.len(), 0);
9227         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9228         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9229
9230         let (channel_ready, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9231         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9232         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9233
9234         send_payment(&nodes[0], &[&nodes[1]], 8000000);
9235 }
9236
9237 #[test]
9238 fn test_error_chans_closed() {
9239         // Test that we properly handle error messages, closing appropriate channels.
9240         //
9241         // Prior to #787 we'd allow a peer to make us force-close a channel we had with a different
9242         // peer. The "real" fix for that is to index channels with peers_ids, however in the mean time
9243         // we can test various edge cases around it to ensure we don't regress.
9244         let chanmon_cfgs = create_chanmon_cfgs(3);
9245         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9246         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9247         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9248
9249         // Create some initial channels
9250         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9251         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9252         let chan_3 = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100000, 10001);
9253
9254         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9255         assert_eq!(nodes[1].node.list_usable_channels().len(), 2);
9256         assert_eq!(nodes[2].node.list_usable_channels().len(), 1);
9257
9258         // Closing a channel from a different peer has no effect
9259         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_3.2, data: "ERR".to_owned() });
9260         assert_eq!(nodes[0].node.list_usable_channels().len(), 3);
9261
9262         // Closing one channel doesn't impact others
9263         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: chan_2.2, data: "ERR".to_owned() });
9264         check_added_monitors!(nodes[0], 1);
9265         check_closed_broadcast!(nodes[0], false);
9266         check_closed_event!(nodes[0], 1, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9267                 [nodes[1].node.get_our_node_id()], 100000);
9268         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0).len(), 1);
9269         assert_eq!(nodes[0].node.list_usable_channels().len(), 2);
9270         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_1.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_1.2);
9271         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2 || nodes[0].node.list_usable_channels()[1].channel_id == chan_3.2);
9272
9273         // A null channel ID should close all channels
9274         let _chan_4 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9275         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msgs::ErrorMessage { channel_id: ChannelId::new_zero(), data: "ERR".to_owned() });
9276         check_added_monitors!(nodes[0], 2);
9277         check_closed_event!(nodes[0], 2, ClosureReason::CounterpartyForceClosed { peer_msg: UntrustedString("ERR".to_string()) },
9278                 [nodes[1].node.get_our_node_id(); 2], 100000);
9279         let events = nodes[0].node.get_and_clear_pending_msg_events();
9280         assert_eq!(events.len(), 2);
9281         match events[0] {
9282                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9283                         assert_eq!(msg.contents.flags & 2, 2);
9284                 },
9285                 _ => panic!("Unexpected event"),
9286         }
9287         match events[1] {
9288                 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
9289                         assert_eq!(msg.contents.flags & 2, 2);
9290                 },
9291                 _ => panic!("Unexpected event"),
9292         }
9293         // Note that at this point users of a standard PeerHandler will end up calling
9294         // peer_disconnected.
9295         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9296         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9297
9298         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9299         assert_eq!(nodes[0].node.list_usable_channels().len(), 1);
9300         assert!(nodes[0].node.list_usable_channels()[0].channel_id == chan_3.2);
9301 }
9302
9303 #[test]
9304 fn test_invalid_funding_tx() {
9305         // Test that we properly handle invalid funding transactions sent to us from a peer.
9306         //
9307         // Previously, all other major lightning implementations had failed to properly sanitize
9308         // funding transactions from their counterparties, leading to a multi-implementation critical
9309         // security vulnerability (though we always sanitized properly, we've previously had
9310         // un-released crashes in the sanitization process).
9311         //
9312         // Further, if the funding transaction is consensus-valid, confirms, and is later spent, we'd
9313         // previously have crashed in `ChannelMonitor` even though we closed the channel as bogus and
9314         // gave up on it. We test this here by generating such a transaction.
9315         let chanmon_cfgs = create_chanmon_cfgs(2);
9316         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9317         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9318         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9319
9320         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 10_000, 42, None, None).unwrap();
9321         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
9322         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id()));
9323
9324         let (temporary_channel_id, mut tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100_000, 42);
9325
9326         // Create a witness program which can be spent by a 4-empty-stack-elements witness and which is
9327         // 136 bytes long. This matches our "accepted HTLC preimage spend" matching, previously causing
9328         // a panic as we'd try to extract a 32 byte preimage from a witness element without checking
9329         // its length.
9330         let mut wit_program: Vec<u8> = channelmonitor::deliberately_bogus_accepted_htlc_witness_program();
9331         let wit_program_script: ScriptBuf = wit_program.into();
9332         for output in tx.output.iter_mut() {
9333                 // Make the confirmed funding transaction have a bogus script_pubkey
9334                 output.script_pubkey = ScriptBuf::new_v0_p2wsh(&wit_program_script.wscript_hash());
9335         }
9336
9337         nodes[0].node.funding_transaction_generated_unchecked(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone(), 0).unwrap();
9338         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9339         check_added_monitors!(nodes[1], 1);
9340         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9341
9342         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9343         check_added_monitors!(nodes[0], 1);
9344         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9345
9346         let events_1 = nodes[0].node.get_and_clear_pending_events();
9347         assert_eq!(events_1.len(), 0);
9348
9349         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
9350         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0], tx);
9351         nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
9352
9353         let expected_err = "funding tx had wrong script/value or output index";
9354         confirm_transaction_at(&nodes[1], &tx, 1);
9355         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError { err: expected_err.to_string() },
9356                 [nodes[0].node.get_our_node_id()], 100000);
9357         check_added_monitors!(nodes[1], 1);
9358         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
9359         assert_eq!(events_2.len(), 1);
9360         if let MessageSendEvent::HandleError { node_id, action } = &events_2[0] {
9361                 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
9362                 if let msgs::ErrorAction::DisconnectPeer { msg } = action {
9363                         assert_eq!(msg.as_ref().unwrap().data, "Channel closed because of an exception: ".to_owned() + expected_err);
9364                 } else { panic!(); }
9365         } else { panic!(); }
9366         assert_eq!(nodes[1].node.list_channels().len(), 0);
9367
9368         // Now confirm a spend of the (bogus) funding transaction. As long as the witness is 5 elements
9369         // long the ChannelMonitor will try to read 32 bytes from the second-to-last element, panicing
9370         // as its not 32 bytes long.
9371         let mut spend_tx = Transaction {
9372                 version: 2i32, lock_time: LockTime::ZERO,
9373                 input: tx.output.iter().enumerate().map(|(idx, _)| TxIn {
9374                         previous_output: BitcoinOutPoint {
9375                                 txid: tx.txid(),
9376                                 vout: idx as u32,
9377                         },
9378                         script_sig: ScriptBuf::new(),
9379                         sequence: Sequence::ENABLE_RBF_NO_LOCKTIME,
9380                         witness: Witness::from_slice(&channelmonitor::deliberately_bogus_accepted_htlc_witness())
9381                 }).collect(),
9382                 output: vec![TxOut {
9383                         value: 1000,
9384                         script_pubkey: ScriptBuf::new(),
9385                 }]
9386         };
9387         check_spends!(spend_tx, tx);
9388         mine_transaction(&nodes[1], &spend_tx);
9389 }
9390
9391 #[test]
9392 fn test_coinbase_funding_tx() {
9393         // Miners are able to fund channels directly from coinbase transactions, however
9394         // by consensus rules, outputs of a coinbase transaction are encumbered by a 100
9395         // block maturity timelock. To ensure that a (non-0conf) channel like this is enforceable
9396         // on-chain, the minimum depth is updated to 100 blocks for coinbase funding transactions.
9397         //
9398         // Note that 0conf channels with coinbase funding transactions are unaffected and are
9399         // immediately operational after opening.
9400         let chanmon_cfgs = create_chanmon_cfgs(2);
9401         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9402         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9403         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9404
9405         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None, None).unwrap();
9406         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9407
9408         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9409         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9410
9411         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9412
9413         // Create the coinbase funding transaction.
9414         let (temporary_channel_id, tx, _) = create_coinbase_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 100000, 42);
9415
9416         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9417         check_added_monitors!(nodes[0], 0);
9418         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
9419
9420         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
9421         check_added_monitors!(nodes[1], 1);
9422         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9423
9424         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
9425
9426         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
9427         check_added_monitors!(nodes[0], 1);
9428
9429         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9430         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
9431
9432         // Starting at height 0, we "confirm" the coinbase at height 1.
9433         confirm_transaction_at(&nodes[0], &tx, 1);
9434         // We connect 98 more blocks to have 99 confirmations for the coinbase transaction.
9435         connect_blocks(&nodes[0], COINBASE_MATURITY - 2);
9436         // Check that we have no pending message events (we have not queued a `channel_ready` yet).
9437         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
9438         // Now connect one more block which results in 100 confirmations of the coinbase transaction.
9439         connect_blocks(&nodes[0], 1);
9440         // There should now be a `channel_ready` which can be handled.
9441         let _ = &nodes[1].node.handle_channel_ready(&nodes[0].node.get_our_node_id(), &get_event_msg!(&nodes[0], MessageSendEvent::SendChannelReady, nodes[1].node.get_our_node_id()));
9442
9443         confirm_transaction_at(&nodes[1], &tx, 1);
9444         connect_blocks(&nodes[1], COINBASE_MATURITY - 2);
9445         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
9446         connect_blocks(&nodes[1], 1);
9447         expect_channel_ready_event(&nodes[1], &nodes[0].node.get_our_node_id());
9448         create_chan_between_nodes_with_value_confirm_second(&nodes[0], &nodes[1]);
9449 }
9450
9451 fn do_test_tx_confirmed_skipping_blocks_immediate_broadcast(test_height_before_timelock: bool) {
9452         // In the first version of the chain::Confirm interface, after a refactor was made to not
9453         // broadcast CSV-locked transactions until their CSV lock is up, we wouldn't reliably broadcast
9454         // transactions after a `transactions_confirmed` call. Specifically, if the chain, provided via
9455         // `best_block_updated` is at height N, and a transaction output which we wish to spend at
9456         // height N-1 (due to a CSV to height N-1) is provided at height N, we will not broadcast the
9457         // spending transaction until height N+1 (or greater). This was due to the way
9458         // `ChannelMonitor::transactions_confirmed` worked, only checking if we should broadcast a
9459         // spending transaction at the height the input transaction was confirmed at, not whether we
9460         // should broadcast a spending transaction at the current height.
9461         // A second, similar, issue involved failing HTLCs backwards - because we only provided the
9462         // height at which transactions were confirmed to `OnchainTx::update_claims_view`, it wasn't
9463         // aware that the anti-reorg-delay had, in fact, already expired, waiting to fail-backwards
9464         // until we learned about an additional block.
9465         //
9466         // As an additional check, if `test_height_before_timelock` is set, we instead test that we
9467         // aren't broadcasting transactions too early (ie not broadcasting them at all).
9468         let chanmon_cfgs = create_chanmon_cfgs(3);
9469         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
9470         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
9471         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
9472         *nodes[0].connect_style.borrow_mut() = ConnectStyle::BestBlockFirstSkippingBlocks;
9473
9474         create_announced_chan_between_nodes(&nodes, 0, 1);
9475         let (chan_announce, _, channel_id, _) = create_announced_chan_between_nodes(&nodes, 1, 2);
9476         let (_, payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1_000_000);
9477         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id());
9478         nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id());
9479
9480         nodes[1].node.force_close_broadcasting_latest_txn(&channel_id, &nodes[2].node.get_our_node_id()).unwrap();
9481         check_closed_broadcast!(nodes[1], true);
9482         check_closed_event!(nodes[1], 1, ClosureReason::HolderForceClosed, [nodes[2].node.get_our_node_id()], 100000);
9483         check_added_monitors!(nodes[1], 1);
9484         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9485         assert_eq!(node_txn.len(), 1);
9486
9487         let conf_height = nodes[1].best_block_info().1;
9488         if !test_height_before_timelock {
9489                 connect_blocks(&nodes[1], 24 * 6);
9490         }
9491         nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9492                 &nodes[1].get_block_header(conf_height), &[(0, &node_txn[0])], conf_height);
9493         if test_height_before_timelock {
9494                 // If we confirmed the close transaction, but timelocks have not yet expired, we should not
9495                 // generate any events or broadcast any transactions
9496                 assert!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
9497                 assert!(nodes[1].chain_monitor.chain_monitor.get_and_clear_pending_events().is_empty());
9498         } else {
9499                 // We should broadcast an HTLC transaction spending our funding transaction first
9500                 let spending_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().split_off(0);
9501                 assert_eq!(spending_txn.len(), 2);
9502                 let htlc_tx = if spending_txn[0].txid() == node_txn[0].txid() {
9503                         &spending_txn[1]
9504                 } else {
9505                         &spending_txn[0]
9506                 };
9507                 check_spends!(htlc_tx, node_txn[0]);
9508                 // We should also generate a SpendableOutputs event with the to_self output (as its
9509                 // timelock is up).
9510                 let descriptor_spend_txn = check_spendable_outputs!(nodes[1], node_cfgs[1].keys_manager);
9511                 assert_eq!(descriptor_spend_txn.len(), 1);
9512
9513                 // If we also discover that the HTLC-Timeout transaction was confirmed some time ago, we
9514                 // should immediately fail-backwards the HTLC to the previous hop, without waiting for an
9515                 // additional block built on top of the current chain.
9516                 nodes[1].chain_monitor.chain_monitor.transactions_confirmed(
9517                         &nodes[1].get_block_header(conf_height + 1), &[(0, htlc_tx)], conf_height + 1);
9518                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[2].node.get_our_node_id()), channel_id: channel_id }]);
9519                 check_added_monitors!(nodes[1], 1);
9520
9521                 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9522                 assert!(updates.update_add_htlcs.is_empty());
9523                 assert!(updates.update_fulfill_htlcs.is_empty());
9524                 assert_eq!(updates.update_fail_htlcs.len(), 1);
9525                 assert!(updates.update_fail_malformed_htlcs.is_empty());
9526                 assert!(updates.update_fee.is_none());
9527                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
9528                 commitment_signed_dance!(nodes[0], nodes[1], updates.commitment_signed, true, true);
9529                 expect_payment_failed_with_update!(nodes[0], payment_hash, false, chan_announce.contents.short_channel_id, true);
9530         }
9531 }
9532
9533 #[test]
9534 fn test_tx_confirmed_skipping_blocks_immediate_broadcast() {
9535         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(false);
9536         do_test_tx_confirmed_skipping_blocks_immediate_broadcast(true);
9537 }
9538
9539 fn do_test_dup_htlc_second_rejected(test_for_second_fail_panic: bool) {
9540         let chanmon_cfgs = create_chanmon_cfgs(2);
9541         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9542         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
9543         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9544
9545         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 10001);
9546
9547         let payment_params = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), TEST_FINAL_CLTV)
9548                 .with_bolt11_features(nodes[1].node.bolt11_invoice_features()).unwrap();
9549         let route = get_route!(nodes[0], payment_params, 10_000).unwrap();
9550
9551         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[1]);
9552
9553         {
9554                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9555                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_hash.0)).unwrap();
9556                 check_added_monitors!(nodes[0], 1);
9557                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9558                 assert_eq!(events.len(), 1);
9559                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9560                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9561                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9562         }
9563         expect_pending_htlcs_forwardable!(nodes[1]);
9564         expect_payment_claimable!(nodes[1], our_payment_hash, our_payment_secret, 10_000);
9565
9566         {
9567                 // Note that we use a different PaymentId here to allow us to duplicativly pay
9568                 nodes[0].node.send_payment_with_route(&route, our_payment_hash,
9569                         RecipientOnionFields::secret_only(our_payment_secret), PaymentId(our_payment_secret.0)).unwrap();
9570                 check_added_monitors!(nodes[0], 1);
9571                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9572                 assert_eq!(events.len(), 1);
9573                 let mut payment_event = SendEvent::from_event(events.pop().unwrap());
9574                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9575                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
9576                 // At this point, nodes[1] would notice it has too much value for the payment. It will
9577                 // assume the second is a privacy attack (no longer particularly relevant
9578                 // post-payment_secrets) and fail back the new HTLC. Previously, it'd also have failed back
9579                 // the first HTLC delivered above.
9580         }
9581
9582         expect_pending_htlcs_forwardable_ignore!(nodes[1]);
9583         nodes[1].node.process_pending_htlc_forwards();
9584
9585         if test_for_second_fail_panic {
9586                 // Now we go fail back the first HTLC from the user end.
9587                 nodes[1].node.fail_htlc_backwards(&our_payment_hash);
9588
9589                 let expected_destinations = vec![
9590                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9591                         HTLCDestination::FailedPayment { payment_hash: our_payment_hash },
9592                 ];
9593                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1],  expected_destinations);
9594                 nodes[1].node.process_pending_htlc_forwards();
9595
9596                 check_added_monitors!(nodes[1], 1);
9597                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9598                 assert_eq!(fail_updates_1.update_fail_htlcs.len(), 2);
9599
9600                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9601                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[1]);
9602                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9603
9604                 let failure_events = nodes[0].node.get_and_clear_pending_events();
9605                 assert_eq!(failure_events.len(), 4);
9606                 if let Event::PaymentPathFailed { .. } = failure_events[0] {} else { panic!(); }
9607                 if let Event::PaymentFailed { .. } = failure_events[1] {} else { panic!(); }
9608                 if let Event::PaymentPathFailed { .. } = failure_events[2] {} else { panic!(); }
9609                 if let Event::PaymentFailed { .. } = failure_events[3] {} else { panic!(); }
9610         } else {
9611                 // Let the second HTLC fail and claim the first
9612                 expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9613                 nodes[1].node.process_pending_htlc_forwards();
9614
9615                 check_added_monitors!(nodes[1], 1);
9616                 let fail_updates_1 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
9617                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9618                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates_1.commitment_signed, false);
9619
9620                 expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new());
9621
9622                 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
9623         }
9624 }
9625
9626 #[test]
9627 fn test_dup_htlc_second_fail_panic() {
9628         // Previously, if we received two HTLCs back-to-back, where the second overran the expected
9629         // value for the payment, we'd fail back both HTLCs after generating a `PaymentClaimable` event.
9630         // Then, if the user failed the second payment, they'd hit a "tried to fail an already failed
9631         // HTLC" debug panic. This tests for this behavior, checking that only one HTLC is auto-failed.
9632         do_test_dup_htlc_second_rejected(true);
9633 }
9634
9635 #[test]
9636 fn test_dup_htlc_second_rejected() {
9637         // Test that if we receive a second HTLC for an MPP payment that overruns the payment amount we
9638         // simply reject the second HTLC but are still able to claim the first HTLC.
9639         do_test_dup_htlc_second_rejected(false);
9640 }
9641
9642 #[test]
9643 fn test_inconsistent_mpp_params() {
9644         // Test that if we recieve two HTLCs with different payment parameters we fail back the first
9645         // such HTLC and allow the second to stay.
9646         let chanmon_cfgs = create_chanmon_cfgs(4);
9647         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9648         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9649         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9650
9651         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9652         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9653         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9654         let chan_2_3 =create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9655
9656         let payment_params = PaymentParameters::from_node_id(nodes[3].node.get_our_node_id(), TEST_FINAL_CLTV)
9657                 .with_bolt11_features(nodes[3].node.bolt11_invoice_features()).unwrap();
9658         let mut route = get_route!(nodes[0], payment_params, 15_000_000).unwrap();
9659         assert_eq!(route.paths.len(), 2);
9660         route.paths.sort_by(|path_a, _| {
9661                 // Sort the path so that the path through nodes[1] comes first
9662                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9663                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9664         });
9665
9666         let (our_payment_preimage, our_payment_hash, our_payment_secret) = get_payment_preimage_hash!(&nodes[3]);
9667
9668         let cur_height = nodes[0].best_block_info().1;
9669         let payment_id = PaymentId([42; 32]);
9670
9671         let session_privs = {
9672                 // We create a fake route here so that we start with three pending HTLCs, which we'll
9673                 // ultimately have, just not right away.
9674                 let mut dup_route = route.clone();
9675                 dup_route.paths.push(route.paths[1].clone());
9676                 nodes[0].node.test_add_new_pending_payment(our_payment_hash,
9677                         RecipientOnionFields::secret_only(our_payment_secret), payment_id, &dup_route).unwrap()
9678         };
9679         nodes[0].node.test_send_payment_along_path(&route.paths[0], &our_payment_hash,
9680                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9681                 &None, session_privs[0]).unwrap();
9682         check_added_monitors!(nodes[0], 1);
9683
9684         {
9685                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9686                 assert_eq!(events.len(), 1);
9687                 pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), false, None);
9688         }
9689         assert!(nodes[3].node.get_and_clear_pending_events().is_empty());
9690
9691         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9692                 RecipientOnionFields::secret_only(our_payment_secret), 14_000_000, cur_height, payment_id, &None, session_privs[1]).unwrap();
9693         check_added_monitors!(nodes[0], 1);
9694
9695         {
9696                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9697                 assert_eq!(events.len(), 1);
9698                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9699
9700                 nodes[2].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
9701                 commitment_signed_dance!(nodes[2], nodes[0], payment_event.commitment_msg, false);
9702
9703                 expect_pending_htlcs_forwardable!(nodes[2]);
9704                 check_added_monitors!(nodes[2], 1);
9705
9706                 let mut events = nodes[2].node.get_and_clear_pending_msg_events();
9707                 assert_eq!(events.len(), 1);
9708                 let payment_event = SendEvent::from_event(events.pop().unwrap());
9709
9710                 nodes[3].node.handle_update_add_htlc(&nodes[2].node.get_our_node_id(), &payment_event.msgs[0]);
9711                 check_added_monitors!(nodes[3], 0);
9712                 commitment_signed_dance!(nodes[3], nodes[2], payment_event.commitment_msg, true, true);
9713
9714                 // At this point, nodes[3] should notice the two HTLCs don't contain the same total payment
9715                 // amount. It will assume the second is a privacy attack (no longer particularly relevant
9716                 // post-payment_secrets) and fail back the new HTLC.
9717         }
9718         expect_pending_htlcs_forwardable_ignore!(nodes[3]);
9719         nodes[3].node.process_pending_htlc_forwards();
9720         expect_pending_htlcs_forwardable_and_htlc_handling_failed_ignore!(nodes[3], vec![HTLCDestination::FailedPayment { payment_hash: our_payment_hash }]);
9721         nodes[3].node.process_pending_htlc_forwards();
9722
9723         check_added_monitors!(nodes[3], 1);
9724
9725         let fail_updates_1 = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
9726         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &fail_updates_1.update_fail_htlcs[0]);
9727         commitment_signed_dance!(nodes[2], nodes[3], fail_updates_1.commitment_signed, false);
9728
9729         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[2], vec![HTLCDestination::NextHopChannel { node_id: Some(nodes[3].node.get_our_node_id()), channel_id: chan_2_3.2 }]);
9730         check_added_monitors!(nodes[2], 1);
9731
9732         let fail_updates_2 = get_htlc_update_msgs!(nodes[2], nodes[0].node.get_our_node_id());
9733         nodes[0].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_updates_2.update_fail_htlcs[0]);
9734         commitment_signed_dance!(nodes[0], nodes[2], fail_updates_2.commitment_signed, false);
9735
9736         expect_payment_failed_conditions(&nodes[0], our_payment_hash, true, PaymentFailedConditions::new().mpp_parts_remain());
9737
9738         nodes[0].node.test_send_payment_along_path(&route.paths[1], &our_payment_hash,
9739                 RecipientOnionFields::secret_only(our_payment_secret), 15_000_000, cur_height, payment_id,
9740                 &None, session_privs[2]).unwrap();
9741         check_added_monitors!(nodes[0], 1);
9742
9743         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9744         assert_eq!(events.len(), 1);
9745         pass_along_path(&nodes[0], &[&nodes[2], &nodes[3]], 15_000_000, our_payment_hash, Some(our_payment_secret), events.pop().unwrap(), true, None);
9746
9747         do_claim_payment_along_route(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, our_payment_preimage);
9748         expect_payment_sent(&nodes[0], our_payment_preimage, Some(None), true, true);
9749 }
9750
9751 #[test]
9752 fn test_double_partial_claim() {
9753         // Test what happens if a node receives a payment, generates a PaymentClaimable event, the HTLCs
9754         // time out, the sender resends only some of the MPP parts, then the user processes the
9755         // PaymentClaimable event, ensuring they don't inadvertently claim only part of the full payment
9756         // amount.
9757         let chanmon_cfgs = create_chanmon_cfgs(4);
9758         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
9759         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
9760         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
9761
9762         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100_000, 0);
9763         create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 100_000, 0);
9764         create_announced_chan_between_nodes_with_value(&nodes, 1, 3, 100_000, 0);
9765         create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 100_000, 0);
9766
9767         let (mut route, payment_hash, payment_preimage, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[3], 15_000_000);
9768         assert_eq!(route.paths.len(), 2);
9769         route.paths.sort_by(|path_a, _| {
9770                 // Sort the path so that the path through nodes[1] comes first
9771                 if path_a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
9772                         core::cmp::Ordering::Less } else { core::cmp::Ordering::Greater }
9773         });
9774
9775         send_along_route_with_secret(&nodes[0], route.clone(), &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 15_000_000, payment_hash, payment_secret);
9776         // nodes[3] has now received a PaymentClaimable event...which it will take some (exorbitant)
9777         // amount of time to respond to.
9778
9779         // Connect some blocks to time out the payment
9780         connect_blocks(&nodes[3], TEST_FINAL_CLTV);
9781         connect_blocks(&nodes[0], TEST_FINAL_CLTV); // To get the same height for sending later
9782
9783         let failed_destinations = vec![
9784                 HTLCDestination::FailedPayment { payment_hash },
9785                 HTLCDestination::FailedPayment { payment_hash },
9786         ];
9787         expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
9788
9789         pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
9790
9791         // nodes[1] now retries one of the two paths...
9792         nodes[0].node.send_payment_with_route(&route, payment_hash,
9793                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9794         check_added_monitors!(nodes[0], 2);
9795
9796         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
9797         assert_eq!(events.len(), 2);
9798         let node_1_msgs = remove_first_msg_event_to_node(&nodes[1].node.get_our_node_id(), &mut events);
9799         pass_along_path(&nodes[0], &[&nodes[1], &nodes[3]], 15_000_000, payment_hash, Some(payment_secret), node_1_msgs, false, None);
9800
9801         // At this point nodes[3] has received one half of the payment, and the user goes to handle
9802         // that PaymentClaimable event they got hours ago and never handled...we should refuse to claim.
9803         nodes[3].node.claim_funds(payment_preimage);
9804         check_added_monitors!(nodes[3], 0);
9805         assert!(nodes[3].node.get_and_clear_pending_msg_events().is_empty());
9806 }
9807
9808 /// The possible events which may trigger a `max_dust_htlc_exposure` breach
9809 #[derive(Clone, Copy, PartialEq)]
9810 enum ExposureEvent {
9811         /// Breach occurs at HTLC forwarding (see `send_htlc`)
9812         AtHTLCForward,
9813         /// Breach occurs at HTLC reception (see `update_add_htlc`)
9814         AtHTLCReception,
9815         /// Breach occurs at outbound update_fee (see `send_update_fee`)
9816         AtUpdateFeeOutbound,
9817 }
9818
9819 fn do_test_max_dust_htlc_exposure(dust_outbound_balance: bool, exposure_breach_event: ExposureEvent, on_holder_tx: bool, multiplier_dust_limit: bool) {
9820         // Test that we properly reject dust HTLC violating our `max_dust_htlc_exposure_msat`
9821         // policy.
9822         //
9823         // At HTLC forward (`send_payment()`), if the sum of the trimmed-to-dust HTLC inbound and
9824         // trimmed-to-dust HTLC outbound balance and this new payment as included on next
9825         // counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll reject the
9826         // update. At HTLC reception (`update_add_htlc()`), if the sum of the trimmed-to-dust HTLC
9827         // inbound and trimmed-to-dust HTLC outbound balance and this new received HTLC as included
9828         // on next counterparty commitment are above our `max_dust_htlc_exposure_msat`, we'll fail
9829         // the update. Note, we return a `temporary_channel_failure` (0x1000 | 7), as the channel
9830         // might be available again for HTLC processing once the dust bandwidth has cleared up.
9831
9832         let chanmon_cfgs = create_chanmon_cfgs(2);
9833         let mut config = test_default_channel_config();
9834         config.channel_config.max_dust_htlc_exposure = if multiplier_dust_limit {
9835                 // Default test fee estimator rate is 253 sat/kw, so we set the multiplier to 5_000_000 / 253
9836                 // to get roughly the same initial value as the default setting when this test was
9837                 // originally written.
9838                 MaxDustHTLCExposure::FeeRateMultiplier(5_000_000 / 253)
9839         } else { MaxDustHTLCExposure::FixedLimitMsat(5_000_000) }; // initial default setting value
9840         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
9841         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(config), None]);
9842         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
9843
9844         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1_000_000, 500_000_000, 42, None, None).unwrap();
9845         let mut open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
9846         open_channel.max_htlc_value_in_flight_msat = 50_000_000;
9847         open_channel.max_accepted_htlcs = 60;
9848         if on_holder_tx {
9849                 open_channel.dust_limit_satoshis = 546;
9850         }
9851         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel);
9852         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
9853         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel);
9854
9855         let channel_type_features = ChannelTypeFeatures::only_static_remote_key();
9856
9857         let (temporary_channel_id, tx, _) = create_funding_transaction(&nodes[0], &nodes[1].node.get_our_node_id(), 1_000_000, 42);
9858
9859         if on_holder_tx {
9860                 let mut node_0_per_peer_lock;
9861                 let mut node_0_peer_state_lock;
9862                 match get_channel_ref!(nodes[0], nodes[1], node_0_per_peer_lock, node_0_peer_state_lock, temporary_channel_id) {
9863                         ChannelPhase::UnfundedOutboundV1(chan) => {
9864                                 chan.context.holder_dust_limit_satoshis = 546;
9865                         },
9866                         _ => panic!("Unexpected ChannelPhase variant"),
9867                 }
9868         }
9869
9870         nodes[0].node.funding_transaction_generated(&temporary_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).unwrap();
9871         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id()));
9872         check_added_monitors!(nodes[1], 1);
9873         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
9874
9875         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id()));
9876         check_added_monitors!(nodes[0], 1);
9877         expect_channel_pending_event(&nodes[0], &nodes[1].node.get_our_node_id());
9878
9879         let (channel_ready, channel_id) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
9880         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &channel_ready);
9881         update_nodes_with_chan_announce(&nodes, 0, 1, &announcement, &as_update, &bs_update);
9882
9883         // Fetch a route in advance as we will be unable to once we're unable to send.
9884         let (mut route, payment_hash, _, payment_secret) =
9885                 get_route_and_payment_hash!(nodes[0], nodes[1], 1000);
9886
9887         let (dust_buffer_feerate, max_dust_htlc_exposure_msat) = {
9888                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
9889                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
9890                 let chan = chan_lock.channel_by_id.get(&channel_id).unwrap();
9891                 (chan.context().get_dust_buffer_feerate(None) as u64,
9892                 chan.context().get_max_dust_htlc_exposure_msat(&LowerBoundedFeeEstimator(nodes[0].fee_estimator)))
9893         };
9894         let dust_outbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_timeout_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9895         let dust_outbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_outbound_htlc_on_holder_tx_msat;
9896
9897         let dust_inbound_htlc_on_holder_tx_msat: u64 = (dust_buffer_feerate * htlc_success_tx_weight(&channel_type_features) / 1000 + open_channel.dust_limit_satoshis - 1) * 1000;
9898         let dust_inbound_htlc_on_holder_tx: u64 = max_dust_htlc_exposure_msat / dust_inbound_htlc_on_holder_tx_msat;
9899
9900         let dust_htlc_on_counterparty_tx: u64 = 4;
9901         let dust_htlc_on_counterparty_tx_msat: u64 = max_dust_htlc_exposure_msat / dust_htlc_on_counterparty_tx;
9902
9903         if on_holder_tx {
9904                 if dust_outbound_balance {
9905                         // Outbound dust threshold: 2223 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9906                         // Outbound dust balance: 4372 sats
9907                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2132 sats
9908                         for _ in 0..dust_outbound_htlc_on_holder_tx {
9909                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_outbound_htlc_on_holder_tx_msat);
9910                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9911                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9912                         }
9913                 } else {
9914                         // Inbound dust threshold: 2324 sats (`dust_buffer_feerate` * HTLC_SUCCESS_TX_WEIGHT / 1000 + holder's `dust_limit_satoshis`)
9915                         // Inbound dust balance: 4372 sats
9916                         // Note, we need sent payment to be above outbound dust threshold on counterparty_tx of 2031 sats
9917                         for _ in 0..dust_inbound_htlc_on_holder_tx {
9918                                 route_payment(&nodes[1], &[&nodes[0]], dust_inbound_htlc_on_holder_tx_msat);
9919                         }
9920                 }
9921         } else {
9922                 if dust_outbound_balance {
9923                         // Outbound dust threshold: 2132 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9924                         // Outbound dust balance: 5000 sats
9925                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9926                                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[0], nodes[1], dust_htlc_on_counterparty_tx_msat);
9927                                 nodes[0].node.send_payment_with_route(&route, payment_hash,
9928                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9929                         }
9930                 } else {
9931                         // Inbound dust threshold: 2031 sats (`dust_buffer_feerate` * HTLC_TIMEOUT_TX_WEIGHT / 1000 + counteparty's `dust_limit_satoshis`)
9932                         // Inbound dust balance: 5000 sats
9933                         for _ in 0..dust_htlc_on_counterparty_tx - 1 {
9934                                 route_payment(&nodes[1], &[&nodes[0]], dust_htlc_on_counterparty_tx_msat);
9935                         }
9936                 }
9937         }
9938
9939         if exposure_breach_event == ExposureEvent::AtHTLCForward {
9940                 route.paths[0].hops.last_mut().unwrap().fee_msat =
9941                         if on_holder_tx { dust_outbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 1 };
9942                 // With default dust exposure: 5000 sats
9943                 if on_holder_tx {
9944                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9945                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9946                                 ), true, APIError::ChannelUnavailable { .. }, {});
9947                 } else {
9948                         unwrap_send_err!(nodes[0].node.send_payment_with_route(&route, payment_hash,
9949                                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)
9950                                 ), true, APIError::ChannelUnavailable { .. }, {});
9951                 }
9952         } else if exposure_breach_event == ExposureEvent::AtHTLCReception {
9953                 let (route, payment_hash, _, payment_secret) = get_route_and_payment_hash!(nodes[1], nodes[0], if on_holder_tx { dust_inbound_htlc_on_holder_tx_msat } else { dust_htlc_on_counterparty_tx_msat + 4 });
9954                 nodes[1].node.send_payment_with_route(&route, payment_hash,
9955                         RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9956                 check_added_monitors!(nodes[1], 1);
9957                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
9958                 assert_eq!(events.len(), 1);
9959                 let payment_event = SendEvent::from_event(events.remove(0));
9960                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
9961                 // With default dust exposure: 5000 sats
9962                 if on_holder_tx {
9963                         // Outbound dust balance: 6399 sats
9964                         let dust_inbound_overflow = dust_inbound_htlc_on_holder_tx_msat * (dust_inbound_htlc_on_holder_tx + 1);
9965                         let dust_outbound_overflow = dust_outbound_htlc_on_holder_tx_msat * dust_outbound_htlc_on_holder_tx + dust_inbound_htlc_on_holder_tx_msat;
9966                         nodes[0].logger.assert_log("lightning::ln::channel", format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on holder commitment tx", if dust_outbound_balance { dust_outbound_overflow } else { dust_inbound_overflow }, max_dust_htlc_exposure_msat), 1);
9967                 } else {
9968                         // Outbound dust balance: 5200 sats
9969                         nodes[0].logger.assert_log("lightning::ln::channel",
9970                                 format!("Cannot accept value that would put our exposure to dust HTLCs at {} over the limit {} on counterparty commitment tx",
9971                                         dust_htlc_on_counterparty_tx_msat * (dust_htlc_on_counterparty_tx - 1) + dust_htlc_on_counterparty_tx_msat + 4,
9972                                         max_dust_htlc_exposure_msat), 1);
9973                 }
9974         } else if exposure_breach_event == ExposureEvent::AtUpdateFeeOutbound {
9975                 route.paths[0].hops.last_mut().unwrap().fee_msat = 2_500_000;
9976                 // For the multiplier dust exposure limit, since it scales with feerate,
9977                 // we need to add a lot of HTLCs that will become dust at the new feerate
9978                 // to cross the threshold.
9979                 for _ in 0..20 {
9980                         let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[1], Some(1_000), None);
9981                         nodes[0].node.send_payment_with_route(&route, payment_hash,
9982                                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
9983                 }
9984                 {
9985                         let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
9986                         *feerate_lock = *feerate_lock * 10;
9987                 }
9988                 nodes[0].node.timer_tick_occurred();
9989                 check_added_monitors!(nodes[0], 1);
9990                 nodes[0].logger.assert_log_contains("lightning::ln::channel", "Cannot afford to send new feerate at 2530 without infringing max dust htlc exposure", 1);
9991         }
9992
9993         let _ = nodes[0].node.get_and_clear_pending_msg_events();
9994         let mut added_monitors = nodes[0].chain_monitor.added_monitors.lock().unwrap();
9995         added_monitors.clear();
9996 }
9997
9998 fn do_test_max_dust_htlc_exposure_by_threshold_type(multiplier_dust_limit: bool) {
9999         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10000         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, true, multiplier_dust_limit);
10001         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10002         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10003         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10004         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, false, multiplier_dust_limit);
10005         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtHTLCReception, true, multiplier_dust_limit);
10006         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtHTLCForward, false, multiplier_dust_limit);
10007         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10008         do_test_max_dust_htlc_exposure(true, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10009         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, false, multiplier_dust_limit);
10010         do_test_max_dust_htlc_exposure(false, ExposureEvent::AtUpdateFeeOutbound, true, multiplier_dust_limit);
10011 }
10012
10013 #[test]
10014 fn test_max_dust_htlc_exposure() {
10015         do_test_max_dust_htlc_exposure_by_threshold_type(false);
10016         do_test_max_dust_htlc_exposure_by_threshold_type(true);
10017 }
10018
10019 #[test]
10020 fn test_non_final_funding_tx() {
10021         let chanmon_cfgs = create_chanmon_cfgs(2);
10022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10024         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10025
10026         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10027         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10028         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10029         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10030         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10031
10032         let best_height = nodes[0].node.best_block.read().unwrap().height();
10033
10034         let chan_id = *nodes[0].network_chan_count.borrow();
10035         let events = nodes[0].node.get_and_clear_pending_events();
10036         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[&[1]]) };
10037         assert_eq!(events.len(), 1);
10038         let mut tx = match events[0] {
10039                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10040                         // Timelock the transaction _beyond_ the best client height + 1.
10041                         Transaction { version: chan_id as i32, lock_time: LockTime::from_height(best_height + 2).unwrap(), input: vec![input], output: vec![TxOut {
10042                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10043                         }]}
10044                 },
10045                 _ => panic!("Unexpected event"),
10046         };
10047         // Transaction should fail as it's evaluated as non-final for propagation.
10048         match nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()) {
10049                 Err(APIError::APIMisuseError { err }) => {
10050                         assert_eq!(format!("Funding transaction absolute timelock is non-final"), err);
10051                 },
10052                 _ => panic!()
10053         }
10054         let events = nodes[0].node.get_and_clear_pending_events();
10055         assert_eq!(events.len(), 1);
10056         match events[0] {
10057                 Event::ChannelClosed { channel_id, .. } => {
10058                         assert_eq!(channel_id, temp_channel_id);
10059                 },
10060                 _ => panic!("Unexpected event"),
10061         }
10062 }
10063
10064 #[test]
10065 fn test_non_final_funding_tx_within_headroom() {
10066         let chanmon_cfgs = create_chanmon_cfgs(2);
10067         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10068         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10069         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10070
10071         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10072         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10073         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10074         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10075         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10076
10077         let best_height = nodes[0].node.best_block.read().unwrap().height();
10078
10079         let chan_id = *nodes[0].network_chan_count.borrow();
10080         let events = nodes[0].node.get_and_clear_pending_events();
10081         let input = TxIn { previous_output: BitcoinOutPoint::null(), script_sig: bitcoin::ScriptBuf::new(), sequence: Sequence(1), witness: Witness::from_slice(&[[1]]) };
10082         assert_eq!(events.len(), 1);
10083         let mut tx = match events[0] {
10084                 Event::FundingGenerationReady { ref channel_value_satoshis, ref output_script, .. } => {
10085                         // Timelock the transaction within a +1 headroom from the best block.
10086                         Transaction { version: chan_id as i32, lock_time: LockTime::from_consensus(best_height + 1), input: vec![input], output: vec![TxOut {
10087                                 value: *channel_value_satoshis, script_pubkey: output_script.clone(),
10088                         }]}
10089                 },
10090                 _ => panic!("Unexpected event"),
10091         };
10092
10093         // Transaction should be accepted if it's in a +1 headroom from best block.
10094         assert!(nodes[0].node.funding_transaction_generated(&temp_channel_id, &nodes[1].node.get_our_node_id(), tx.clone()).is_ok());
10095         get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
10096 }
10097
10098 #[test]
10099 fn accept_busted_but_better_fee() {
10100         // If a peer sends us a fee update that is too low, but higher than our previous channel
10101         // feerate, we should accept it. In the future we may want to consider closing the channel
10102         // later, but for now we only accept the update.
10103         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10104         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10105         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10106         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10107
10108         create_chan_between_nodes(&nodes[0], &nodes[1]);
10109
10110         // Set nodes[1] to expect 5,000 sat/kW.
10111         {
10112                 let mut feerate_lock = chanmon_cfgs[1].fee_estimator.sat_per_kw.lock().unwrap();
10113                 *feerate_lock = 5000;
10114         }
10115
10116         // If nodes[0] increases their feerate, even if its not enough, nodes[1] should accept it.
10117         {
10118                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10119                 *feerate_lock = 1000;
10120         }
10121         nodes[0].node.timer_tick_occurred();
10122         check_added_monitors!(nodes[0], 1);
10123
10124         let events = nodes[0].node.get_and_clear_pending_msg_events();
10125         assert_eq!(events.len(), 1);
10126         match events[0] {
10127                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10128                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10129                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10130                 },
10131                 _ => panic!("Unexpected event"),
10132         };
10133
10134         // If nodes[0] increases their feerate further, even if its not enough, nodes[1] should accept
10135         // it.
10136         {
10137                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10138                 *feerate_lock = 2000;
10139         }
10140         nodes[0].node.timer_tick_occurred();
10141         check_added_monitors!(nodes[0], 1);
10142
10143         let events = nodes[0].node.get_and_clear_pending_msg_events();
10144         assert_eq!(events.len(), 1);
10145         match events[0] {
10146                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
10147                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10148                         commitment_signed_dance!(nodes[1], nodes[0], commitment_signed, false);
10149                 },
10150                 _ => panic!("Unexpected event"),
10151         };
10152
10153         // However, if nodes[0] decreases their feerate, nodes[1] should reject it and close the
10154         // channel.
10155         {
10156                 let mut feerate_lock = chanmon_cfgs[0].fee_estimator.sat_per_kw.lock().unwrap();
10157                 *feerate_lock = 1000;
10158         }
10159         nodes[0].node.timer_tick_occurred();
10160         check_added_monitors!(nodes[0], 1);
10161
10162         let events = nodes[0].node.get_and_clear_pending_msg_events();
10163         assert_eq!(events.len(), 1);
10164         match events[0] {
10165                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
10166                         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_fee.as_ref().unwrap());
10167                         check_closed_event!(nodes[1], 1, ClosureReason::ProcessingError {
10168                                 err: "Peer's feerate much too low. Actual: 1000. Our expected lower limit: 5000".to_owned() },
10169                                 [nodes[0].node.get_our_node_id()], 100000);
10170                         check_closed_broadcast!(nodes[1], true);
10171                         check_added_monitors!(nodes[1], 1);
10172                 },
10173                 _ => panic!("Unexpected event"),
10174         };
10175 }
10176
10177 fn do_payment_with_custom_min_final_cltv_expiry(valid_delta: bool, use_user_hash: bool) {
10178         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10179         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10180         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10181         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10182         let min_final_cltv_expiry_delta = 120;
10183         let final_cltv_expiry_delta = if valid_delta { min_final_cltv_expiry_delta + 2 } else {
10184                 min_final_cltv_expiry_delta - 2 };
10185         let recv_value = 100_000;
10186
10187         create_chan_between_nodes(&nodes[0], &nodes[1]);
10188
10189         let payment_parameters = PaymentParameters::from_node_id(nodes[1].node.get_our_node_id(), final_cltv_expiry_delta as u32);
10190         let (payment_hash, payment_preimage, payment_secret) = if use_user_hash {
10191                 let (payment_preimage, payment_hash, payment_secret) = get_payment_preimage_hash!(nodes[1],
10192                         Some(recv_value), Some(min_final_cltv_expiry_delta));
10193                 (payment_hash, payment_preimage, payment_secret)
10194         } else {
10195                 let (payment_hash, payment_secret) = nodes[1].node.create_inbound_payment(Some(recv_value), 7200, Some(min_final_cltv_expiry_delta)).unwrap();
10196                 (payment_hash, nodes[1].node.get_payment_preimage(payment_hash, payment_secret).unwrap(), payment_secret)
10197         };
10198         let route = get_route!(nodes[0], payment_parameters, recv_value).unwrap();
10199         nodes[0].node.send_payment_with_route(&route, payment_hash,
10200                 RecipientOnionFields::secret_only(payment_secret), PaymentId(payment_hash.0)).unwrap();
10201         check_added_monitors!(nodes[0], 1);
10202         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
10203         assert_eq!(events.len(), 1);
10204         let mut payment_event = SendEvent::from_event(events.pop().unwrap());
10205         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
10206         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
10207         expect_pending_htlcs_forwardable!(nodes[1]);
10208
10209         if valid_delta {
10210                 expect_payment_claimable!(nodes[1], payment_hash, payment_secret, recv_value, if use_user_hash {
10211                         None } else { Some(payment_preimage) }, nodes[1].node.get_our_node_id());
10212
10213                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
10214         } else {
10215                 expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[1], vec![HTLCDestination::FailedPayment { payment_hash }]);
10216
10217                 check_added_monitors!(nodes[1], 1);
10218
10219                 let fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
10220                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_updates.update_fail_htlcs[0]);
10221                 commitment_signed_dance!(nodes[0], nodes[1], fail_updates.commitment_signed, false, true);
10222
10223                 expect_payment_failed!(nodes[0], payment_hash, true);
10224         }
10225 }
10226
10227 #[test]
10228 fn test_payment_with_custom_min_cltv_expiry_delta() {
10229         do_payment_with_custom_min_final_cltv_expiry(false, false);
10230         do_payment_with_custom_min_final_cltv_expiry(false, true);
10231         do_payment_with_custom_min_final_cltv_expiry(true, false);
10232         do_payment_with_custom_min_final_cltv_expiry(true, true);
10233 }
10234
10235 #[test]
10236 fn test_disconnects_peer_awaiting_response_ticks() {
10237         // Tests that nodes which are awaiting on a response critical for channel responsiveness
10238         // disconnect their counterparty after `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10239         let mut chanmon_cfgs = create_chanmon_cfgs(2);
10240         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10241         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10242         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10243
10244         // Asserts a disconnect event is queued to the user.
10245         let check_disconnect_event = |node: &Node, should_disconnect: bool| {
10246                 let disconnect_event = node.node.get_and_clear_pending_msg_events().iter().find_map(|event|
10247                         if let MessageSendEvent::HandleError { action, .. } = event {
10248                                 if let msgs::ErrorAction::DisconnectPeerWithWarning { .. } = action {
10249                                         Some(())
10250                                 } else {
10251                                         None
10252                                 }
10253                         } else {
10254                                 None
10255                         }
10256                 );
10257                 assert_eq!(disconnect_event.is_some(), should_disconnect);
10258         };
10259
10260         // Fires timer ticks ensuring we only attempt to disconnect peers after reaching
10261         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10262         let check_disconnect = |node: &Node| {
10263                 // No disconnect without any timer ticks.
10264                 check_disconnect_event(node, false);
10265
10266                 // No disconnect with 1 timer tick less than required.
10267                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS - 1 {
10268                         node.node.timer_tick_occurred();
10269                         check_disconnect_event(node, false);
10270                 }
10271
10272                 // Disconnect after reaching the required ticks.
10273                 node.node.timer_tick_occurred();
10274                 check_disconnect_event(node, true);
10275
10276                 // Disconnect again on the next tick if the peer hasn't been disconnected yet.
10277                 node.node.timer_tick_occurred();
10278                 check_disconnect_event(node, true);
10279         };
10280
10281         create_chan_between_nodes(&nodes[0], &nodes[1]);
10282
10283         // We'll start by performing a fee update with Alice (nodes[0]) on the channel.
10284         *nodes[0].fee_estimator.sat_per_kw.lock().unwrap() *= 2;
10285         nodes[0].node.timer_tick_occurred();
10286         check_added_monitors!(&nodes[0], 1);
10287         let alice_fee_update = get_htlc_update_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10288         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), alice_fee_update.update_fee.as_ref().unwrap());
10289         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &alice_fee_update.commitment_signed);
10290         check_added_monitors!(&nodes[1], 1);
10291
10292         // This will prompt Bob (nodes[1]) to respond with his `CommitmentSigned` and `RevokeAndACK`.
10293         let (bob_revoke_and_ack, bob_commitment_signed) = get_revoke_commit_msgs!(&nodes[1], nodes[0].node.get_our_node_id());
10294         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bob_revoke_and_ack);
10295         check_added_monitors!(&nodes[0], 1);
10296         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bob_commitment_signed);
10297         check_added_monitors(&nodes[0], 1);
10298
10299         // Alice then needs to send her final `RevokeAndACK` to complete the commitment dance. We
10300         // pretend Bob hasn't received the message and check whether he'll disconnect Alice after
10301         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10302         let alice_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
10303         check_disconnect(&nodes[1]);
10304
10305         // Now, we'll reconnect them to test awaiting a `ChannelReestablish` message.
10306         //
10307         // Note that since the commitment dance didn't complete above, Alice is expected to resend her
10308         // final `RevokeAndACK` to Bob to complete it.
10309         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id());
10310         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10311         let bob_init = msgs::Init {
10312                 features: nodes[1].node.init_features(), networks: None, remote_network_address: None
10313         };
10314         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &bob_init, true).unwrap();
10315         let alice_init = msgs::Init {
10316                 features: nodes[0].node.init_features(), networks: None, remote_network_address: None
10317         };
10318         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &alice_init, true).unwrap();
10319
10320         // Upon reconnection, Alice sends her `ChannelReestablish` to Bob. Alice, however, hasn't
10321         // received Bob's yet, so she should disconnect him after reaching
10322         // `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10323         let alice_channel_reestablish = get_event_msg!(
10324                 nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id()
10325         );
10326         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &alice_channel_reestablish);
10327         check_disconnect(&nodes[0]);
10328
10329         // Bob now sends his `ChannelReestablish` to Alice to resume the channel and consider it "live".
10330         let bob_channel_reestablish = nodes[1].node.get_and_clear_pending_msg_events().iter().find_map(|event|
10331                 if let MessageSendEvent::SendChannelReestablish { node_id, msg } = event {
10332                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
10333                         Some(msg.clone())
10334                 } else {
10335                         None
10336                 }
10337         ).unwrap();
10338         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &bob_channel_reestablish);
10339
10340         // Sanity check that Alice won't disconnect Bob since she's no longer waiting for any messages.
10341         for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10342                 nodes[0].node.timer_tick_occurred();
10343                 check_disconnect_event(&nodes[0], false);
10344         }
10345
10346         // However, Bob is still waiting on Alice's `RevokeAndACK`, so he should disconnect her after
10347         // reaching `DISCONNECT_PEER_AWAITING_RESPONSE_TICKS`.
10348         check_disconnect(&nodes[1]);
10349
10350         // Finally, have Bob process the last message.
10351         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &alice_revoke_and_ack);
10352         check_added_monitors(&nodes[1], 1);
10353
10354         // At this point, neither node should attempt to disconnect each other, since they aren't
10355         // waiting on any messages.
10356         for node in &nodes {
10357                 for _ in 0..DISCONNECT_PEER_AWAITING_RESPONSE_TICKS {
10358                         node.node.timer_tick_occurred();
10359                         check_disconnect_event(node, false);
10360                 }
10361         }
10362 }
10363
10364 #[test]
10365 fn test_remove_expired_outbound_unfunded_channels() {
10366         let chanmon_cfgs = create_chanmon_cfgs(2);
10367         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10368         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10369         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10370
10371         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10372         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10373         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10374         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10375         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10376
10377         let events = nodes[0].node.get_and_clear_pending_events();
10378         assert_eq!(events.len(), 1);
10379         match events[0] {
10380                 Event::FundingGenerationReady { .. } => (),
10381                 _ => panic!("Unexpected event"),
10382         };
10383
10384         // Asserts the outbound channel has been removed from a nodes[0]'s peer state map.
10385         let check_outbound_channel_existence = |should_exist: bool| {
10386                 let per_peer_state = nodes[0].node.per_peer_state.read().unwrap();
10387                 let chan_lock = per_peer_state.get(&nodes[1].node.get_our_node_id()).unwrap().lock().unwrap();
10388                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10389         };
10390
10391         // Channel should exist without any timer ticks.
10392         check_outbound_channel_existence(true);
10393
10394         // Channel should exist with 1 timer tick less than required.
10395         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10396                 nodes[0].node.timer_tick_occurred();
10397                 check_outbound_channel_existence(true)
10398         }
10399
10400         // Remove channel after reaching the required ticks.
10401         nodes[0].node.timer_tick_occurred();
10402         check_outbound_channel_existence(false);
10403
10404         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10405         assert_eq!(msg_events.len(), 1);
10406         match msg_events[0] {
10407                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10408                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10409                 },
10410                 _ => panic!("Unexpected event"),
10411         }
10412         check_closed_event(&nodes[0], 1, ClosureReason::HolderForceClosed, false, &[nodes[1].node.get_our_node_id()], 100000);
10413 }
10414
10415 #[test]
10416 fn test_remove_expired_inbound_unfunded_channels() {
10417         let chanmon_cfgs = create_chanmon_cfgs(2);
10418         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10419         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
10420         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10421
10422         let temp_channel_id = nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100_000, 0, 42, None, None).unwrap();
10423         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
10424         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &open_channel_message);
10425         let accept_channel_message = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
10426         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), &accept_channel_message);
10427
10428         let events = nodes[0].node.get_and_clear_pending_events();
10429         assert_eq!(events.len(), 1);
10430         match events[0] {
10431                 Event::FundingGenerationReady { .. } => (),
10432                 _ => panic!("Unexpected event"),
10433         };
10434
10435         // Asserts the inbound channel has been removed from a nodes[1]'s peer state map.
10436         let check_inbound_channel_existence = |should_exist: bool| {
10437                 let per_peer_state = nodes[1].node.per_peer_state.read().unwrap();
10438                 let chan_lock = per_peer_state.get(&nodes[0].node.get_our_node_id()).unwrap().lock().unwrap();
10439                 assert_eq!(chan_lock.channel_by_id.contains_key(&temp_channel_id), should_exist);
10440         };
10441
10442         // Channel should exist without any timer ticks.
10443         check_inbound_channel_existence(true);
10444
10445         // Channel should exist with 1 timer tick less than required.
10446         for _ in 0..UNFUNDED_CHANNEL_AGE_LIMIT_TICKS - 1 {
10447                 nodes[1].node.timer_tick_occurred();
10448                 check_inbound_channel_existence(true)
10449         }
10450
10451         // Remove channel after reaching the required ticks.
10452         nodes[1].node.timer_tick_occurred();
10453         check_inbound_channel_existence(false);
10454
10455         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
10456         assert_eq!(msg_events.len(), 1);
10457         match msg_events[0] {
10458                 MessageSendEvent::HandleError { action: ErrorAction::SendErrorMessage { ref msg }, node_id: _ } => {
10459                         assert_eq!(msg.data, "Force-closing pending channel due to timeout awaiting establishment handshake");
10460                 },
10461                 _ => panic!("Unexpected event"),
10462         }
10463         check_closed_event(&nodes[1], 1, ClosureReason::HolderForceClosed, false, &[nodes[0].node.get_our_node_id()], 100000);
10464 }
10465
10466 fn do_test_multi_post_event_actions(do_reload: bool) {
10467         // Tests handling multiple post-Event actions at once.
10468         // There is specific code in ChannelManager to handle channels where multiple post-Event
10469         // `ChannelMonitorUpdates` are pending at once. This test exercises that code.
10470         //
10471         // Specifically, we test calling `get_and_clear_pending_events` while there are two
10472         // PaymentSents from different channels and one channel has two pending `ChannelMonitorUpdate`s
10473         // - one from an RAA and one from an inbound commitment_signed.
10474         let chanmon_cfgs = create_chanmon_cfgs(3);
10475         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10476         let (persister, chain_monitor);
10477         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10478         let nodes_0_deserialized;
10479         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10480
10481         let chan_id = create_announced_chan_between_nodes(&nodes, 0, 1).2;
10482         let chan_id_2 = create_announced_chan_between_nodes(&nodes, 0, 2).2;
10483
10484         send_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10485         send_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10486
10487         let (our_payment_preimage, our_payment_hash, ..) = route_payment(&nodes[0], &[&nodes[1]], 1_000_000);
10488         let (payment_preimage_2, payment_hash_2, ..) = route_payment(&nodes[0], &[&nodes[2]], 1_000_000);
10489
10490         nodes[1].node.claim_funds(our_payment_preimage);
10491         check_added_monitors!(nodes[1], 1);
10492         expect_payment_claimed!(nodes[1], our_payment_hash, 1_000_000);
10493
10494         nodes[2].node.claim_funds(payment_preimage_2);
10495         check_added_monitors!(nodes[2], 1);
10496         expect_payment_claimed!(nodes[2], payment_hash_2, 1_000_000);
10497
10498         for dest in &[1, 2] {
10499                 let htlc_fulfill_updates = get_htlc_update_msgs!(nodes[*dest], nodes[0].node.get_our_node_id());
10500                 nodes[0].node.handle_update_fulfill_htlc(&nodes[*dest].node.get_our_node_id(), &htlc_fulfill_updates.update_fulfill_htlcs[0]);
10501                 commitment_signed_dance!(nodes[0], nodes[*dest], htlc_fulfill_updates.commitment_signed, false);
10502                 check_added_monitors(&nodes[0], 0);
10503         }
10504
10505         let (route, payment_hash_3, _, payment_secret_3) =
10506                 get_route_and_payment_hash!(nodes[1], nodes[0], 100_000);
10507         let payment_id = PaymentId(payment_hash_3.0);
10508         nodes[1].node.send_payment_with_route(&route, payment_hash_3,
10509                 RecipientOnionFields::secret_only(payment_secret_3), payment_id).unwrap();
10510         check_added_monitors(&nodes[1], 1);
10511
10512         let send_event = SendEvent::from_node(&nodes[1]);
10513         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_event.msgs[0]);
10514         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_event.commitment_msg);
10515         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
10516
10517         if do_reload {
10518                 let nodes_0_serialized = nodes[0].node.encode();
10519                 let chan_0_monitor_serialized = get_monitor!(nodes[0], chan_id).encode();
10520                 let chan_1_monitor_serialized = get_monitor!(nodes[0], chan_id_2).encode();
10521                 reload_node!(nodes[0], test_default_channel_config(), &nodes_0_serialized, &[&chan_0_monitor_serialized, &chan_1_monitor_serialized], persister, chain_monitor, nodes_0_deserialized);
10522
10523                 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10524                 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id());
10525
10526                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[1]));
10527                 reconnect_nodes(ReconnectArgs::new(&nodes[0], &nodes[2]));
10528         }
10529
10530         let events = nodes[0].node.get_and_clear_pending_events();
10531         assert_eq!(events.len(), 4);
10532         if let Event::PaymentSent { payment_preimage, .. } = events[0] {
10533                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10534         } else { panic!(); }
10535         if let Event::PaymentSent { payment_preimage, .. } = events[1] {
10536                 assert!(payment_preimage == our_payment_preimage || payment_preimage == payment_preimage_2);
10537         } else { panic!(); }
10538         if let Event::PaymentPathSuccessful { .. } = events[2] {} else { panic!(); }
10539         if let Event::PaymentPathSuccessful { .. } = events[3] {} else { panic!(); }
10540
10541         // After the events are processed, the ChannelMonitorUpdates will be released and, upon their
10542         // completion, we'll respond to nodes[1] with an RAA + CS.
10543         get_revoke_commit_msgs(&nodes[0], &nodes[1].node.get_our_node_id());
10544         check_added_monitors(&nodes[0], 3);
10545 }
10546
10547 #[test]
10548 fn test_multi_post_event_actions() {
10549         do_test_multi_post_event_actions(true);
10550         do_test_multi_post_event_actions(false);
10551 }
10552
10553 #[test]
10554 fn test_batch_channel_open() {
10555         let chanmon_cfgs = create_chanmon_cfgs(3);
10556         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10557         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10558         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10559
10560         // Initiate channel opening and create the batch channel funding transaction.
10561         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10562                 (&nodes[1], 100_000, 0, 42, None),
10563                 (&nodes[2], 200_000, 0, 43, None),
10564         ]);
10565
10566         // Go through the funding_created and funding_signed flow with node 1.
10567         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10568         check_added_monitors(&nodes[1], 1);
10569         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10570
10571         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10572         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10573         check_added_monitors(&nodes[0], 1);
10574
10575         // The transaction should not have been broadcast before all channels are ready.
10576         assert_eq!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 0);
10577
10578         // Go through the funding_created and funding_signed flow with node 2.
10579         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10580         check_added_monitors(&nodes[2], 1);
10581         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10582
10583         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10584         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10585         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10586         check_added_monitors(&nodes[0], 1);
10587
10588         // The transaction should not have been broadcast before persisting all monitors has been
10589         // completed.
10590         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10591         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
10592
10593         // Complete the persistence of the monitor.
10594         nodes[0].chain_monitor.complete_sole_pending_chan_update(
10595                 &OutPoint { txid: tx.txid(), index: 1 }.to_channel_id()
10596         );
10597         let events = nodes[0].node.get_and_clear_pending_events();
10598
10599         // The transaction should only have been broadcast now.
10600         let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10601         assert_eq!(broadcasted_txs.len(), 1);
10602         assert_eq!(broadcasted_txs[0], tx);
10603
10604         assert_eq!(events.len(), 2);
10605         assert!(events.iter().any(|e| matches!(
10606                 *e,
10607                 crate::events::Event::ChannelPending {
10608                         ref counterparty_node_id,
10609                         ..
10610                 } if counterparty_node_id == &nodes[1].node.get_our_node_id(),
10611         )));
10612         assert!(events.iter().any(|e| matches!(
10613                 *e,
10614                 crate::events::Event::ChannelPending {
10615                         ref counterparty_node_id,
10616                         ..
10617                 } if counterparty_node_id == &nodes[2].node.get_our_node_id(),
10618         )));
10619 }
10620
10621 #[test]
10622 fn test_disconnect_in_funding_batch() {
10623         let chanmon_cfgs = create_chanmon_cfgs(3);
10624         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10625         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10626         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10627
10628         // Initiate channel opening and create the batch channel funding transaction.
10629         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10630                 (&nodes[1], 100_000, 0, 42, None),
10631                 (&nodes[2], 200_000, 0, 43, None),
10632         ]);
10633
10634         // Go through the funding_created and funding_signed flow with node 1.
10635         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10636         check_added_monitors(&nodes[1], 1);
10637         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10638
10639         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10640         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10641         check_added_monitors(&nodes[0], 1);
10642
10643         // The transaction should not have been broadcast before all channels are ready.
10644         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10645
10646         // The remaining peer in the batch disconnects.
10647         nodes[0].node.peer_disconnected(&nodes[2].node.get_our_node_id());
10648
10649         // The channels in the batch will close immediately.
10650         let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10651         let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10652         check_closed_events(&nodes[0], &[
10653                 ExpectedCloseEvent {
10654                         channel_id: Some(channel_id_1),
10655                         discard_funding: true,
10656                         ..Default::default()
10657                 },
10658                 ExpectedCloseEvent {
10659                         channel_id: Some(channel_id_2),
10660                         discard_funding: true,
10661                         ..Default::default()
10662                 },
10663         ]);
10664
10665         // The monitor should become closed.
10666         check_added_monitors(&nodes[0], 1);
10667         {
10668                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10669                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10670                 assert_eq!(monitor_updates_1.len(), 1);
10671                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10672         }
10673
10674         // The funding transaction should not have been broadcast, and therefore, we don't need
10675         // to broadcast a force-close transaction for the closed monitor.
10676         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10677
10678         // Ensure the channels don't exist anymore.
10679         assert!(nodes[0].node.list_channels().is_empty());
10680 }
10681
10682 #[test]
10683 fn test_batch_funding_close_after_funding_signed() {
10684         let chanmon_cfgs = create_chanmon_cfgs(3);
10685         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
10686         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
10687         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
10688
10689         // Initiate channel opening and create the batch channel funding transaction.
10690         let (tx, funding_created_msgs) = create_batch_channel_funding(&nodes[0], &[
10691                 (&nodes[1], 100_000, 0, 42, None),
10692                 (&nodes[2], 200_000, 0, 43, None),
10693         ]);
10694
10695         // Go through the funding_created and funding_signed flow with node 1.
10696         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[0]);
10697         check_added_monitors(&nodes[1], 1);
10698         expect_channel_pending_event(&nodes[1], &nodes[0].node.get_our_node_id());
10699
10700         let funding_signed_msg = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10701         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed_msg);
10702         check_added_monitors(&nodes[0], 1);
10703
10704         // Go through the funding_created and funding_signed flow with node 2.
10705         nodes[2].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created_msgs[1]);
10706         check_added_monitors(&nodes[2], 1);
10707         expect_channel_pending_event(&nodes[2], &nodes[0].node.get_our_node_id());
10708
10709         let funding_signed_msg = get_event_msg!(nodes[2], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
10710         chanmon_cfgs[0].persister.set_update_ret(ChannelMonitorUpdateStatus::InProgress);
10711         nodes[0].node.handle_funding_signed(&nodes[2].node.get_our_node_id(), &funding_signed_msg);
10712         check_added_monitors(&nodes[0], 1);
10713
10714         // The transaction should not have been broadcast before all channels are ready.
10715         assert_eq!(nodes[0].tx_broadcaster.txn_broadcast().len(), 0);
10716
10717         // Force-close the channel for which we've completed the initial monitor.
10718         let channel_id_1 = OutPoint { txid: tx.txid(), index: 0 }.to_channel_id();
10719         let channel_id_2 = OutPoint { txid: tx.txid(), index: 1 }.to_channel_id();
10720         nodes[0].node.force_close_broadcasting_latest_txn(&channel_id_1, &nodes[1].node.get_our_node_id()).unwrap();
10721         check_added_monitors(&nodes[0], 2);
10722         {
10723                 let mut monitor_updates = nodes[0].chain_monitor.monitor_updates.lock().unwrap();
10724                 let monitor_updates_1 = monitor_updates.get(&channel_id_1).unwrap();
10725                 assert_eq!(monitor_updates_1.len(), 1);
10726                 assert_eq!(monitor_updates_1[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10727                 let monitor_updates_2 = monitor_updates.get(&channel_id_2).unwrap();
10728                 assert_eq!(monitor_updates_2.len(), 1);
10729                 assert_eq!(monitor_updates_2[0].update_id, CLOSED_CHANNEL_UPDATE_ID);
10730         }
10731         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
10732         match msg_events[0] {
10733                 MessageSendEvent::HandleError { .. } => (),
10734                 _ => panic!("Unexpected message."),
10735         }
10736
10737         // We broadcast the commitment transaction as part of the force-close.
10738         {
10739                 let broadcasted_txs = nodes[0].tx_broadcaster.txn_broadcast();
10740                 assert_eq!(broadcasted_txs.len(), 1);
10741                 assert!(broadcasted_txs[0].txid() != tx.txid());
10742                 assert_eq!(broadcasted_txs[0].input.len(), 1);
10743                 assert_eq!(broadcasted_txs[0].input[0].previous_output.txid, tx.txid());
10744         }
10745
10746         // All channels in the batch should close immediately.
10747         check_closed_events(&nodes[0], &[
10748                 ExpectedCloseEvent {
10749                         channel_id: Some(channel_id_1),
10750                         discard_funding: true,
10751                         ..Default::default()
10752                 },
10753                 ExpectedCloseEvent {
10754                         channel_id: Some(channel_id_2),
10755                         discard_funding: true,
10756                         ..Default::default()
10757                 },
10758         ]);
10759
10760         // Ensure the channels don't exist anymore.
10761         assert!(nodes[0].node.list_channels().is_empty());
10762 }
10763
10764 fn do_test_funding_and_commitment_tx_confirm_same_block(confirm_remote_commitment: bool) {
10765         // Tests that a node will forget the channel (when it only requires 1 confirmation) if the
10766         // funding and commitment transaction confirm in the same block.
10767         let chanmon_cfgs = create_chanmon_cfgs(2);
10768         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
10769         let mut min_depth_1_block_cfg = test_default_channel_config();
10770         min_depth_1_block_cfg.channel_handshake_config.minimum_depth = 1;
10771         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(min_depth_1_block_cfg), Some(min_depth_1_block_cfg)]);
10772         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
10773
10774         let funding_tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 1_000_000, 0);
10775         let chan_id = chain::transaction::OutPoint { txid: funding_tx.txid(), index: 0 }.to_channel_id();
10776
10777         assert_eq!(nodes[0].node.list_channels().len(), 1);
10778         assert_eq!(nodes[1].node.list_channels().len(), 1);
10779
10780         let (closing_node, other_node) = if confirm_remote_commitment {
10781                 (&nodes[1], &nodes[0])
10782         } else {
10783                 (&nodes[0], &nodes[1])
10784         };
10785
10786         closing_node.node.force_close_broadcasting_latest_txn(&chan_id, &other_node.node.get_our_node_id()).unwrap();
10787         let mut msg_events = closing_node.node.get_and_clear_pending_msg_events();
10788         assert_eq!(msg_events.len(), 1);
10789         match msg_events.pop().unwrap() {
10790                 MessageSendEvent::HandleError { action: msgs::ErrorAction::DisconnectPeer { .. }, .. } => {},
10791                 _ => panic!("Unexpected event"),
10792         }
10793         check_added_monitors(closing_node, 1);
10794         check_closed_event(closing_node, 1, ClosureReason::HolderForceClosed, false, &[other_node.node.get_our_node_id()], 1_000_000);
10795
10796         let commitment_tx = {
10797                 let mut txn = closing_node.tx_broadcaster.txn_broadcast();
10798                 assert_eq!(txn.len(), 1);
10799                 let commitment_tx = txn.pop().unwrap();
10800                 check_spends!(commitment_tx, funding_tx);
10801                 commitment_tx
10802         };
10803
10804         mine_transactions(&nodes[0], &[&funding_tx, &commitment_tx]);
10805         mine_transactions(&nodes[1], &[&funding_tx, &commitment_tx]);
10806
10807         check_closed_broadcast(other_node, 1, true);
10808         check_added_monitors(other_node, 1);
10809         check_closed_event(other_node, 1, ClosureReason::CommitmentTxConfirmed, false, &[closing_node.node.get_our_node_id()], 1_000_000);
10810
10811         assert!(nodes[0].node.list_channels().is_empty());
10812         assert!(nodes[1].node.list_channels().is_empty());
10813 }
10814
10815 #[test]
10816 fn test_funding_and_commitment_tx_confirm_same_block() {
10817         do_test_funding_and_commitment_tx_confirm_same_block(false);
10818         do_test_funding_and_commitment_tx_confirm_same_block(true);
10819 }